<?php
session_start();
require_once "config.php";

/* PHPMailer */
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

$message = "";
$redirect = false;

/* RESET SESSION ON FRESH LOAD */
if (!isset($_POST['send_otp']) && !isset($_POST['verify_reset']) && !isset($_POST['resend_otp'])) {
    unset($_SESSION['otp']);
    unset($_SESSION['reset_email']);
    unset($_SESSION['otp_time']);
}

/* =========================
   STEP 1: SEND / RESEND OTP
========================= */
if (isset($_POST['send_otp']) || isset($_POST['resend_otp'])) {

    // cooldown check (30 sec)
    if (isset($_SESSION['otp_time']) && time() - $_SESSION['otp_time'] < 30) {
        $message = "Please wait 30 seconds before resending OTP.";
    } else {

        $email = strtolower(trim($_POST['email'] ?? $_SESSION['reset_email'] ?? ''));

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $message = "Invalid email.";
        } else {

            $check = $conn->prepare("SELECT id, name FROM users WHERE email=?");
            $check->bind_param("s", $email);
            $check->execute();
            $res = $check->get_result();

            if ($res && $res->num_rows > 0) {

                $row = $res->fetch_assoc();
                $otp = rand(100000, 999999);

                /* SEND MAIL */
                $mail = new PHPMailer(true);

                try {
                    $mail->isSMTP();
                    $mail->Host = 'webmail.bionick.co.in';
                    $mail->SMTPAuth = true;

                    $mail->Username = 'aryan@bionick.co.in';
                    $mail->Password = 'aryan123@*'; // 🔴 CHANGE

                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    $mail->Port = 587;

                    $mail->SMTPOptions = [
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                            'allow_self_signed' => true
                        ]
                    ];

                    $mail->setFrom('aryan@bionick.co.in', 'ERP System');
                    $mail->addAddress($email, $row['name']);

                    $mail->isHTML(true);
                    $mail->Subject = 'OTP for Password Reset';
                    $mail->Body = "
                        <div style='font-family:Arial'>
                            <h2>Hello {$row['name']}</h2>
                            <p>Your OTP is:</p>
                            <h1 style='color:#1f4e79;'>$otp</h1>
                            <p>This OTP is valid for 10 minutes.</p>
                        </div>
                    ";

                    if ($mail->send()) {
                        $_SESSION['otp'] = $otp;
                        $_SESSION['reset_email'] = $email;
                        $_SESSION['otp_time'] = time();

                        $message = isset($_POST['resend_otp']) ? "OTP resent successfully!" : "OTP sent successfully!";
                    }

                } catch (Exception $e) {
                    $message = "Mailer Error: " . $mail->ErrorInfo;
                }

            } else {
                $message = "Email not found.";
            }
        }
    }
}

/* =========================
   STEP 2: VERIFY OTP
========================= */
if (isset($_POST['verify_reset'])) {

    $entered_otp = $_POST['otp'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // OTP expiry (10 min)
    if (!isset($_SESSION['otp_time']) || time() - $_SESSION['otp_time'] > 600) {
        $message = "OTP expired. Please resend OTP.";
    }
    elseif ($entered_otp != ($_SESSION['otp'] ?? '')) {
        $message = "Invalid OTP.";
    }
    elseif ($new_password !== $confirm_password) {
        $message = "Passwords do not match.";
    }
   else {

    $email = $_SESSION['reset_email'];

    // ❌ No hashing
    $update = $conn->prepare("UPDATE users SET password=? WHERE email=?");
    $update->bind_param("ss", $new_password, $email);

    if ($update->execute()) {
        $message = "Password reset successful. Redirecting...";
        $redirect = true;

        unset($_SESSION['otp']);
        unset($_SESSION['reset_email']);
        unset($_SESSION['otp_time']);
    } else {
        $message = "Error updating password.";
    }
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Forgot Password</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
:root{
--primary:#1f4e79;
--shadow:0 20px 50px rgba(15,23,42,0.08);
}

body{
font-family:'Inter',sans-serif;
background:linear-gradient(135deg,#eef3f8,#f8fbff);
display:flex;
align-items:center;
justify-content:center;
height:100vh;
margin:0;
}

.container{
max-width:420px;
width:100%;
}

.card{
background:#fff;
padding:32px;
border-radius:14px;
box-shadow:var(--shadow);
}

.logo{text-align:center;margin-bottom:20px;}
.logo img{height:60px;}

h3{text-align:center;margin-bottom:20px;}

.input{
width:100%;
padding:12px;
border-radius:10px;
border:1px solid #e6ecf3;
margin-bottom:16px;
}

.btn{
width:100%;
padding:14px;
border-radius:10px;
border:none;
background:#1f4e79;
color:#fff;
font-weight:700;
cursor:pointer;
}

.btn:hover{background:#2e6aa3;}

.msg{text-align:center;margin-bottom:10px;color:green;}
.back{text-align:center;margin-top:10px;}
.back{
    text-align:center;
    margin-top:18px;
}

.back-btn{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:10px 16px;
    border-radius:8px;
    text-decoration:none;
    font-weight:600;
    color:#1f4e79;
    background:#eef4fb;
    transition:all 0.3s ease;
}

.back-btn:hover{
    background:#1f4e79;
    color:#fff;
    transform:translateY(-2px);
    box-shadow:0 8px 20px rgba(31,78,121,0.2);
}
</style>
</head>

<body>

<div class="container">
<div class="card">

<div class="logo">
<img src="logo.png">
</div>

<h3>Reset Password</h3>

<?php if ($message): ?>
<div class="msg"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>

<?php if (!isset($_SESSION['otp'])): ?>

<form method="post">
<input class="input" type="email" name="email" placeholder="Enter your email" required>
<button class="btn" name="send_otp">Send OTP</button>
</form>

<?php else: ?>

<form method="post">
<input class="input" type="text" name="otp" placeholder="Enter OTP" required>
<input class="input" type="password" name="new_password" placeholder="New Password" required>
<input class="input" type="password" name="confirm_password" placeholder="Confirm Password" required>

<button class="btn" name="verify_reset">Verify & Reset</button>
</form>

<form method="post" style="margin-top:10px;">
<button class="btn" name="resend_otp" style="opacity:0.9;">Resend OTP</button></form>

<?php endif; ?>

<div class="back">
    <a href="login.php" class="back-btn">
        ← Back to Login
    </a>
</div>

</div>
</div>

<script>
<?php if (!empty($redirect)): ?>
setTimeout(function(){
    window.location.href = "login.php";
}, 3000);
<?php endif; ?>
</script>

</body>
</html>