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

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');

    if ($email) {
        $stmt = $conn_rbe->prepare("SELECT id FROM rbe_users WHERE email = ? AND is_deleted = 0 AND is_active = 1 LIMIT 1");
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $token = bin2hex(random_bytes(16));
            $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

            // Save token with created_at for compatibility
            $stmt = $conn_rbe->prepare("INSERT INTO login_tokens (user_id, token, expires_at, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$user['id'], $token, $expires]);

            $link = RBE_V2_BASE_URL . "/reset-password.php?token=" . urlencode($token);
            mail($email, "Reset Your Password", "Click this link to reset your password: $link");

            $message = "Reset link sent to your email.";
        } else {
            $message = "Email not found.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Forgot 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="email"] { 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>Forgot Password</h2>
    <form method="post">
        <input type="email" name="email" placeholder="Enter your email" required>
        <button type="submit">Send Reset Link</button>
    </form>
    <?php if ($message): ?>
        <div class="message"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
    <a href="login.php" class="back">Back to Login</a>
</div>
</body>
</html>
