<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
if (isUserLoggedIn()) { header('Location: /dashboard.php'); exit; }

$error = ''; $success = ''; $step = $_GET['step'] ?? 'email';
$token = trim($_GET['token'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { $error = 'Invalid request.'; goto done; }
    $action = $_POST['action'] ?? '';

    if ($action === 'send_otp') {
        $email = trim($_POST['email'] ?? '');
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = 'Enter a valid email address.'; goto done; }
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
        $stmt->execute([$email]); $user = $stmt->fetch();
        if ($user) {
            $otp = createOTP($pdo, $user['id'], 'password_reset');
            sendOTPEmail($email, $user['first_name'], $otp, 'password_reset');
        }
        // Always show success for security (don't reveal if email exists)
        $success = 'If that email exists in our system, a reset code has been sent.';
        $_SESSION['reset_email'] = $email;
        $step = 'otp';
    }

    if ($action === 'verify_reset_otp') {
        $email = $_SESSION['reset_email'] ?? '';
        $code  = trim($_POST['otp_code'] ?? '');
        $stmt  = $pdo->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
        $stmt->execute([$email]); $user = $stmt->fetch();
        if ($user && verifyOTP($pdo, $user['id'], $code, 'password_reset')) {
            $_SESSION['reset_user_id'] = $user['id'];
            $step = 'reset';
        } else {
            $error = 'Invalid or expired code.'; $step = 'otp';
        }
    }

    if ($action === 'reset_password') {
        $uid2 = (int)($_SESSION['reset_user_id'] ?? 0);
        if (!$uid2) { $error = 'Session expired. Start again.'; $step = 'email'; goto done; }
        $pass  = $_POST['password'] ?? '';
        $pass2 = $_POST['confirm_password'] ?? '';
        if (strlen($pass) < 8) { $error = 'Password must be at least 8 characters.'; $step = 'reset'; goto done; }
        if ($pass !== $pass2) { $error = 'Passwords do not match.'; $step = 'reset'; goto done; }
        $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($pass, PASSWORD_DEFAULT), $uid2]);
        unset($_SESSION['reset_email'], $_SESSION['reset_user_id']);
        flash('success', 'Password reset successfully! Please log in with your new password.');
        header('Location: /login.php'); exit;
    }
}
done:
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reset Password | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body class="auth-page">
<div class="container">
  <div class="d-flex justify-content-center">
    <div class="auth-card fade-in-up">
      <div class="auth-logo"><img src="/assets/img/logo.png" alt="<?= SITE_NAME ?>"></div>
      <?php if ($error): ?><div class="alert alert-danger py-2 small"><?= sanitize($error) ?></div><?php endif; ?>
      <?php if ($success): ?><div class="alert alert-success py-2 small"><?= sanitize($success) ?></div><?php endif; ?>

      <?php if ($step === 'email'): ?>
      <h2 class="auth-title">Reset Password</h2>
      <p class="auth-subtitle">Enter your email address to receive a reset code</p>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="send_otp">
        <div class="mb-3"><label class="form-label">Email Address</label>
          <div class="input-group"><span class="input-group-text"><i class="fa fa-envelope"></i></span>
          <input type="email" name="email" class="form-control" required></div>
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold">Send Reset Code</button>
      </form>

      <?php elseif ($step === 'otp'): ?>
      <h2 class="auth-title">Enter Reset Code</h2>
      <p class="auth-subtitle">We sent a 6-digit code to your email</p>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="verify_reset_otp">
        <div class="mb-3"><label class="form-label">Verification Code</label>
          <input type="text" name="otp_code" class="form-control form-control-lg text-center fw-bold" placeholder="000000" maxlength="6" pattern="\d{6}" required style="letter-spacing:8px;font-size:1.5rem;">
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold">Verify Code</button>
      </form>

      <?php elseif ($step === 'reset'): ?>
      <h2 class="auth-title">New Password</h2>
      <p class="auth-subtitle">Choose a strong new password</p>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="reset_password">
        <div class="mb-3"><label class="form-label">New Password</label>
          <input type="password" name="password" class="form-control" minlength="8" required>
        </div>
        <div class="mb-3"><label class="form-label">Confirm Password</label>
          <input type="password" name="confirm_password" class="form-control" required>
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold">Reset Password</button>
      </form>
      <?php endif; ?>

      <hr><p class="text-center small mb-0"><a href="/login.php" style="color:var(--primary)"><i class="fa fa-arrow-left me-1"></i>Back to Login</a></p>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>
