<?php
require('configuration.php');
session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$token = $_GET['token'] ?? $_POST['token'] ?? '';
$message = '';

if ($token === '') {
    die("Invalid request.");
}

// Check token
$stmt = mysqli_prepare($connection,
    "SELECT memberid FROM member
     WHERE reset_token = ? AND reset_token_expiry > NOW() LIMIT 1"
);

mysqli_stmt_bind_param($stmt, 's', $token);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);

if (!$user) {
    die("Reset link is invalid or has expired. <a href='forgot_password.php'>Request a new link</a>.");
}

if (isset($_POST['submit'])) {
    if (!isset($_POST['csrf_token'], $_SESSION['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $message = "Invalid request.";
    } else {
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if ($password === '' || $confirm_password === '') {
            $message = "Enter and confirm your new password.";
        } elseif ($password !== $confirm_password) {
            $message = "Passwords do not match.";
        } elseif (strlen($password) < 8) {
            $message = "Password must be at least 8 characters.";
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = mysqli_prepare($connection,
                "UPDATE member
                 SET member_password=?, reset_token=NULL, reset_token_expiry=NULL
                 WHERE memberid=?"
            );

            mysqli_stmt_bind_param($stmt, 'si', $hash, $user['memberid']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            $message = success_text() . " <a href='index.php'>Login</a>";
        }
    }
}
?>

<form method="post">
    <input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
    <input type="password" name="password" placeholder="New Password" required>
    <input type="password" name="confirm_password" placeholder="Confirm New Password" required>
    <button type="submit" name="submit">Update Password</button>
</form>

<p><?php echo $message; ?></p>
