<?php
require_once 'auth.php';
require_once __DIR__ . '/../includes/pdo.php';
require_once __DIR__ . '/../includes/ai-manager.php';

ini_set('display_errors', '1');
error_reporting(E_ALL);

// ============================================================
// ✅ HANDLE: Save API Keys
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_api_key'])) {
    $keysToSave = [
        'gemini_api_key'     => $_POST['gemini_api_key'] ?? '',
        'groq_api_key'       => $_POST['groq_api_key'] ?? '',
        'openrouter_api_key' => $_POST['openrouter_api_key'] ?? '',
        'mistral_api_key'    => $_POST['mistral_api_key'] ?? '',
        'together_api_key'   => $_POST['together_api_key'] ?? '',
        'cohere_api_key'     => $_POST['cohere_api_key'] ?? ''
    ];

    foreach ($keysToSave as $key => $value) {
        $stmt = $pdo->prepare("INSERT INTO finggu_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$key, $value, $value]);
    }
    $success_message = "✅ All API Keys saved successfully!";
}


// ============================================================
// ✅ HANDLE: Toggle Manual Updated Flag (AJAX)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_manual'])) {
    $id  = intval($_POST['id'] ?? 0);
    $val = intval($_POST['value'] ?? 0);
    $stmt = $pdo->prepare("UPDATE city_service SET is_manually_updated = ? WHERE id = ?");
    $stmt->execute([$val, $id]);
    echo json_encode(['success' => true]);
    exit;
}


