<?php
require_once __DIR__ . '/../app/includes/auth.php';

if (current_user()) {
    redirect('/dashboard.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $email = trim((string)post('email'));
    if ($email === '') {
        flash('error', 'Email is required.');
        redirect('/forgot_password.php');
    }

    $stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND status = "active"');
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        $token = bin2hex(random_bytes(32));
        
        $stmt = db()->prepare('REPLACE INTO password_resets (email, token, created_at) VALUES (?, ?, ?)');
        $stmt->execute([$email, $token, now()]);

        $resetLink = APP_BASE . '/reset_password.php?token=' . $token . '&email=' . urlencode($email);
        log_activity('password_reset.requested', 'Password reset requested for: ' . $email);
        
        flash('success', 'A password reset link has been sent to your email. (Simulated: <a href="'.e($resetLink).'">Click here to reset</a>)');
    } else {
        flash('success', 'If your email is registered, you will receive a password reset link.');
    }
    redirect('/forgot_password.php');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Forgot Password - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="<?= APP_BASE ?>/assets/css/app.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body class="login-page">
    <div class="login-card">
        <div class="login-logo">F</div>
        <h1>Forgot Password</h1>
        <p>Enter your email to receive a reset link.</p>
        <?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
        <?php if ($msg = flash('success')): ?><div class="alert alert-success"><?= $msg ?></div><?php endif; ?>
        <form method="post" novalidate>
            <?= csrf_field() ?>
            <label class="form-label">Email</label>
            <input class="form-control mb-4" type="email" name="email" required autocomplete="username">
            <button class="btn btn-primary w-100 mb-3" type="submit"><i class="bi bi-envelope me-1"></i>Send Reset Link</button>
            <div class="text-center text-muted" style="font-size:0.9rem;">
                Remember your password? <a href="<?= APP_BASE ?>/login.php" class="text-decoration-none fw-bold">Login</a>
            </div>
        </form>
    </div>
</body>
</html>
