<?php
require_once 'db_connection.php'; // Make sure this connects to your database

$token = $_GET['token'] ?? '';
$role = $_GET['role'] ?? '';
$errors = [];
$success = '';
$email = '';

// Validate token on load
if (!empty($token) && !empty($role)) {
    $stmt = $conn->prepare("SELECT * FROM password_resets WHERE token = ? AND role = ?");
    $stmt->bind_param("ss", $token, $role);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $row = $result->fetch_assoc();
        $expires_at = strtotime($row['expires_at']);
        if (time() > $expires_at) {
            $errors[] = "This reset link has expired.";
        } else {
            $email = $row['email'];
        }
    } else {
        $errors[] = "Invalid reset link.";
    }
} else {
    $errors[] = "Missing or invalid token.";
}

// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] === "POST" && empty($errors)) {
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($password) || empty($confirm_password)) {
        $errors[] = "Both fields are required.";
    } elseif ($password !== $confirm_password) {
        $errors[] = "Passwords do not match.";
    } else {
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        
        $table = match ($role) {
            'student' => 'students',
            'instructor' => 'instructors',
            'admin' => 'admins',
            default => ''
        };

        if ($table) {
            $stmt = $conn->prepare("UPDATE $table SET password = ? WHERE email = ?");
            $stmt->bind_param("ss", $hashed_password, $email);
            $stmt->execute();

            // Delete the reset token
            $stmt = $conn->prepare("DELETE FROM password_resets WHERE token = ?");
            $stmt->bind_param("s", $token);
            $stmt->execute();

            $success = "Your password has been reset successfully. You can now <a href='{$role}-login.php'>login</a>.";
        } else {
            $errors[] = "Invalid role.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reset Password</title>
</head>
<body>
    <h2>Reset Your Password</h2>

    <?php
    if ($errors) {
        echo "<ul style='color: red;'>";
        foreach ($errors as $e) echo "<li>$e</li>";
        echo "</ul>";
    }

    if ($success) {
        echo "<p style='color: green;'>$success</p>";
    }
    ?>

    <?php if (empty($success) && !empty($email)): ?>
    <form method="POST" action="">
        <label>New Password:</label><br>
        <input type="password" name="password" required><br><br>
        <label>Confirm Password:</label><br>
        <input type="password" name="confirm_password" required><br><br>
        <button type="submit">Reset Password</button>
    </form>
    <?php endif; ?>
</body>
</html>
