<?php
declare(strict_types=1);

require('configuration.php');

if (session_status() === PHP_SESSION_NONE) {
    session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);
}

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

$message = '';

function buildResetLink(string $token): string
{
    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    return sprintf(
        '%s://%s%s/reset_password.php?token=%s',
        $scheme,
        $_SERVER['HTTP_HOST'],
        dirname($_SERVER['SCRIPT_NAME']),
        urlencode($token)
    );
}

function sendResetEmail(string $to, string $token): bool
{
    $subject = 'Pinnacle Fitness Password Reset';
    $resetLink = buildResetLink($token);
    $body = "A password reset request was received for your Pinnacle Fitness member account.\n\n" .
        "Click the link below to reset your password (valid for 1 hour):\n\n" .
        $resetLink . "\n\n" .
        "If you did not request this, you can ignore this message.\n";

    $headers = 'From: ' . (_fromEmail_ ?? 'coach@pinnacle-fitness.com') . "\r\n" .
               'Reply-To: ' . (_fromEmail_ ?? 'coach@pinnacle-fitness.com') . "\r\n" .
               'X-Mailer: PHP/' . phpversion();

    return mail($to, $subject, $body, $headers);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token'], $_SESSION['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $message = 'Invalid request.';
    } else {
        $email = trim($_POST['email'] ?? '');

        if ($email === '') {
            $message = 'Please enter your email.';
        } else {
            // Same message whether or not the email exists — prevents
            // attackers from using this form to discover valid member emails.
            $message = 'If that email is registered, a password reset link has been sent.';

            $stmt = mysqli_prepare($connection, "SELECT memberid FROM member WHERE member_email = ? LIMIT 1");
            mysqli_stmt_bind_param($stmt, 's', $email);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            $user = mysqli_fetch_assoc($result);
            mysqli_stmt_close($stmt);

            if ($user) {
                $token = bin2hex(random_bytes(32));

                // Expiry computed by MySQL's own NOW(), not PHP's date() —
                // the app's PHP timezone (America/New_York) and the DB
                // server's timezone are not the same, so comparing a
                // PHP-computed timestamp against MySQL's NOW() later (in
                // reset_password.php) could make tokens expire immediately
                // or last far longer than 1 hour depending on the offset.
                $stmt = mysqli_prepare($connection,
                    "UPDATE member SET reset_token = ?, reset_token_expiry = NOW() + INTERVAL 1 HOUR WHERE memberid = ?"
                );
                mysqli_stmt_bind_param($stmt, 'si', $token, $user['memberid']);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);

                sendResetEmail($email, $token);
            }
        }
    }
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
    <input type="email" name="email" placeholder="Enter your email" required>
    <button type="submit" name="submit">Reset Password</button>
</form>

<p><?php echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8'); ?></p>