// ============================================================
// ✅ HANDLE: AI Content Generation (AJAX)
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_ai'])) {
    set_time_limit(180);

    $id = intval($_POST['id'] ?? 0);
    if (!$id) {
        echo json_encode(['success' => false, 'error' => 'Invalid page ID']);
        exit;
    }

    // Fetch city and service name
    $stmt = $pdo->prepare("
        SELECT cs.id, c.name AS city_name, s.name AS service_name 
        FROM city_service cs
        JOIN cities c ON cs.city_id = c.id
        JOIN services s ON cs.service_id = s.id
        WHERE cs.id = ?
    ");
    $stmt->execute([$id]);
    $pageData = $stmt->fetch();

    if (!$pageData) {
        echo json_encode(['success' => false, 'error' => 'Page not found']);
        exit;
    }

    // ✅ FIX 1: Check if ANY API key is configured (not just Gemini)
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM finggu_settings WHERE setting_key LIKE '%_api_key' AND setting_value != ''");
    $stmt->execute();
    $hasAnyKey = (int) $stmt->fetchColumn();

    if (!$hasAnyKey) {
        echo json_encode(['success' => false, 'error' => 'No API keys configured. Please add at least one API key above.']);
        exit;
    }

    $cityName    = $pageData['city_name'];
    $serviceName = $pageData['service_name'];

    // ✅ Prompt (Enhanced for 1500-2000 words & Exact Keyword Targeting)
    $prompt = "You are a Senior SEO Strategist and Content Architect.
    
    Goal: Create a world-class, authority-building service page for '$serviceName' in '$cityName' to outrank top competitors.
    Target Keyword: '$serviceName Company in $cityName'
    Word Count Goal: 1500-2000 words of high-value content.
    
    IMPORTANT: You MUST return ONLY a valid JSON object. No conversational text.
    Ensure ALL newlines and special characters inside JSON string values are properly escaped (use \\n for newlines).
    
    JSON Structure Requirement:
    {
      \"seo_title\": \"(Generate a unique, punchy, high-CTR primary keyword title for $serviceName in $cityName. Avoid repeating common patterns.)\",
      \"seo_description\": \"(Generate an original, persuasive meta description under 160 chars specifically for $serviceName in $cityName. No generic templates.)\",
      \"seo_keywords\": \"(List 6-8 highly specific local and service-related keywords)\",
      \"html_content\": \"<!-- AI_FULL_CONTENT --><div class='rich-content'>...</div>\"
    }

    CONTENT ARCHITECTURE & SEO RULES:
    1. Exact Keywords: Use '$serviceName Company in $cityName' and '$serviceName Services in $cityName' as your primary H1 and H2 tags.
    2. Semantic SEO & Keyword Density (CRITICAL):
       - Maintain a primary keyword density of approximately 1.5%.
       - Identify and naturally integrate 10-15 LSI (Latent Semantic Indexing) and secondary keywords related to '$serviceName' (e.g., if service is 'Web Design', use terms like 'UI/UX', 'responsive layout', 'performance optimization', 'conversion rate', 'CMS development').
       - Bold key service-related phrases throughout the content to signal relevance to search engines.
    3. Deep Local Context:
       - Research and mention at least 5-6 real neighborhoods, major roads, or landmarks specific to '$cityName'.
       - Explain WHY '$serviceName' is crucial for businesses specifically located in the $cityName region.
    4. Mandatory Sections (Professional & Premium):
       - H1: $serviceName Company in $cityName (add a catchy subtitle).
       - Detailed Introduction (300 words): High-authority approach to the industry in $cityName.
       - H2: Professional $serviceName Services in $cityName (Deep dive into technical details).
       - H2: Why Our $serviceName Company in $cityName Stands Out (Grid md:grid-cols-3 layout with 6 cards).
       - Local Market Intelligence Section (500+ words): Analyze the digital landscape of $cityName.
       - Our Strategic Process (6-steps): Style this as a series of premium cards in a 'grid md:grid-cols-3 gap-6' layout. Each card should feature a white background, a bold step number (class='text-red-600'), a bold title, and a professional light border with hover shadow-lg effects.
       - Local Neighborhoods We Serve in $cityName: A dedicated list/section mentioning specific local zones.
       - FAQ: 8-10 highly detailed technical and local questions.
    5. Aesthetics & Formatting (CRITICAL):
       - All H2 and H3 headings MUST be **bold** (class='font-bold') and have large vertical spacing (class='mt-12 mb-6').
       - Primary Color: #dc2626 (Red). Secondary: #1A1A1A (Dark).
       - Use rounded-3xl, shadow-xl, and elegant borders for all sections.
       - Use FontAwesome 6 for all icons.
       - Use gradient text for impact: bg-gradient-to-r from-red-600 to-red-800 bg-clip-text text-transparent.
    6. Structural Integrity: Ensure subheadings (H3) for every 2-3 paragraphs. High keyword density but naturally written. No fluff. Ensure the 1500-2000 word count is strictly met with high-value technical information.";

    // Call AI with fallback chain
    $aiResult = ai_generate_with_fallback($prompt, $pdo);

    if (!$aiResult['success']) {
        echo json_encode(['success' => false, 'error' => $aiResult['error']]);
        exit;
    }

    // ── JSON Cleaning & Repair ──────────────────────────────
    $aiResponseJSON = trim($aiResult['content']);
    $providerUsed   = $aiResult['provider'];

    // 1. Strip markdown code fences
    if (preg_match('/^```(?:json)?\s*(.*)\s*```$/is', $aiResponseJSON, $matches)) {
        $aiResponseJSON = $matches[1];
    }

    // 2. Extract first { ... last }
    $firstBracket = strpos($aiResponseJSON, '{');
    $lastBracket  = strrpos($aiResponseJSON, '}');
    
    if ($firstBracket !== false) {
        if ($lastBracket !== false && $lastBracket > $firstBracket) {
            $aiResponseJSON = substr($aiResponseJSON, $firstBracket, $lastBracket - $firstBracket + 1);
        } else {
            // Cut off at the end? Try to close it.
            $aiResponseJSON = substr($aiResponseJSON, $firstBracket);
            $aiResponseJSON = json_fix_broken($aiResponseJSON);
        }
    }

    // 3. Strip hidden/control characters (BOM etc)
    $aiResponseJSON = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $aiResponseJSON);

    // 4. Decode attempt
    $aiData = json_decode($aiResponseJSON, true);

    // 5. Retry: fix unescaped newlines inside string values
    if (json_last_error() !== JSON_ERROR_NONE) {
        $fixedJSON = preg_replace_callback('/"(.*?)":\s*"(.*?)"(?=\s*[,}\]])/s', function($m) {
            $val = str_replace(["\r", "\n", "\t"], ["\\r", "\\n", "\\t"], $m[2]);
            return "\"{$m[1]}\": \"$val\"";
        }, $aiResponseJSON);
        $aiData = json_decode($fixedJSON, true);
    }

    /**
     * Helper to close unclosed JSON brackets/quotes if truncated
     */
    function json_fix_broken($json) {
        $json = trim($json);
        // Remove trailing comma if exists
        $json = preg_replace('/,\s*$/', '', $json);
        
        // Count quotes and brackets
        $quotes = substr_count($json, '"') - substr_count($json, '\"');
        if ($quotes % 2 !== 0) $json .= '"';
        
        $braces = substr_count($json, '{') - substr_count($json, '}');
        while ($braces > 0) { $json .= '}'; $braces--; }
        
        $brackets = substr_count($json, '[') - substr_count($json, ']');
        while ($brackets > 0) { $json .= ']'; $brackets--; }
        
        return $json;
    }

    // ── Save to Database ───────────────────────────────────
    if (json_last_error() === JSON_ERROR_NONE && !empty($aiData['html_content'])) {
        try {
            // Check required columns exist
            $checkCols = $pdo->query("SHOW COLUMNS FROM city_service LIKE 'seo_keywords'");
            if ($checkCols->rowCount() == 0) {
                echo json_encode(['success' => false, 'error' => 'Database columns missing. Please run update-db-v3.php first.']);
                exit;
            }

            $keywords = $aiData['seo_keywords'] ?? '';
            if (is_array($keywords)) {
                $keywords = implode(', ', $keywords);
            }

            $updateStmt = $pdo->prepare("
                UPDATE city_service 
                SET content = :content,
                    seo_title = :title,
                    seo_description = :desc,
                    seo_keywords = :keywords,
                    content_update_count = content_update_count + 1, 
                    last_ai_update = CURRENT_TIMESTAMP 
                WHERE id = :id
            ");
            $updateStmt->execute([
                ':content'  => $aiData['html_content'],
                ':title'    => (string)($aiData['seo_title'] ?? ''),
                ':desc'     => (string)($aiData['seo_description'] ?? ''),
                ':keywords' => $keywords,
                ':id'       => $id
            ]);

            // ✅ FIX 2: Use prepared statement (no SQL injection)
            $countStmt = $pdo->prepare("SELECT content_update_count FROM city_service WHERE id = ?");
            $countStmt->execute([$id]);
            $newCount = $countStmt->fetchColumn();

            echo json_encode([
                'success'   => true,
                'new_count' => $newCount,
                'provider'  => $providerUsed  // ✅ FIX 3: Return provider name to UI
            ]);

        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database Error: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'AI returned invalid JSON. Error: ' . json_last_error_msg() . ' | Raw: ' . substr($aiResponseJSON, 0, 300)]);
    }
    exit;
}


