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

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

$email = trim((string)($_GET['email'] ?? ''));
$token = trim((string)($_GET['token'] ?? ''));

if (!$email || !$token) {
    flash('error', 'Invalid or missing reset token.');
    redirect('/login.php');
}

$stmt = db()->prepare('SELECT * FROM password_resets WHERE email = ? AND token = ?');
$stmt->execute([$email, $token]);
$reset = $stmt->fetch();

if (!$reset || strtotime($reset['created_at']) < strtotime('-1 hour')) {
    flash('error', 'Reset link is invalid or has expired.');
    redirect('/forgot_password.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $password = (string)post('password');
    $confirm = (string)post('confirm_password');

    if (!$password || strlen($password) < 6) {
        flash('error', 'Password must be at least 6 characters.');
    } elseif ($password !== $confirm) {
        flash('error', 'Passwords do not match.');
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = db()->prepare('UPDATE users SET password_hash = ? WHERE email = ?');
        $stmt->execute([$hash, $email]);

        $stmt = db()->prepare('DELETE FROM password_resets WHERE email = ?');
        $stmt->execute([$email]);

        log_activity('password_reset.success', 'Password reset successfully for: ' . $email);
        flash('success', 'Your password has been reset. You can now login.');
        redirect('/login.php');
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Reset 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>Reset Password</h1>
        <p>Enter your new password below.</p>
        <?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
        <form method="post" novalidate>
            <?= csrf_field() ?>
            <label class="form-label">New Password</label>
            <input class="form-control mb-3" type="password" name="password" required autocomplete="new-password">
            <label class="form-label">Confirm Password</label>
            <input class="form-control mb-4" type="password" name="confirm_password" required autocomplete="new-password">
            <button class="btn btn-primary w-100 mb-3" type="submit"><i class="bi bi-check2-circle me-1"></i>Reset Password</button>
        </form>
    </div>
</body>
</html>
