<?php
if (!defined('VALID_ACCESS')) { include(__DIR__ . '/include/config.php'); }
define('RESET_OTP_EXPIRATION', 60);

// POST handler
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'send_otp') {
        $email = trim($_POST['email']);
        // Math captcha validation
        $captcha_answer = isset($_POST['captcha_answer']) ? intval($_POST['captcha_answer']) : -1;
        $captcha_expected = isset($_SESSION['reset_captcha_result']) ? intval($_SESSION['reset_captcha_result']) : null;
        unset($_SESSION['reset_captcha_result']);
        if ($captcha_expected === null || $captcha_answer !== $captcha_expected) {
            $_SESSION['error'] = "Incorrect captcha answer. Please try again.";
            header('Location: resetpassword.php'); exit();
        }
        if (empty($email)) { $_SESSION['error'] = "Email address is required!"; header('Location: resetpassword.php'); exit(); }
        try {
            $stmt = $pdo->prepare("SELECT id, username FROM users WHERE email = ?"); $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($user) {
                $otp = rand(100000, 999999);
                $_SESSION['reset_email'] = $email; $_SESSION['reset_user_id'] = $user['id'];
                $_SESSION['reset_otp'] = $otp; $_SESSION['reset_otp_time'] = time(); $_SESSION['reset_step'] = 'verify_otp';
                $subject = WEB_NAME . " - Password Reset Code";
                $message = "<html><body style='font-family:sans-serif;max-width:600px;margin:0 auto;padding:20px'><div style='background:#4D148C;padding:20px;text-align:center;border-radius:8px 8px 0 0'><h1 style='color:#fff;margin:0'>" . WEB_NAME . " Password Reset</h1></div><div style='padding:25px;background:#f9f9f9;border-radius:0 0 8px 8px;border:1px solid #e0e0e0;border-top:none'><p>Hello {$user['username']},</p><p>Your reset code:</p><div style='text-align:center'><div style='background:#4D148C;color:#fff;font-size:28px;font-weight:bold;padding:15px 25px;border-radius:8px;display:inline-block;letter-spacing:5px'>{$otp}</div></div><p style='background:#fff8e1;padding:10px;border-left:4px solid #ffc107;margin:20px 0;font-size:14px'><strong>Note:</strong> Expires in 60 seconds.</p></div></body></html>";
                send_system_email($email, $subject, $message, $pdo, $site_data);
                $_SESSION['success'] = "Verification code sent to your email!";
            } else { $_SESSION['success'] = "If this email is registered, you will receive a verification code."; }
        } catch (PDOException $e) { $_SESSION['error'] = "An error occurred. Please try again!"; }
        header('Location: resetpassword.php'); exit();
    }

    if ($action === 'verify_otp') {
        $entered_otp = trim($_POST['otp']);
        if (!isset($_SESSION['reset_otp']) || !isset($_SESSION['reset_otp_time'])) { $_SESSION['error'] = "Session expired. Please start over."; unset($_SESSION['reset_step']); header('Location: resetpassword.php'); exit(); }
        $otp_age = time() - $_SESSION['reset_otp_time'];
        if ($otp_age > RESET_OTP_EXPIRATION) { $_SESSION['error'] = "Code expired. Please request a new one."; unset($_SESSION['reset_step']); }
        elseif ($entered_otp == $_SESSION['reset_otp']) { $_SESSION['reset_step'] = 'new_password'; $_SESSION['success'] = "Code verified! Enter your new password."; unset($_SESSION['reset_otp'], $_SESSION['reset_otp_time']); }
        else { $_SESSION['error'] = "Invalid code. Please try again."; }
        header('Location: resetpassword.php'); exit();
    }

    if ($action === 'update_password') {
        if (!isset($_SESSION['reset_step']) || $_SESSION['reset_step'] !== 'new_password') { $_SESSION['error'] = "Invalid request."; header('Location: resetpassword.php'); exit(); }
        $password = $_POST['password']; $password_confirmation = $_POST['password_confirmation'];
        if ($password !== $password_confirmation) { $_SESSION['error'] = "Passwords do not match!"; header('Location: resetpassword.php'); exit(); }
        if (strlen($password) < 8) { $_SESSION['error'] = "Password must be at least 8 characters!"; header('Location: resetpassword.php'); exit(); }
        try {
            $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([password_hash($password, PASSWORD_DEFAULT), $_SESSION['reset_user_id']]);
            unset($_SESSION['reset_email'], $_SESSION['reset_user_id'], $_SESSION['reset_step']);
            $_SESSION['password_reset_success'] = true;
        } catch (PDOException $e) { $_SESSION['error'] = "Failed to update password."; }
        header('Location: resetpassword.php'); exit();
    }
}