// ============================================================
// ✅ PAGE SETUP: Filters, Pagination, Data Fetch
// ============================================================
$search         = $_GET['search'] ?? '';
$city_filter    = $_GET['city'] ?? '';
$service_filter = $_GET['service'] ?? '';
$status_filter  = $_GET['status'] ?? ''; // New status filter
$page           = max(1, intval($_GET['page'] ?? 1));
$per_page       = 500;
$offset         = ($page - 1) * $per_page;

$where_conditions = [];
$params = [];

if ($search) {
    $where_conditions[] = "(c.name LIKE ? OR s.name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($city_filter) {
    $where_conditions[] = "c.slug = ?";
    $params[] = $city_filter;
}
if ($service_filter) {
    $where_conditions[] = "s.slug = ?";
    $params[] = $service_filter;
}
if ($status_filter === 'done') {
    $where_conditions[] = "cs.content_update_count > 0";
} elseif ($status_filter === 'pending') {
    $where_conditions[] = "cs.content_update_count = 0";
}

$where_clause = $where_conditions ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Count total records
$count_stmt = $pdo->prepare("
    SELECT COUNT(*) AS total
    FROM city_service cs
    JOIN cities c ON cs.city_id = c.id
    JOIN services s ON cs.service_id = s.id
    $where_clause
");
$count_stmt->execute($params);
$total_records = $count_stmt->fetch()['total'];
$total_pages   = ceil($total_records / $per_page);

// ✅ Calculate Overall AI Progress Stats
$stats_stmt = $pdo->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN content_update_count > 0 THEN 1 ELSE 0 END) as done,
        SUM(CASE WHEN content_update_count = 0 THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN DATE(last_ai_update) = CURDATE() THEN 1 ELSE 0 END) as done_today
    FROM city_service
");
$overall_stats = $stats_stmt->fetch();
$total_all     = $overall_stats['total'] ?? 0;
$done_all      = $overall_stats['done'] ?? 0;
$pending_all   = $overall_stats['pending'] ?? 0;
$done_today    = $overall_stats['done_today'] ?? 0;
$progress_pct  = $total_all > 0 ? round(($done_all / $total_all) * 100, 1) : 0;

