
<?php

date_default_timezone_set('Asia/Colombo');

require_once 'config/db.php';
require_once 'includes/csrf.php';

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

if(empty($token))
{
    die("Invalid reset link.");
}

/*
|--------------------------------------------------------------------------
| Check Token Validity
|--------------------------------------------------------------------------
*/
$stmt = mysqli_prepare(
    $conn,
    "SELECT id, email
     FROM users
     WHERE reset_token = ?
     AND reset_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);

if(!$user)
{
    die("Invalid or expired reset link.");
}

$message = '';

/*
|--------------------------------------------------------------------------
| Reset Password
|--------------------------------------------------------------------------
*/
if(isset($_POST['reset_password']))
{
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) die('Invalid request.');
    $password         = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if(empty($password))
    {
        $message =
        "<div class='alert alert-danger'>
        Password is required.
        </div>";
    }
    elseif(strlen($password) < 6)
    {
        $message =
        "<div class='alert alert-danger'>
        Password must be at least 6 characters.
        </div>";
    }
    elseif($password !== $confirm_password)
    {
        $message =
        "<div class='alert alert-danger'>
        Passwords do not match.
        </div>";
    }
    else
    {
        $hash = password_hash(
            $password,
            PASSWORD_DEFAULT
        );

        $update = mysqli_prepare(
            $conn,
            "UPDATE users
             SET password = ?,
                 reset_token = NULL,
                 reset_expiry = NULL
             WHERE id = ?"
        );

        mysqli_stmt_bind_param(
            $update,
            "si",
            $hash,
            $user['id']
        );

        if(mysqli_stmt_execute($update))
        {
            echo "
            <script>
                alert('Password updated successfully');
                window.location='login.php';
            </script>
            ";
            exit();
        }
        else
        {
            $message =
            "<div class='alert alert-danger'>
            Failed to update password.
            </div>";
        }
    }
}
?>

<!DOCTYPE html>
<html>

<head>

    <title>Reset Password</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
          rel="stylesheet">

</head>

<body>

<div class="container mt-5">

    <div class="row justify-content-center">

        <div class="col-md-5">

            <div class="card shadow">

                <div class="card-header bg-primary text-white">
                    Reset Password
                </div>

                <div class="card-body">

                    <?= $message ?>

                    <p>
                        Account:
                        <strong>
                            <?= htmlspecialchars($user['email']) ?>
                        </strong>
                    </p>

                    <form method="POST">

                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

                        <div class="mb-3">

                            <label>
                                New Password
                            </label>

                            <input
                                type="password"
                                name="password"
                                class="form-control"
                                required>

                        </div>

                        <div class="mb-3">

                            <label>
                                Confirm Password
                            </label>

                            <input
                                type="password"
                                name="confirm_password"
                                class="form-control"
                                required>

                        </div>

                        <button
                            type="submit"
                            name="reset_password"
                            class="btn btn-success w-100">

                            Update Password

                        </button>

                    </form>

                </div>

            </div>

        </div>

    </div>

</div>

</body>
</html>