if (isset($_GET['resend']) && isset($_SESSION['reset_email'])) {
    $otp = rand(100000, 999999); $_SESSION['reset_otp'] = $otp; $_SESSION['reset_otp_time'] = time();
    $email = $_SESSION['reset_email'];
    $stmt = $pdo->prepare("SELECT username FROM users WHERE email = ?"); $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    $subject = WEB_NAME . " - Password Reset Code";
    $message = "<html><body><div style='background:#4D148C;padding:20px;text-align:center;border-radius:8px 8px 0 0'><h1 style='color:#fff'>" . WEB_NAME . "</h1></div><div style='padding:25px;background:#f9f9f9;border:1px solid #e0e0e0;border-top:none;border-radius:0 0 8px 8px'><p>Your reset code:</p><div style='text-align:center'><div style='background:#4D148C;color:#fff;font-size:28px;font-weight:bold;padding:15px 25px;border-radius:8px;display:inline-block;letter-spacing:5px'>{$otp}</div></div></div></body></html>";
    send_system_email($email, $subject, $message, $pdo, $site_data);
    $_SESSION['success'] = "New code sent to your email.";
    header('Location: resetpassword.php'); exit();
}

if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) { header('Location: user/dashboard.php'); exit(); }

$current_step = $_SESSION['reset_step'] ?? 'request_reset';

// Generate math captcha for step 1
$captcha_num1 = rand(1, 15); $captcha_num2 = rand(1, 10);
$captcha_op = rand(0, 1) ? '+' : '-';
if ($captcha_op === '-' && $captcha_num1 < $captcha_num2) { $tmp = $captcha_num1; $captcha_num1 = $captcha_num2; $captcha_num2 = $tmp; }
$_SESSION['reset_captcha_result'] = $captcha_op === '+' ? $captcha_num1 + $captcha_num2 : $captcha_num1 - $captcha_num2;
$captcha_question = $captcha_num1 . ' ' . $captcha_op . ' ' . $captcha_num2 . ' = ?';

$page_title = $site_data['web_name'] . " | Reset Password";
include('include/header.php');
?>

