<?php
require_once "config/db.php";

$token = $_GET['token'] ?? '';
$error = "";
$success = "";

if(!$token){
    die("Invalid request");
}

// Validate token
$stmt = $conn->prepare("SELECT * FROM users WHERE reset_token=? AND reset_expire > NOW()");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows !== 1){
    die("Invalid or expired token");
}

$user = $result->fetch_assoc();

if(isset($_POST['reset'])){

    $pass = $_POST['password'];
    $confirm = $_POST['confirm'];

    if($pass !== $confirm){
        $error = "Passwords do not match";
    } else {

        $hash = password_hash($pass, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("
        UPDATE users 
        SET password=?, reset_token=NULL, reset_expire=NULL 
        WHERE id=?
        ");
        $stmt->bind_param("si", $hash, $user['id']);
        $stmt->execute();

        $success = "Password updated successfully";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Reset Password</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="d-flex align-items-center justify-content-center" style="height:100vh;background:#f5f5f5;">

<div class="card p-4 shadow" style="width:350px;">

<h5 class="text-center mb-3">Reset Password</h5>

<?php if($error){ ?>
<div class="alert alert-danger"><?= $error ?></div>
<?php } ?>

<?php if($success){ ?>
<div class="alert alert-success"><?= $success ?></div>
<?php } ?>

<form method="POST">

<input type="password" name="password" class="form-control mb-2" placeholder="New Password" required>
<input type="password" name="confirm" class="form-control mb-3" placeholder="Confirm Password" required>

<button class="btn btn-success w-100" name="reset">Update Password</button>

</form>

</div>

</body>
</html>
