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

$page_title = 'Set a new password';
$token = $_GET['token'] ?? $_POST['token'] ?? '';
$error = '';

// Validate token on GET
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!$token) {
        header('Location: forgot-password.php'); exit;
    }
    // We don't consume yet — just check it would be valid.
    $hashed = hash('sha256', $token);
    $row = db_row(
        'SELECT 1 FROM password_resets
            WHERE token = :t AND used_at IS NULL AND expires_at > NOW() LIMIT 1',
        ['t' => $hashed]
    );
    if (!$row) {
        $error = 'This reset link has expired or already been used. Request a new one below.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $pw  = $_POST['password'] ?? '';
    $pw2 = $_POST['password_confirm'] ?? '';

    if (strlen($pw) < 8) {
        $error = 'Password must be at least 8 characters.';
    } elseif ($pw !== $pw2) {
        $error = 'The two passwords don\'t match.';
    } else {
        $member = auth_consume_reset_token($token);
        if (!$member) {
            $error = 'This reset link is no longer valid. Request a new one.';
        } else {
            auth_set_password((int)$member['id'], $pw);
            header('Location: login.php?reset=1');
            exit;
        }
    }
}

require 'includes/header.php';
?>

<section class="page-banner">
    <div class="container">
        <h1>Set a new password</h1>
        <p>Pick something secure — you'll use this to sign in from now on.</p>
    </div>
</section>

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

        <?php if ($error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
            <p class="text-center mt-2">
                <a href="forgot-password.php" class="btn btn-outline">Request a new reset link</a>
            </p>
        <?php else: ?>
            <div class="card">
                <form method="post" action="reset-password.php">
                    <?= csrf_field() ?>
                    <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

                    <label for="password">New password</label>
                    <input type="password" id="password" name="password" required minlength="8" autofocus>

                    <label for="password_confirm">Confirm new password</label>
                    <input type="password" id="password_confirm" name="password_confirm" required minlength="8">

                    <button type="submit" class="btn btn-block mt-3">Set password</button>
                </form>
            </div>
        <?php endif; ?>
    </div>
</section>

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