<!-- Reset Password Page -->
<section class="py-16 px-4 sm:px-6 lg:px-8 max-w-lg mx-auto">
  <div class="glassmorphism rounded-3xl p-8 shadow-premium">
    <!-- Header -->
    <div class="text-center mb-6">
      <div class="w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mx-auto mb-4">
        <i class="fa-solid fa-key text-primary text-2xl"></i>
      </div>
      <h1 class="text-2xl font-extrabold text-slate-900">
        <?php if ($current_step === 'verify_otp') echo "Verify Code";
              elseif ($current_step === 'new_password') echo "New Password";
              else echo "Reset Password"; ?>
      </h1>
      <p class="text-sm text-slate-500 mt-1">
        <?php if ($current_step === 'verify_otp') echo "Enter the 6-digit code sent to your email";
              elseif ($current_step === 'new_password') echo "Choose a strong new password";
              else echo "Enter your email to receive a reset code"; ?>
      </p>
    </div>

    <!-- Success State -->
    <?php if (isset($_SESSION['password_reset_success'])): ?>
      <div class="text-center py-6">
        <div class="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
          <i class="fa-solid fa-circle-check text-green-600 text-2xl"></i>
        </div>
        <h3 class="text-lg font-bold text-slate-900 mb-2">Password Reset Successful!</h3>
        <p class="text-sm text-slate-500 mb-6">You can now sign in with your new password.</p>
        <a href="<?php echo $site_data['web_url']; ?>/signin" class="inline-flex items-center gap-2 bg-primary hover:bg-primary-light text-white font-bold text-sm px-6 py-3 rounded-xl transition-all shadow-glow-purple">
          <i class="fa-solid fa-right-to-bracket"></i> Sign In Now
        </a>
      </div>
      <script>setTimeout(function(){window.location.href='<?php echo $site_data['web_url']; ?>/signin';},3000);</script>
      <?php unset($_SESSION['password_reset_success']); ?>

    <?php else: ?>

      <!-- Alerts -->
      <?php if (isset($_SESSION['error'])): ?>
      <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-4 flex items-center gap-3">
        <i class="fa-solid fa-circle-exclamation text-red-500"></i>
        <span class="text-sm text-red-800"><?php echo htmlspecialchars($_SESSION['error']); unset($_SESSION['error']); ?></span>
      </div>
      <?php endif; ?>
      <?php if (isset($_SESSION['success'])): ?>
      <div class="bg-green-50 border border-green-200 rounded-xl p-4 mb-4 flex items-center gap-3">
        <i class="fa-solid fa-circle-check text-green-600"></i>
        <span class="text-sm text-green-800"><?php echo htmlspecialchars($_SESSION['success']); unset($_SESSION['success']); ?></span>
      </div>
      <?php endif; ?>

      <!-- Step 1: Request Reset -->
      <?php if ($current_step === 'request_reset'): ?>
      <form action="resetpassword.php" method="POST">
        <input type="hidden" name="action" value="send_otp">
        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Email Address</label>
          <div class="relative">
            <i class="fa-solid fa-envelope absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="email" name="email" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Enter your registered email" autocomplete="email">
          </div>
          <p class="text-[11px] text-slate-400 mt-1">We'll send a verification code to this address</p>
        </div>

        <!-- Math Captcha -->
        <div class="mb-5">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">
            Solve: <span class="text-primary text-sm ml-1"><?php echo $captcha_question; ?></span>
          </label>
          <div class="relative">
            <i class="fa-solid fa-calculator absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="number" name="captcha_answer" required class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Your answer" autocomplete="off">
          </div>
        </div>

        <button type="submit" class="w-full bg-primary hover:bg-primary-light text-white font-bold text-sm py-4 rounded-xl transition-all shadow-glow-purple flex items-center justify-center gap-2">
          <i class="fa-solid fa-paper-plane"></i> Send Reset Code
        </button>
      </form>

      <!-- Step 2: Verify OTP -->
      <?php elseif ($current_step === 'verify_otp'): ?>
      <div class="bg-amber-50 border border-amber-200 rounded-xl p-4 mb-5 flex items-center gap-3">
        <i class="fa-solid fa-clock text-amber-500"></i>
        <span class="text-xs text-amber-800">Code expires in <strong>60 seconds</strong></span>
      </div>

      <form action="resetpassword.php" method="POST" id="otpForm">
        <input type="hidden" name="action" value="verify_otp">
        <input type="hidden" name="otp" id="otp-hidden">

        <div class="flex gap-2 justify-center mb-6">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
          <input type="text" class="w-12 h-14 text-center text-xl font-bold bg-slate-50 border border-slate-200 rounded-xl focus:outline-none focus:border-primary transition-all otp-d" maxlength="1" inputmode="numeric">
        </div>

        <button type="submit" id="verifyBtn" class="w-full bg-primary hover:bg-primary-light text-white font-bold text-sm py-4 rounded-xl transition-all shadow-glow-purple flex items-center justify-center gap-2">
          <i class="fa-solid fa-shield-check"></i> Verify Code
        </button>

        <div class="w-full h-1 bg-slate-200 rounded-full overflow-hidden mt-4">
          <div id="timerBar" class="h-full bg-primary rounded-full transition-all duration-1000" style="width:100%"></div>
        </div>
        <p class="text-center text-xs text-slate-400 mt-2">Expires in <strong id="timerSec">60</strong>s</p>
      </form>

      <p class="text-center text-sm text-slate-500 mt-5">Didn't get it? <a href="resetpassword.php?resend" class="font-bold text-primary hover:text-accent">Resend Code</a></p>

      <script>
      var digits=document.querySelectorAll('.otp-d');
      digits.forEach(function(d,i){
        d.addEventListener('input',function(){this.value=this.value.replace(/\D/g,'').slice(0,1);if(this.value&&i<5)digits[i+1].focus();});
        d.addEventListener('keydown',function(e){if(e.key==='Backspace'&&!this.value&&i>0)digits[i-1].focus();});
        d.addEventListener('paste',function(e){e.preventDefault();var t=(e.clipboardData||window.clipboardData).getData('text').replace(/\D/g,'');for(var j=0;j<6&&j<t.length;j++)digits[j].value=t[j];});
      });
      document.getElementById('otpForm').addEventListener('submit',function(){var v='';digits.forEach(function(d){v+=d.value;});document.getElementById('otp-hidden').value=v;});
      digits[0].focus();
      var secs=60,bar=document.getElementById('timerBar'),secEl=document.getElementById('timerSec'),btn=document.getElementById('verifyBtn');
      setInterval(function(){secs--;if(secs<0)return;bar.style.width=(secs/60*100)+'%';if(secs<=10)bar.style.background='#ef4444';else if(secs<=30)bar.style.background='#f59e0b';secEl.textContent=secs;if(secs<=0){btn.disabled=true;btn.classList.add('opacity-50');btn.innerHTML='<i class="fa-solid fa-clock"></i> Code Expired';}},1000);
      </script>

      <!-- Step 3: New Password -->
      <?php elseif ($current_step === 'new_password'): ?>
      <form action="resetpassword.php" method="POST">
        <input type="hidden" name="action" value="update_password">

        <div class="mb-4">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">New Password</label>
          <div class="relative">
            <i class="fa-solid fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input id="pw1" type="password" name="password" required minlength="8" class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-12 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Min. 8 characters">
            <button type="button" onclick="var f=document.getElementById('pw1');f.type=f.type==='password'?'text':'password'" class="absolute right-3 top-1/2 -translate-y-1/2 w-8 h-8 rounded-lg bg-white border border-slate-200 flex items-center justify-center text-slate-400 hover:text-primary"><i class="fa-solid fa-eye text-xs"></i></button>
          </div>
        </div>

        <div class="mb-5">
          <label class="block text-xs font-bold text-slate-600 uppercase tracking-wider mb-2">Confirm Password</label>
          <div class="relative">
            <i class="fa-solid fa-shield-halved absolute left-4 top-1/2 -translate-y-1/2 text-primary/50 text-sm"></i>
            <input type="password" name="password_confirmation" required minlength="8" class="w-full bg-slate-50 border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 focus:outline-none focus:border-primary transition-all" placeholder="Re-enter new password">
          </div>
        </div>

        <button type="submit" class="w-full bg-primary hover:bg-primary-light text-white font-bold text-sm py-4 rounded-xl transition-all shadow-glow-purple flex items-center justify-center gap-2">
          <i class="fa-solid fa-check"></i> Update Password
        </button>
      </form>
      <?php endif; ?>

    <?php endif; ?>

    <!-- Back to signin -->
    <div class="text-center mt-6 pt-5 border-t border-slate-200">
      <a href="<?php echo $site_data['web_url']; ?>/signin" class="text-sm text-slate-500 hover:text-primary transition-colors">
        <i class="fa-solid fa-arrow-left text-xs"></i> Back to Sign In
      </a>
    </div>
  </div>
</section>

<?php include('include/footer.php'); ?>
