<?php
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'config/seo.php';

$seo = getSEO('forgot_password');

$type = isset($_GET['type']) ? sanitize($_GET['type']) : (isset($_POST['type']) ? sanitize($_POST['type']) : 'client');
$validTypes = ['client', 'rider', 'restaurant', 'admin'];
if (!in_array($type, $validTypes)) {
    $type = 'client';
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize($_POST['email'] ?? '');
    
    if (empty($email)) {
        $error = "Please enter your email.";
    } elseif (!validateEmail($email)) {
        $error = "Invalid email format.";
    } else {
        $db = getDB();

        // ── Rate Limiting: Max 3 reset requests per email per hour ───
        $rateSql = "SELECT COUNT(*) as cnt FROM password_resets WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)";
        $rateRow = $db->query($rateSql)->fetch_assoc();
        // Per-email rate limit check is done below after we know the user exists

        if (!$error) {
            $table = '';
            if ($type === 'client') $table = 'users';
            elseif ($type === 'rider') $table = 'riders';
            elseif ($type === 'restaurant') $table = 'restaurants';
            elseif ($type === 'admin') $table = 'admins';

            $stmt = $db->prepare("SELECT * FROM $table WHERE email = ? LIMIT 1");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();

            if ($user) {
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', time() + 3600);

                // ── Per-email rate limit: max 3 requests in last hour ──
                $emailRateStmt = $db->prepare("SELECT COUNT(*) as cnt FROM password_resets WHERE user_id = ? AND user_type = ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
                $emailRateStmt->bind_param('is', $user['id'], $type);
                $emailRateStmt->execute();
                $emailRateRow = $emailRateStmt->get_result()->fetch_assoc();
                if (intval($emailRateRow['cnt']) >= 3) {
                    $error = "Too many reset requests. Please wait 1 hour before trying again.";
                } else {
                    $insert = $db->prepare("INSERT INTO password_resets (user_type, user_id, token, expires_at) VALUES (?, ?, ?, ?)");
                    $insert->bind_param("siss", $type, $user['id'], $token, $expires);

                    if ($insert->execute()) {
                        $resetLink = SITE_URL . "/reset-password.php?token=$token";
                        $userName = $user['name'] ?? $user['full_name'] ?? $user['username'] ?? 'User';
                        $body = "<h2>Password Reset Request</h2>
                                 <p>Hi " . htmlspecialchars($userName) . ",</p>
                                 <p>We received a request to reset your password. Click the link below:</p>
                                 <p><a href='$resetLink'>$resetLink</a></p>
                                 <p>If you didn't request this, ignore this email. This link expires in 1 hour.</p>";
                        if (sendEmail($email, "Reset Your GoBotad Password", $body)) {
                            $success = "A password reset link has been sent to your email.";
                        } else {
                            $error = "Failed to send email. Please try again later.";
                        }
                    } else {
                        $error = "Database error. Please try again later.";
                    }
                } // end rate-limit else
            } else {
                $displayType = $type;
                if ($type === 'client') $displayType = 'customer';
                $error = "This email address is not registered as a " . htmlspecialchars($displayType) . ".";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($seo['title']); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($seo['description']); ?>">
    <meta name="keywords" content="<?php echo htmlspecialchars($seo['keywords']); ?>">
    <link rel="canonical" href="https://gobotad.com/forgot-password" />
    
    <!-- Open Graph / Facebook -->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://gobotad.com/forgot-password">
    <meta property="og:title" content="<?php echo htmlspecialchars($seo['title']); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($seo['description']); ?>">
    <meta property="og:image" content="https://gobotad.com/uploads/banners/69d16da394dd8_1775332771.png">

    <!-- Twitter -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:url" content="https://gobotad.com/forgot-password">
    <meta name="twitter:title" content="<?php echo htmlspecialchars($seo['title']); ?>">
    <meta name="twitter:description" content="<?php echo htmlspecialchars($seo['description']); ?>">
    <meta name="twitter:image" content="https://gobotad.com/uploads/banners/69d16da394dd8_1775332771.png">

    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        body { font-family: 'Outfit', sans-serif; background: #f8fafc; margin: 0; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
        .card { background: #fff; padding: 2.5rem; border-radius: 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.08); width: 100%; max-width: 420px; }
        h1 { margin: 0 0 10px; color: #1e293b; font-weight: 900; font-size: 1.75rem; }
        p.sub { color: #64748b; font-size: 0.95rem; margin-bottom: 25px; line-height: 1.5; }
        .input-wrap { position: relative; margin-bottom: 20px; }
        .input-wrap i { position: absolute; left: 15px; top: 15px; color: #94a3b8; }
        .input-wrap input { width: 100%; padding: 13px 15px 13px 40px; border: 1.5px solid #e2e8f0; border-radius: 12px; font-family: 'Outfit', sans-serif; font-size: 1rem; outline: none; transition: 0.2s; box-sizing: border-box;}
        .input-wrap input:focus { border-color: #f97316; box-shadow: 0 0 0 3px rgba(249,115,22,0.1); }
        .btn { width: 100%; padding: 14px; border: none; background: #f97316; color: white; border-radius: 12px; font-family: 'Outfit', sans-serif; font-weight: 800; font-size: 1rem; cursor: pointer; transition: 0.2s; }
        .btn:hover { background: #ea580c; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(249,115,22,0.3); }
        .alert { padding: 12px; border-radius: 10px; font-size: 0.9rem; font-weight: 600; margin-bottom: 20px; }
        .alert-error { background: #fff1f2; color: #ef4444; border: 1px solid #fecdd3; }
        .alert-success { background: #f0fdf4; color: #16a34a; border: 1px solid #bbf7d0; }
        .back { display: block; text-align: center; margin-top: 20px; color: #f97316; text-decoration: none; font-weight: 700; font-size: 0.9rem; }
    </style>
</head>
<body>
    <div class="card">
        <h1>Forgot Password?</h1>
        <p class="sub">Enter your registered email address and we'll send you a link to reset your password.</p>
        
        <?php if ($error): ?>
            <div class="alert alert-error"><i class="fas fa-circle-exclamation"></i> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <?php if ($success): ?>
            <div class="alert alert-success"><i class="fas fa-circle-check"></i> <?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>

        <form method="POST">
            <input type="hidden" name="type" value="<?php echo htmlspecialchars($type); ?>">
            <div class="input-wrap">
                <i class="fas fa-envelope"></i>
                <input type="email" name="email" placeholder="Enter your email" required autofocus>
            </div>
            <button class="btn" type="submit">Send Reset Link</button>
        </form>

        <?php
        $backUrl = '/';
        if ($type === 'admin') {
            $backUrl = '/admin/auth/login-page.php';
        } elseif ($type !== 'client') {
            $backUrl = '/?app_type=' . urlencode($type);
        }
        ?>
        <a href="<?php echo htmlspecialchars($backUrl); ?>" class="back"><i class="fas fa-arrow-left"></i> Back to Login</a>
        
        <details class="seo-text" style="margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid #e2e8f0; font-size: 0.8rem; color: #94a3b8; line-height: 1.5; text-align: justify;">
            <summary style="font-size: 0.85rem; color: #64748b; font-weight: 700; cursor: pointer; outline: none;">Need Help? Security & Account Recovery <i class="fas fa-chevron-down" style="font-size: 0.75rem; margin-left: 4px;"></i></summary>
            <div style="margin-top: 0.8rem;">
                <p style="margin-bottom: 0.6rem;">Recovering your GoBotad account is simple and highly secure. Enter your registered email address above, and our system will instantly verify it. If a matching account is found in our database, we will email you a unique, encrypted password reset link that is valid for exactly one hour. For security reasons, the link will expire after one hour or once it has been used to set a new password, preventing unauthorized access to your account.</p>
                <p style="margin-bottom: 0.6rem;">If you do not receive the password reset email within a few minutes, please check your spam or junk folder, or verify that you entered the correct email address associated with your GoBotad profile. Our automated mail servers deliver notifications immediately. If you continue to experience technical difficulties or are unable to access your email account, please contact our support team at gobotad@gmail.com for personalized assistance.</p>
                <p>We recommend creating a strong, unique password that you do not use on other websites. A strong password should be at least 8 characters long and contain a mix of uppercase and lowercase letters, numbers, and special symbols. Never share your password, OTP, or reset links with anyone, including GoBotad customer care executives. Our support team will never ask you for your account credentials.</p>
            </div>
        </details>
    </div>
</body>
</html>
