<?php
// admin/forgot_password.php — request a password reset link by email
require_once __DIR__ . '/../config.php';
startSecureSession();

$msg = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email  = trim($_POST['email'] ?? '');
    $bucket = 'pwreset:' . clientIp();
    $gate   = loginThrottleAllowed($bucket);

    if (!csrfValid()) {
        $error = 'Security token expired. Please try again.';
    } elseif (!$gate['allowed']) {
        $error = 'Too many requests. Try again in ' . ceil($gate['retry_after'] / 60) . ' minute(s).';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } else {
        // Only active accounts can reset; pending accounts must activate instead.
        $stmt = db()->prepare("SELECT * FROM admins WHERE email=? AND status='active' LIMIT 1");
        $stmt->execute([$email]);
        $admin = $stmt->fetch();

        if ($admin) {
            $token   = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', time() + 3600); // 1-hour validity
            db()->prepare('UPDATE admins SET reset_token=?, reset_expires=? WHERE id=?')
                ->execute([$token, $expires, $admin['id']]);
            $link = BASE_URL . '/admin/reset_password.php?token=' . urlencode($token);
            $html = buildEmailHtml(
                $admin['name'], 'Password Reset',
                "We received a request to reset your RSVP admin password. "
                . "Click the button below to choose a new password. If you didn't request this, you can ignore this email.",
                $link
            );
            // Reuse the account's own sender settings
            @sendMail($admin, $email, 'Reset your RSVP admin password', str_replace('View Your Ticket', 'Reset Password', $html));
        }
        // Register the attempt to throttle abuse, but never reveal whether the email exists.
        loginThrottleFail($bucket);
        $msg = 'If that email belongs to an active account, a reset link has been sent.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Forgot Password — RSVP System</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" media="print" onload="this.media='all'" href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/main.css">
</head>
<body>
<div class="login-wrap">
  <div class="login-card">
    <div class="login-logo">
      <div class="name">RSVP</div>
      <div class="sub">Password Reset</div>
    </div>

    <?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

    <?php if (!$msg): ?>
    <p class="text-muted text-sm" style="text-align:center;margin-bottom:20px">
      Enter your account email and we'll send you a reset link.
    </p>
    <form method="POST">
      <?= csrfField() ?>
      <div class="form-group">
        <label class="form-label">Email Address</label>
        <input class="form-control" type="email" name="email" autocomplete="email" required>
      </div>
      <button class="btn btn-gold w-100 mt-3" type="submit">Send Reset Link</button>
    </form>
    <?php endif; ?>

    <p style="text-align:center;margin-top:18px">
      <a href="<?= BASE_URL ?>/admin/login.php" class="text-muted text-sm">← Back to login</a>
    </p>
  </div>
</div>
</body>
</html>
