<?php
session_start();
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['token'])) {
    $token = $conn->real_escape_string($_GET['token']);
    $query = "SELECT * FROM users WHERE reset_token = '$token'";
    $result = $conn->query($query);

    if ($result->num_rows == 0) {
        $_SESSION['error'] = "Token tidak valid.";
        header("Location: forgot-password.php");
        exit();
    }
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $token = $conn->real_escape_string($_POST['token']);
    $newPassword = password_hash($conn->real_escape_string($_POST['password']), PASSWORD_BCRYPT);

    $query = "SELECT * FROM users WHERE reset_token = '$token'";
    $result = $conn->query($query);

    if ($result->num_rows == 1) {
        $updateQuery = "UPDATE users SET password = '$newPassword', reset_token = NULL WHERE reset_token = '$token'";
        $conn->query($updateQuery);

        $_SESSION['success'] = "Password berhasil direset.";
        header("Location: login.php");
        exit();
    } else {
        $_SESSION['error'] = "Token tidak valid.";
        header("Location: forgot-password.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Reset Password</title>
</head>

<body>
    <?php if (isset($_SESSION['error'])): ?>
        <p style="color: red;"><?php echo $_SESSION['error'];
                                unset($_SESSION['error']); ?></p>
    <?php endif; ?>

    <?php if (isset($_SESSION['success'])): ?>
        <p style="color: green;"><?php echo $_SESSION['success'];
                                    unset($_SESSION['success']); ?></p>
    <?php endif; ?>

    <form action="reset-password.php" method="POST">
        <input type="hidden" name="token" value="<?php echo htmlspecialchars($_GET['token']); ?>">
        <label for="password">Password Baru:</label>
        <input type="password" name="password" id="password" required>
        <button type="submit">Reset Password</button>
    </form>
</body>

</html>