<?php
session_start();
require_once 'db_connect.php';

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

// Handle token verification
if ($token) {
    $stmt = $conn_rbe->prepare("SELECT user_id, expires_at FROM login_tokens WHERE token = ? LIMIT 1");
    $stmt->execute([$token]);
    $token_row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($token_row) {
        if (strtotime($token_row['expires_at']) > time()) {
            // Valid token, check if form submitted
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                $password = $_POST['password'] ?? '';
                $confirm = $_POST['confirm'] ?? '';

                if ($password && $confirm && $password === $confirm) {
                    $hashed = password_hash($password, PASSWORD_BCRYPT);
                    $stmt = $conn_rbe->prepare("UPDATE rbe_users SET password_hash = ?, password_updated_at = NOW(), must_set_password = 0, is_active = 1 WHERE id = ?");
                    $stmt->execute([$hashed, $token_row['user_id']]);

                    // Delete the token
                    $conn_rbe->prepare("DELETE FROM login_tokens WHERE token = ?")->execute([$token]);

                    $success = "✅ Password set successfully. You can now log in.";
                    header("refresh:3;url=login.php");
                } else {
                    $error = "❌ Passwords do not match or are empty.";
                }
            }
        } else {
            $error = "❌ This link has expired.";
        }
    } else {
        $error = "❌ Invalid or expired token.";
    }
} else {
    $error = "❌ No token provided.";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Set Your Password – RBE Platform</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { background: #051a25; color: #fff; font-family: Arial, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
        .box { background: #122c4c; padding: 30px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.5); width: 100%; max-width: 400px; }
        h2 { margin-top: 0; color: #7ed957; }
        input { width: 100%; padding: 12px; margin: 10px 0; border-radius: 8px; border: none; }
        button { width: 100%; padding: 12px; background: #7ed957; border: none; border-radius: 8px; font-weight: bold; color: #000; cursor: pointer; }
        button:hover { background: #00cc77; }
        .message { margin-top: 15px; font-weight: bold; }
    </style>
</head>
<body>
    <div class="box">
        <h2>Set Your Password</h2>

        <?php if ($error): ?>
            <p class="message" style="color: #ff4444;"><?php echo $error; ?></p>
        <?php elseif ($success): ?>
            <p class="message" style="color: #7ed957;"><?php echo $success; ?></p>
        <?php else: ?>
            <form method="post">
                <input type="password" name="password" placeholder="New Password" required>
                <input type="password" name="confirm" placeholder="Confirm Password" required>
                <button type="submit">Set Password</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