// Guard: check DB columns exist
try {
    $pdo->query("SELECT content_update_count FROM city_service LIMIT 1");
} catch (Exception $e) {
    die("
        <div style='font-family:sans-serif; padding:40px; text-align:center;'>
            <h2 style='color:#e74c3c;'>Database Update Required</h2>
            <p>The AI Content System requires database changes to track updates.</p>
            <a href='update-db-v2.php' style='display:inline-block; padding:12px 25px; background:#667eea; color:#fff; text-decoration:none; border-radius:10px; font-weight:bold;'>Run Database Update Now</a>
        </div>
    ");
}

// Fetch rows
$stmt = $pdo->prepare("
    SELECT cs.id, c.name AS city, s.name AS service,
           cs.content_update_count, cs.is_manually_updated, cs.last_ai_update
    FROM city_service cs
    JOIN cities c ON cs.city_id = c.id
    JOIN services s ON cs.service_id = s.id
    $where_clause
    ORDER BY cs.content_update_count ASC, c.name ASC
    LIMIT $per_page OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

// Filter dropdowns
$cities   = $pdo->query("SELECT slug, name FROM cities ORDER BY name")->fetchAll();
$services = $pdo->query("SELECT slug, name FROM services ORDER BY name")->fetchAll();

// API keys for form display
$stmt = $pdo->prepare("SELECT setting_key, setting_value FROM finggu_settings WHERE setting_key LIKE '%_api_key'");
$stmt->execute();
$apiKeys             = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$gemini_api_key      = $apiKeys['gemini_api_key'] ?? '';
$groq_api_key        = $apiKeys['groq_api_key'] ?? '';
$openrouter_api_key  = $apiKeys['openrouter_api_key'] ?? '';
$mistral_api_key     = $apiKeys['mistral_api_key'] ?? '';
$together_api_key    = $apiKeys['together_api_key'] ?? '';
$cohere_api_key      = $apiKeys['cohere_api_key'] ?? '';

// ✅ FIX 4: Load today's usage stats for dashboard card
$todayStats = ai_get_today_stats($pdo);
$statsMap   = [];
foreach ($todayStats as $s) {
    $statsMap[$s['provider']] = $s;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Content System | Finggu Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #667eea;
            --secondary: #764ba2;
            --success: #2ecc71;
            --danger: #e74c3c;
            --warning: #f1c40f;
            --dark: #2c3e50;
            --light: #f8f9fa;
        }

        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; color: #fff; }

        .sidebar { position:fixed; left:0; top:0; width:260px; height:100vh; background:rgba(0,0,0,0.8); backdrop-filter:blur(10px); z-index:1000; padding:20px; border-right:1px solid rgba(255,255,255,0.1); }
        .logo { display:flex; align-items:center; margin-bottom:40px; text-decoration:none; color:#fff; }
        .logo-icon { width:40px; height:40px; background:linear-gradient(135deg,#ff6b6b,#ee5a24); border-radius:10px; display:flex; align-items:center; justify-content:center; margin-right:10px; font-size:1.2rem; }
        .nav-item { display:flex; align-items:center; padding:12px 15px; color:rgba(255,255,255,0.7); text-decoration:none; border-radius:10px; margin-bottom:5px; transition:0.3s; }
        .nav-item:hover, .nav-item.active { background:rgba(255,255,255,0.1); color:#fff; }
        .nav-item i { width:20px; margin-right:10px; }

        .main-content { margin-left:260px; padding:40px; }
        .header { margin-bottom:30px; }
        .header h1 { font-size:2.5rem; font-weight:800; margin-bottom:10px; background:linear-gradient(to right,#fff,#f1c40f); -webkit-background-clip:text; -webkit-text-fill-color:transparent; }

        .card { background:rgba(255,255,255,0.95); border-radius:20px; padding:30px; color:#333; box-shadow:0 10px 30px rgba(0,0,0,0.2); margin-bottom:30px; }
        .card-title { font-size:1.25rem; font-weight:700; margin-bottom:20px; display:flex; align-items:center; }
        .card-title i { margin-right:10px; color:var(--primary); }

        .input-group { margin-bottom:20px; }
        .input-label { display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem; }
        .input-control { width:100%; padding:12px; border:2px solid #ddd; border-radius:10px; font-size:1rem; }
        .btn { padding:12px 25px; border-radius:10px; font-weight:600; cursor:pointer; border:none; transition:0.3s; display:inline-flex; align-items:center; gap:6px; }
        .btn-primary { background:linear-gradient(135deg,var(--primary),var(--secondary)); color:#fff; }
        .btn-success { background:var(--success); color:#fff; }
        .btn:hover { transform:translateY(-3px); box-shadow:0 5px 15px rgba(0,0,0,0.1); }
        .btn:disabled { opacity:0.6; cursor:not-allowed; transform:none; }

        .table-wrap { overflow-x:auto; }
        table { width:100%; border-collapse:collapse; margin-top:20px; }
        th { text-align:left; padding:15px; border-bottom:2px solid #eee; color:#777; font-size:0.85rem; text-transform:uppercase; }
        td { padding:15px; border-bottom:1px solid #eee; vertical-align:middle; }
        .badge { padding:5px 10px; border-radius:20px; font-size:0.75rem; font-weight:700; display:inline-block; }
        .badge-count { background:#e0e0e0; color:#333; }
        .badge-provider { background:#d1ecf1; color:#0c5460; font-size:0.7rem; margin-left:4px; }

        .spinner { display:none; border:3px solid rgba(0,0,0,0.1); width:22px; height:22px; border-radius:50%; border-left-color:var(--primary); animation:spin 1s linear infinite; margin:0 auto; }
        @keyframes spin { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }

        /* ✅ Usage Stats Bar */
        .stats-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:15px; margin-bottom:20px; }
        .stat-card { background:#f8f9fa; border-radius:12px; padding:15px; text-align:center; border:2px solid #eee; }
        .stat-card.active { border-color:#667eea; background:#f0f0ff; }
        .stat-name { font-size:0.75rem; font-weight:700; color:#555; margin-bottom:6px; text-transform:uppercase; }
        .stat-count { font-size:1.4rem; font-weight:800; color:#333; }
        .stat-limit { font-size:0.7rem; color:#999; }
        .stat-bar { height:6px; background:#e0e0e0; border-radius:3px; margin-top:8px; overflow:hidden; }
        .stat-bar-fill { height:100%; background:linear-gradient(to right,#667eea,#764ba2); border-radius:3px; transition:width 0.5s; }
        .stat-bar-fill.warning { background:linear-gradient(to right,#f1c40f,#e67e22); }
        .stat-bar-fill.danger { background:linear-gradient(to right,#e74c3c,#c0392b); }

        .checkbox-container { display:flex; align-items:center; justify-content:center; }
        input[type="checkbox"] { width:1.2rem; height:1.2rem; cursor:pointer; }

        .bulk-bar { position:sticky; bottom:20px; background:rgba(0,0,0,0.9); padding:15px 30px; border-radius:15px; display:flex; justify-content:space-between; align-items:center; z-index:100; margin-top:20px; }

        .pagination { display:flex; list-style:none; margin-top:20px; justify-content:center; flex-wrap:wrap; gap:5px; }
        .pagination a { padding:8px 15px; background:#fff; color:var(--primary); text-decoration:none; border-radius:5px; font-weight:600; }
        .pagination .active a { background:var(--primary); color:#fff; }

        .provider-tag { font-size:0.7rem; padding:2px 7px; border-radius:10px; background:#e8f5e9; color:#2e7d32; font-weight:600; display:inline-block; }
    </style>
</head>
<body>
<div class="sidebar">
    <a href="modern-dashboard.php" class="logo">
        <div class="logo-icon"><i class="fas fa-rocket"></i></div>
        <div>
            <h2 style="font-weight:800;font-size:1.2rem;">Finggu Admin</h2>
            <p style="font-size:0.7rem;opacity:0.7;">AI Systems</p>
        </div>
    </a>
    <nav>
        <a href="modern-dashboard.php" class="nav-item"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="modern-content-management.php" class="nav-item"><i class="fas fa-edit"></i> Content</a>
        <a href="modern-ai-content.php" class="nav-item active"><i class="fas fa-magic"></i> AI Content</a>
        <a href="modern-manage-cities-services.php" class="nav-item"><i class="fas fa-city"></i> Cities & Services</a>
        <a href="logout.php" class="nav-item"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </nav>
</div>

<div class="main-content">
    <div class="header">
        <h1>AI Content System ✨</h1>
        <p>Generate unique, SEO-friendly content for every city page automatically.</p>
    </div>

    <?php if (isset($success_message)): ?>
        <div class="card" style="background:#d4edda;color:#155724;padding:15px;margin-bottom:20px;">
            <?= $success_message ?>
        </div>
    <?php endif; ?>

    <!-- ✅ NEW: AI Progress Dashboard -->
    <div class="card" style="background: linear-gradient(135deg, #1A1A1A 0%, #2c3e50 100%); color: #fff; padding: 35px; border:none; position:relative; overflow:hidden;">
        <div style="position:relative; z-index:2;">
            <div style="display:flex; justify-content:space-between; align-items:flex-end; margin-bottom:15px;">
                <div>
                    <h3 style="font-size:1.4rem; font-weight:800; margin-bottom:5px; color:#f1c40f;">
                        <i class="fas fa-tasks"></i> AI Content Progress
                    </h3>
                    <p style="opacity:0.8; font-size:0.9rem;">Overall coverage of AI-generated landing pages.</p>
                </div>
                <div style="text-align:right;">
                    <div style="font-size:2.5rem; font-weight:900; line-height:1;"><?= $progress_pct ?>%</div>
                    <div style="font-size:0.75rem; opacity:0.7; font-weight:700; text-transform:uppercase;">Completed</div>
                </div>
            </div>

            <div style="height:12px; background:rgba(255,255,255,0.1); border-radius:10px; margin-bottom:25px; overflow:hidden;">
                <div style="height:100%; background: linear-gradient(to right, #f1c40f, #ff9f43); width:<?= $progress_pct ?>%; border-radius:10px; transition:1s;"></div>
            </div>

            <div style="display:grid; grid-template-columns: repeat(4, 1fr); gap:15px;">
                <div style="background:rgba(255,255,255,0.05); padding:15px; border-radius:15px; text-align:center; border:1px solid rgba(255,255,255,0.1);">
                    <div style="font-size:0.75rem; text-transform:uppercase; opacity:0.6; margin-bottom:5px;">Total Pages</div>
                    <div style="font-size:1.5rem; font-weight:800;"><?= number_format($total_all) ?></div>
                </div>
                <div style="background:rgba(255, 255, 255, 0.05); padding:15px; border-radius:15px; text-align:center; border:1px solid rgba(255, 255, 255, 0.2);">
                    <div style="font-size:0.75rem; text-transform:uppercase; color:#f1c40f; opacity:1; margin-bottom:5px;">Done Today</div>
                    <div style="font-size:1.5rem; font-weight:800; color:#f1c40f;"><?= number_format($done_today) ?></div>
                </div>
                <a href="?status=done" style="text-decoration:none; color:inherit; display:block; background:rgba(46, 204, 113, 0.1); padding:15px; border-radius:15px; text-align:center; border:1px solid rgba(46, 204, 113, 0.3); transition:0.3s; cursor:pointer;" onmouseover="this.style.background='rgba(46, 204, 113, 0.2)'" onmouseout="this.style.background='rgba(46, 204, 113, 0.1)'">
                    <div style="font-size:0.75rem; text-transform:uppercase; color:#2ecc71; margin-bottom:5px;">Finished (AI)</div>
                    <div style="font-size:1.5rem; font-weight:800; color:#2ecc71;"><?= number_format($done_all) ?></div>
                </a>
                <a href="?status=pending" style="text-decoration:none; color:inherit; display:block; background:rgba(255, 255, 255, 0.05); padding:15px; border-radius:15px; text-align:center; border:1px solid rgba(255,255,255,0.1); transition:0.3s;" onmouseover="this.style.background='rgba(255, 255, 255, 0.1)'" onmouseout="this.style.background='rgba(255, 255, 255, 0.05)'">
                    <div style="font-size:0.75rem; text-transform:uppercase; opacity:0.6; margin-bottom:5px;">Remaining</div>
                    <div style="font-size:1.5rem; font-weight:800; color:#ff7675;"><?= number_format($pending_all) ?></div>
                </a>
            </div>
        </div>
        <!-- Abstract Decoration -->
        <i class="fas fa-magic" style="position:absolute; right:-20px; bottom:-20px; font-size:10rem; opacity:0.05; transform:rotate(-15deg);"></i>
    </div>

    <!-- ✅ Today's API Usage Stats -->
    <div class="card">
        <h3 class="card-title"><i class="fas fa-chart-bar"></i> Today's API Usage</h3>
        <?php
        $providerLabels = [
            'gemini'     => ['label' => 'Gemini',     'limit' => 1400],
            'groq'       => ['label' => 'Groq',       'limit' => 13000],
            'openrouter' => ['label' => 'OpenRouter',  'limit' => 180],
            'mistral'    => ['label' => 'Mistral',     'limit' => 900],
            'together'   => ['label' => 'Together AI', 'limit' => 400],
            'cohere'     => ['label' => 'Cohere',      'limit' => 30],
        ];
        ?>
        <div class="stats-grid">
            <?php foreach ($providerLabels as $pid => $info):
                $used  = (int)($statsMap[$pid]['success_count'] ?? 0);
                $limit = $info['limit'];
                $pct   = $limit > 0 ? min(100, round(($used / $limit) * 100)) : 0;
                $cls   = $pct >= 90 ? 'danger' : ($pct >= 70 ? 'warning' : '');
                $hasKey = !empty($apiKeys[$pid . '_api_key']);
            ?>
            <div class="stat-card <?= $hasKey ? 'active' : '' ?>">
                <div class="stat-name"><?= $info['label'] ?> <?= !$hasKey ? '🔑' : '✅' ?></div>
                <div class="stat-count"><?= $used ?></div>
                <div class="stat-limit">/ <?= number_format($limit) ?> today</div>
                <div class="stat-bar">
                    <div class="stat-bar-fill <?= $cls ?>" style="width:<?= $pct ?>%"></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <p style="font-size:0.8rem;color:#999;"><i class="fas fa-info-circle"></i> ✅ = API key configured &nbsp;|&nbsp; 🔑 = No key added yet &nbsp;|&nbsp; Counts reset at midnight</p>
    </div>

    <!-- API Keys Configuration -->
    <div class="card">
        <h3 class="card-title"><i class="fas fa-key"></i> AI Fallback Configuration</h3>
        <form method="POST">
            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:20px;">
                <div class="input-group">
                    <label class="input-label">1. Google Gemini (Primary) — 1,500/day free</label>
                    <input type="password" name="gemini_api_key" value="<?= htmlspecialchars($gemini_api_key) ?>" class="input-control" placeholder="AIza...">
                </div>
                <div class="input-group">
                    <label class="input-label">2. Groq API (Fastest) — 14,400/day free</label>
                    <input type="password" name="groq_api_key" value="<?= htmlspecialchars($groq_api_key) ?>" class="input-control" placeholder="gsk_...">
                </div>
                <div class="input-group">
                    <label class="input-label">3. OpenRouter — ~200/day free models</label>
                    <input type="password" name="openrouter_api_key" value="<?= htmlspecialchars($openrouter_api_key) ?>" class="input-control" placeholder="sk-or-...">
                </div>
                <div class="input-group">
                    <label class="input-label">4. Mistral AI — Generous monthly free tier</label>
                    <input type="password" name="mistral_api_key" value="<?= htmlspecialchars($mistral_api_key) ?>" class="input-control" placeholder="...">
                </div>
                <div class="input-group">
                    <label class="input-label">5. Together AI — $25 free credits</label>
                    <input type="password" name="together_api_key" value="<?= htmlspecialchars($together_api_key) ?>" class="input-control" placeholder="...">
                </div>
                <div class="input-group">
                    <label class="input-label">6. Cohere — 1,000 req/month free</label>
                    <input type="password" name="cohere_api_key" value="<?= htmlspecialchars($cohere_api_key) ?>" class="input-control" placeholder="...">
                </div>
            </div>
            <p style="font-size:0.8rem;margin:10px 0 20px;color:#666;">
                <i class="fas fa-info-circle"></i> System tries keys in order 1→6. If one hits its daily limit or fails, it automatically moves to the next.
            </p>
            <button type="submit" name="save_api_key" class="btn btn-primary">
                <i class="fas fa-save"></i> Save All API Settings
            </button>
        </form>
    </div>

    <!-- Pages Table -->
    <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:10px;">
            <h3 class="card-title" style="margin-bottom:0;">
                <i class="fas fa-list"></i> Select Pages to Update
                <span style="font-size:0.8rem;font-weight:400;color:#999;margin-left:10px;"><?= number_format($total_records) ?> total pages</span>
            </h3>
            <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;">
                <select name="city" class="input-control" style="width:150px;padding:8px;">
                    <option value="">All Cities</option>
                    <?php foreach($cities as $c): ?>
                        <option value="<?= $c['slug'] ?>" <?= $city_filter == $c['slug'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="service" class="input-control" style="width:150px;padding:8px;">
                    <option value="">All Services</option>
                    <?php foreach($services as $s): ?>
                        <option value="<?= $s['slug'] ?>" <?= $service_filter == $s['slug'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="status" class="input-control" style="width:150px;padding:8px;">
                    <option value="">All Status</option>
                    <option value="done" <?= $status_filter == 'done' ? 'selected' : '' ?>>AI Done</option>
                    <option value="pending" <?= $status_filter == 'pending' ? 'selected' : '' ?>>AI Pending</option>
                </select>
                <button type="submit" class="btn btn-primary" style="padding:8px 15px;">
                    <i class="fas fa-filter"></i> Filter
                </button>
            </form>
        </div>

        <div class="table-wrap">
            <table id="contentTable">
                <thead>
                    <tr>
                        <th width="50" style="text-align:center;"><input type="checkbox" id="selectAll"></th>
                        <th>Page (Service / City)</th>
                        <th width="140">Update Count</th>
                        <th width="180">Last Update</th>
                        <th width="130" style="text-align:center;">Manual Check</th>
                        <th width="160" style="text-align:center;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($rows as $row): ?>
                    <tr data-id="<?= $row['id'] ?>">
                        <td class="checkbox-container">
                            <input type="checkbox" class="row-check" value="<?= $row['id'] ?>">
                        </td>
                        <td>
                            <strong><?= htmlspecialchars($row['service']) ?></strong><br>
                            <span style="font-size:0.8rem;color:#666;"><?= htmlspecialchars($row['city']) ?></span>
                        </td>
                        <td>
                            <span class="badge badge-count"><?= $row['content_update_count'] ?> times</span>
                        </td>
                        <td>
                            <span class="last-update" style="font-size:0.8rem;">
                                <?= $row['last_ai_update'] ? date('d M, Y H:i', strtotime($row['last_ai_update'])) : 'Never' ?>
                            </span>
                            <!-- ✅ FIX 3: Shows which API was used -->
                            <span class="provider-tag provider-display" style="display:none;"></span>
                        </td>
                        <td style="text-align:center;">
                            <input type="checkbox" class="manual-check"
                                <?= $row['is_manually_updated'] ? 'checked' : '' ?>
                                onchange="toggleManual(<?= $row['id'] ?>, this.checked)">
                        </td>
                        <td style="text-align:center;">
                            <button class="btn btn-success" style="padding:6px 12px;font-size:0.8rem;" onclick="generateAI(<?= $row['id'] ?>, this)">
                                <i class="fas fa-magic"></i> Generate
                            </button>
                            <div class="spinner"></div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <ul class="pagination">
            <?php for($i = 1; $i <= $total_pages; $i++): ?>
                <li class="<?= $page == $i ? 'active' : '' ?>">
                    <a href="?page=<?= $i ?>&city=<?= urlencode($city_filter) ?>&service=<?= urlencode($service_filter) ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </div>

    <!-- Bulk Action Bar -->
    <div class="bulk-bar" id="bulkBar" style="display:none;">
        <div style="color:#fff;">
            <i class="fas fa-check-square"></i>
            <span id="selectedCount">0</span> pages selected
        </div>
        <div style="display:flex;align-items:center;gap:15px;">
            <!-- ✅ FIX 5: Configurable delay -->
            <label style="color:#ccc;font-size:0.85rem;">
                Delay:
                <select id="bulkDelay" style="background:#333;color:#fff;border:1px solid #555;border-radius:5px;padding:4px 8px;">
                    <option value="3000">3s (Groq/Mistral)</option>
                    <option value="5000" selected>5s (Standard)</option>
                    <option value="8000">8s (Safe/Gemini)</option>
                    <option value="12000">12s (Very Safe)</option>
                </select>
            </label>
            <button class="btn btn-primary" onclick="generateBulk()">
                <i class="fas fa-magic"></i> Generate All Selected ✨
            </button>
        </div>
    </div>
</div>

<script>
    // ── Select All ──────────────────────────────────────────
    document.getElementById('selectAll').addEventListener('change', function() {
        document.querySelectorAll('.row-check').forEach(c => c.checked = this.checked);
        updateBulkBar();
    });
    document.querySelectorAll('.row-check').forEach(c => c.addEventListener('change', updateBulkBar));

    function updateBulkBar() {
        const selected = document.querySelectorAll('.row-check:checked').length;
        document.getElementById('selectedCount').innerText = selected;
        document.getElementById('bulkBar').style.display = selected > 0 ? 'flex' : 'none';
    }

    // ── Toggle Manual ───────────────────────────────────────
    function toggleManual(id, isChecked) {
        const formData = new FormData();
        formData.append('toggle_manual', '1');
        formData.append('id', id);
        formData.append('value', isChecked ? '1' : '0');
        fetch(window.location.href, { method: 'POST', body: formData });
    }

    // ── Single Generate ─────────────────────────────────────
    async function generateAI(id, btn) {
        const row     = btn.closest('tr');
        const spinner = row.querySelector('.spinner');

        btn.style.display = 'none';
        spinner.style.display = 'block';

        const formData = new FormData();
        formData.append('generate_ai', '1');
        formData.append('id', id);

        try {
            const response = await fetch(window.location.href, { method: 'POST', body: formData });
            const text = await response.text();

            let result;
            try {
                result = JSON.parse(text);
            } catch (e) {
                console.error('Server returned invalid JSON:', text);
                alert('Server Error: Invalid response. Check browser console (F12) for details.');
                return;
            }

            if (result.success) {
                // Update count badge
                row.querySelector('.badge-count').innerText = result.new_count + ' times';

                // ✅ FIX 3: Show which provider was used
                const providerTag = row.querySelector('.provider-display');
                if (providerTag && result.provider) {
                    providerTag.innerText = '⚡ ' + result.provider;
                    providerTag.style.display = 'inline-block';
                }

                // Update timestamp
                const now    = new Date();
                const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                const ts     = `${String(now.getDate()).padStart(2,'0')} ${months[now.getMonth()]}, ${now.getFullYear()} ${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;
                const tsElem = row.querySelector('.last-update');
                if (tsElem) tsElem.innerText = ts;

            } else {
                alert('❌ Error: ' + result.error);
            }

        } catch (e) {
            console.error('Fetch error:', e);
            alert('Connection error. Check your internet or server.');
        } finally {
            btn.style.display = 'inline-flex';
            spinner.style.display = 'none';
        }
    }

    // ── Bulk Generate ───────────────────────────────────────
    async function generateBulk() {
        const selected = Array.from(document.querySelectorAll('.row-check:checked')).map(c => c.value);
        if (selected.length === 0) return;
        if (!confirm(`Generate content for ${selected.length} pages?\n\nThis may take a while. Do not close this tab.`)) return;

        const bulkBtn      = document.querySelector('#bulkBar button:last-child');
        const delayMs      = parseInt(document.getElementById('bulkDelay').value);
        const originalText = bulkBtn.innerHTML;
        bulkBtn.disabled   = true;

        let success = 0, failed = 0;

        for (let i = 0; i < selected.length; i++) {
            const id  = selected[i];
            bulkBtn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${i + 1} / ${selected.length} (✅${success} ❌${failed})`;

            const btn = document.querySelector(`tr[data-id="${id}"] .btn-success`);
            if (btn) {
                try {
                    await generateAI(id, btn);
                    success++;
                } catch(e) {
                    failed++;
                }
                // Delay between requests to respect rate limits
                if (i < selected.length - 1) {
                    await new Promise(resolve => setTimeout(resolve, delayMs));
                }
            }
        }

        bulkBtn.innerHTML = originalText;
        bulkBtn.disabled  = false;
        alert(`✅ Bulk generation complete!\nSuccess: ${success} | Failed: ${failed}`);
        location.reload(); // Refresh stats
    }
</script>
</body>
</html>
