<?php
require_once 'db_connect.php';
date_default_timezone_set('Africa/Johannesburg');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_password = $_POST['password'] ?? '';

    if ($token && $new_password) {
        $stmt = $conn_rbe->prepare("SELECT user_id FROM login_tokens WHERE token = ? AND expires_at > NOW() LIMIT 1");
        $stmt->execute([$token]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $hash = password_hash($new_password, PASSWORD_DEFAULT);
            $conn_rbe->prepare("UPDATE rbe_users SET password_hash = ?, password_updated_at = NOW(), must_set_password = 0, is_active = 1 WHERE id = ?")->execute([$hash, $row['user_id']]);
            $conn_rbe->prepare("DELETE FROM login_tokens WHERE token = ?")->execute([$token]);
            $message = "Password updated successfully. <a href='login.php' style='color:#7ed957;'>Login</a>";
        } else {
            $message = "Invalid or expired token.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reset Password – RBE</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: Arial, sans-serif; background: #051a25; color: #fff; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; }
        .container { width: 90%; max-width: 400px; background: #122c4c; padding: 20px; border-radius: 12px; box-shadow: 0 0 15px rgba(0,0,0,0.4); text-align: center; }
        input[type="password"] { width: 100%; padding: 12px; margin: 10px 0; border-radius: 8px; border: none; }
        button { background: #7ed957; color: #000; padding: 12px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; width: 100%; }
        button:hover { background: #00cc77; }
        .message { color: #ff6666; margin-top: 10px; }
        a.back { color: #7ed957; display: block; margin-top: 15px; }
    </style>
</head>
<body>
<div class="container">
    <h2>Reset Your Password</h2>
    <form method="post">
        <input type="password" name="password" placeholder="New Password" required>
        <button type="submit">Reset Password</button>
    </form>
    <?php if ($message): ?>
        <div class="message"><?= $message ?></div>
    <?php endif; ?>
</div>
</body>
</html>
