<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/mail.php';
require_once __DIR__ . '/includes/rate-limit.php';

$page_title = 'Reset your password';
$sent  = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    rate_limit_enforce('forgot', RL_FORGOT);
    csrf_verify();
    $email = trim($_POST['email'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } else {
        $raw = auth_create_reset_token($email);
        if ($raw) {
            $link = SITE_URL . '/reset-password.php?token=' . urlencode($raw);
            $body =
                "Hi,\n\n" .
                "Someone asked to reset the password for this Buy Local Lowveld account.\n\n" .
                "If it was you, open this link within 2 hours:\n\n" .
                "  $link\n\n" .
                "If it wasn't you, ignore this email — your password stays unchanged.\n\n" .
                "— The Buy Local team\n";
            mail_send($email, 'Reset your Buy Local password', $body);
        }
        // ALWAYS show the same confirmation, regardless of whether the email exists.
        // This prevents account enumeration.
        $sent = true;
    }
}

require 'includes/header.php';
?>

<section class="page-banner">
    <div class="container">
        <h1>Forgot your password?</h1>
        <p>Enter your email and we'll send a reset link.</p>
    </div>
</section>

<section class="section">
    <div class="container" style="max-width:480px;">

        <?php if ($sent): ?>
            <div class="alert alert-success">
                <strong>Check your inbox.</strong>
                If an account exists for that email, a reset link is on its way.
                The link expires in 2 hours.
            </div>
            <p class="text-center mt-3">
                <a href="login.php">&larr; Back to login</a>
            </p>
        <?php else: ?>
            <?php if ($error): ?>
                <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <div class="card">
                <form method="post" action="forgot-password.php">
                    <?= csrf_field() ?>
                    <label for="email">Email</label>
                    <input type="email" id="email" name="email" required autofocus>
                    <button type="submit" class="btn btn-block mt-3">Send reset link</button>
                </form>
                <p class="text-center mt-3" style="font-size:.9rem;">
                    <a href="login.php">&larr; Back to login</a>
                </p>
            </div>
        <?php endif; ?>
    </div>
</section>

<?php require 'includes/footer.php'; ?>
