<?php
// --- LOGIC BLOCK ---
require_once 'includes/db.php';
$message = '';
$token_is_valid = false;

if (isset($_GET['token'])) {
    $token = $_GET['token'];
    $token_hash = hash('sha256', $token);
    
    $stmt = $conn->prepare("SELECT id FROM users WHERE reset_token_hash = ? AND reset_token_expires_at > NOW()");
    $stmt->bind_param("s", $token_hash);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $token_is_valid = true;
        $user = $result->fetch_assoc();
        $user_id_to_update = $user['id'];
    } else {
        $message = '<div class="alert alert-danger">This password reset link is invalid or has expired. Please try again.</div>';
    }
} else {
    $message = '<div class="alert alert-danger">No reset token provided.</div>';
}

// Handle form submission for the new password
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reset_password']) && $token_is_valid) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    if (strlen($password) < 8) {
        $message = '<div class="alert alert-danger">Password must be at least 8 characters long.</div>';
    } elseif ($password !== $confirm_password) {
        $message = '<div class="alert alert-danger">Passwords do not match.</div>';
    } else {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        // Update password and nullify the token so it can't be reused
        $stmt_update = $conn->prepare("UPDATE users SET password = ?, reset_token_hash = NULL, reset_token_expires_at = NULL WHERE id = ?");
        $stmt_update->bind_param("si", $hashed_password, $user_id_to_update);
        $stmt_update->execute();
        
        $message = '<div class="alert alert-success">Your password has been reset successfully! You can now <a href="login.php">log in</a> with your new password.</div>';
        $token_is_valid = false; // Hide the form after success
    }
}

// --- PRESENTATION BLOCK ---
include 'includes/header.php';
?>
<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-body p-5">
                    <h2 class="text-center mb-4">Set a New Password</h2>
                    <?php echo $message; ?>
                    <?php if ($token_is_valid): ?>
                    <form method="POST">
                        <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                        <div class="mb-3"><label class="form-label">New Password</label><input type="password" name="password" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label">Confirm New Password</label><input type="password" name="confirm_password" class="form-control" required></div>
                        <div class="d-grid"><button type="submit" name="reset_password" class="btn btn-primary">Reset Password</button></div>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</main>
<?php include 'includes/footer.php'; ?>
