<?php
session_start();
if (!isset($_SESSION['reset_userid'])) {
    header("Location: forgot_password.php");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Reset Password</title>
    <link rel="stylesheet" href="main.css">
</head>
<body class="resetpasswordphp">
    <h2>Reset Your Password</h2>

    <form id="resetForm">
        <input type="text" name="username" placeholder="Username" value="<?php echo $_SESSION['username']?>" required minlength="4" /><br>
        <input type="password" name="new_pass" placeholder="New Password" required minlength="8" /><br>
        <input type="password" name="confirm_pass" placeholder="Confirm Password" required minlength="8" /><br>
        <button type="submit">Reset Password</button>
    </form>

    <div class="message" id="responseMessage"></div>

    <script>
        const form = document.getElementById('resetForm');
        const messageDiv = document.getElementById('responseMessage');

        form.addEventListener('submit', async function (e) {
            e.preventDefault();

            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());

            const res = await fetch('update_password.php', {
                method: 'POST',
                headers: { 'Accept': 'application/json' },
                body: formData
            });

            const result = await res.json();

            messageDiv.textContent = result.message;
            messageDiv.className = 'message ' + (result.success ? 'success' : 'error');

            if (result.success) {
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
            }
        });
    </script>
</body>
</html>
