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


// Enable error reporting
ini_set('display_errors', '1');
error_reporting(E_ALL);

// Handle API Key Save
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 Mark as Manually Updated
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_manual'])) {
    $id = $_POST['id'] ?? '';
    $val = $_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 Generation (Ajax)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_ai'])) {
    set_time_limit(180);
    $id = $_POST['id'] ?? '';
    
    // 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;
    }

    // Get API Key
    $stmt = $pdo->prepare("SELECT setting_value FROM finggu_settings WHERE setting_key = 'gemini_api_key'");
    $stmt->execute();
    $apiKey = $stmt->fetchColumn();

    if (!$apiKey) {
        echo json_encode(['success' => false, 'error' => 'API Key not found. Please add it first.']);
        exit;
    }

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

    // Construct High-End, Visually Rich Prompt
    $prompt = "You are a Professional UI Designer & SEO Expert.
    
    Task: Create a premium service page for '$serviceName' in '$cityName'.
    
    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\": \"High-CTR title for $cityName\",
      \"seo_description\": \"Engaging description under 160 chars\",
      \"seo_keywords\": \"local, keywords, list\",
      \"html_content\": \"<!-- AI_FULL_CONTENT --><div class='rich-content'>...</div>\"
    }

    CONTENT & DESIGN RULES:
    1. Use Tailwind CSS with colors: primary(#dc2626) and dark(#1A1A1A).
    2. Use FontAwesome 6 icons.
    3. Give a proper spacing after and before every heading .
    4. The 'html_content' MUST include LOCAL MARKET ANALYSIS (500+ words):
       - H2: '$cityName [Service] Market Insights'
       - 4-5 rich paragraphs with real local context, demographics, why this service matters here.  Also add 2 to 3 keywords which is high demand in the city for my services.
       - Use subheadings (H3) every paragraph
       - Inline stat callouts: e.g. <span class='font-bold text-red-600'>85%</span> of homeowners...
       - No cards here — flowing editorial prose with typographic emphasis
       - H1 or H2 heading with service + city name.
       - Build a high-quality 'Why Choose Us' section using a grid md:grid-cols-3 layout with 3 cards featuring a white background, #dc2626 icons, #111827 bold titles, 2-line descriptions, and a professional light border with a subtle hover shadow effect.
       - Create a premium 'Strategic Process' section for finggu.com using a grid md:grid-cols-4 layout featuring 4 numbered steps with a light border, #dc2626 accents, #111827 text, and a subtle connector line or arrow effect to show progress.
       - Generate a comprehensive 'Market Analysis' section for $cityName featuring 500+ words of deep local insights, demographic trends, and industry-specific growth data, styled with professional #111827 typography, clear subheadings.
       - An FAQ section with 5 detailed questions based on service and city name.
    5. Keep the HTML structure professional, clean, and highly visual using relative positioning, gradients, and rounded corners font-family: Inter, sans-serif;  (rounded-3xl).";


    $aiResult = ai_generate_with_fallback($prompt, $pdo);

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

    // Enhanced Robust JSON Extraction & Cleaning
    $aiResponseJSON = trim($aiResult['content']);
    $providerUsed = $aiResult['provider'];

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

    // 2. Extract first { to last }
    $firstBracket = strpos($aiResponseJSON, '{');
    $lastBracket = strrpos($aiResponseJSON, '}');
    if ($firstBracket !== false && $lastBracket !== false && $lastBracket > $firstBracket) {
        $aiResponseJSON = substr($aiResponseJSON, $firstBracket, $lastBracket - $firstBracket + 1);
    }

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

    // 4. Initial attempt at decoding
    $aiData = json_decode($aiResponseJSON, true);

    // 5. Fallback retry for "Control character error" (common with unescaped newlines in AI strings)
    if (json_last_error() === JSON_ERROR_CTRL_CHAR) {
        // Try to escape literal newlines inside JSON string values
        $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);
    }
    
    // Check if JSON is still invalid or content is missing
    if (json_last_error() === JSON_ERROR_NONE && !empty($aiData['html_content'])) {
        try {
            // Check if columns exist first to avoid crash
            $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;
            }

            // Update database with SEO tags and content
            $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
            ");
            
            // Ensure SEO fields are strings (AI sometimes returns arrays)
            $keywords = $aiData['seo_keywords'] ?? '';
            if (is_array($keywords)) {
                $keywords = implode(', ', $keywords);
            }
            
            $updateStmt->execute([
                ':content' => $aiData['html_content'],
                ':title' => (string)($aiData['seo_title'] ?? ''),
                ':desc' => (string)($aiData['seo_description'] ?? ''),
                ':keywords' => $keywords,
                ':id' => $id
            ]);
            
            echo json_encode([
                'success' => true, 
                'new_count' => $pdo->query("SELECT content_update_count FROM city_service WHERE id = $id")->fetchColumn(),
                'provider' => $providerUsed
            ]);

        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database Error: ' . $e->getMessage()]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'AI returned invalid JSON or empty content. JSON Error: ' . json_last_error_msg()]);
    }
    exit;
}

// Filters
$search = $_GET['search'] ?? '';
$city_filter = $_GET['city'] ?? '';
$service_filter = $_GET['service'] ?? '';
$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;
}

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

// Count
$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);

// Check if columns exist before running the query
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 new AI Content System requires some database changes to track updates and manual checks.</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
$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();

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

// Get all API keys for 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'] ?? '';



?>
<!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 */
        .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; }

        /* Content */
        .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); }

        /* Form Elements */
        .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; }
        .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); }

        /* Table */
        .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-ai { background: #d1ecf1; color: #0c5460; }
        .badge-manual { background: #fff3cd; color: #856404; }

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

        .status-msg { margin-top: 10px; font-size: 0.9rem; font-weight: 600; }
        .success { color: var(--success); }
        .error { color: var(--danger); }

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

        /* Bulk Bar */
        .bulk-bar { position: sticky; bottom: 20px; left: 0; right: 0; 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; }
        .pagination li { margin: 0 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; }
    </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; ?>

        <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)</label>
                        <input type="password" name="gemini_api_key" value="<?= htmlspecialchars($gemini_api_key) ?>" class="input-control" placeholder="Gemini API Key">
                    </div>
                    <div class="input-group">
                        <label class="input-label">2. Groq API (Fastest)</label>
                        <input type="password" name="groq_api_key" value="<?= htmlspecialchars($groq_api_key) ?>" class="input-control" placeholder="Groq API Key">
                    </div>
                    <div class="input-group">
                        <label class="input-label">3. OpenRouter (Unlimited)</label>
                        <input type="password" name="openrouter_api_key" value="<?= htmlspecialchars($openrouter_api_key) ?>" class="input-control" placeholder="OpenRouter API Key">
                    </div>
                    <div class="input-group">
                        <label class="input-label">4. Mistral AI</label>
                        <input type="password" name="mistral_api_key" value="<?= htmlspecialchars($mistral_api_key) ?>" class="input-control" placeholder="Mistral AI Key">
                    </div>
                    <div class="input-group">
                        <label class="input-label">5. Together AI</label>
                        <input type="password" name="together_api_key" value="<?= htmlspecialchars($together_api_key) ?>" class="input-control" placeholder="Together AI Key">
                    </div>
                    <div class="input-group">
                        <label class="input-label">6. Cohere</label>
                        <input type="password" name="cohere_api_key" value="<?= htmlspecialchars($cohere_api_key) ?>" class="input-control" placeholder="Cohere API Key">
                    </div>
                </div>

                <p style="font-size: 0.8rem; margin: 10px 0 20px; color: #666;">
                    <i class="fas fa-info-circle"></i> System will try keys in order. If Gemini fails or hits limit, it will automatically fallback to Groq, then OpenRouter, etc.
                </p>
                <button type="submit" name="save_api_key" class="btn btn-primary">Save All API Settings</button>
            </form>
        </div>


        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h3 class="card-title" style="margin-bottom:0;"><i class="fas fa-list"></i> Select Pages to Update</h3>
                <div style="display:flex; gap:10px;">
                    <form method="GET" style="display:flex; gap:10px;">
                        <select name="city" class="input-control" style="width:150px; padding:5px;">
                            <option value="">All Cities</option>
                            <?php foreach($cities as $c): ?>
                                <option value="<?= $c['slug'] ?>" <?= $city_filter == $c['slug'] ? 'selected' : '' ?>><?= $c['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name="service" class="input-control" style="width:150px; padding:5px;">
                            <option value="">All Services</option>
                            <?php foreach($services as $s): ?>
                                <option value="<?= $s['slug'] ?>" <?= $service_filter == $s['slug'] ? 'selected' : '' ?>><?= $s['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" class="btn btn-primary" style="padding:5px 15px;">Filter</button>
                    </form>
                </div>
            </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="120">Update Count</th>
                            <th width="150">Last Update</th>
                            <th width="150" style="text-align:center;">Manual Check</th>
                            <th width="150" 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><?= $row['service'] ?></strong><br>
                                <span style="font-size:0.8rem; color:#666;"><?= $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></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:5px 10px; font-size:0.8rem;" onclick="generateAI(<?= $row['id'] ?>, this)">
                                    <i class="fas fa-magic"></i> Generate
                                </button>
                                <div class="spinner" style="margin: 0 auto; width: 20px; height: 20px; border-width:2px;"></div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

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

        <div class="bulk-bar" id="bulkBar" style="display:none;">
            <div>
                <span id="selectedCount">0</span> pages selected
            </div>
            <div>
                <button class="btn btn-primary" onclick="generateBulk()">Generate for All Selected ✨</button>
            </div>
        </div>
    </div>

    <script>
        // Select All toggle
        document.getElementById('selectAll').addEventListener('change', function() {
            const checks = document.querySelectorAll('.row-check');
            checks.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';
        }

        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
            });
        }

        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('JSON Parse Error. Server output:', text);
                    alert('Server Error: The server returned an invalid response. Check the browser console (F12) for the full error.');
                    return;
                }
                
                if (result.success) {
                    row.querySelector('.badge-count').innerText = result.new_count + ' times';
                    
                    // Update the timestamp in the UI
                    const now = new Date();
                    const day = String(now.getDate()).padStart(2, '0');
                    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                    const month = months[now.getMonth()];
                    const year = now.getFullYear();
                    const hours = String(now.getHours()).padStart(2, '0');
                    const mins = String(now.getMinutes()).padStart(2, '0');
                    
                    const timestampElem = row.querySelector('.last-update');
                    if (timestampElem) {
                        timestampElem.innerText = `${day} ${month}, ${year} ${hours}:${mins}`;
                    }
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (e) {
                console.error('Fetch error:', e);
                alert('Connection error. The network or server prevented the request.');
            } finally {
                btn.style.display = 'inline-flex';
                spinner.style.display = 'none';
            }
        }

        async function generateBulk() {
            const selected = Array.from(document.querySelectorAll('.row-check:checked')).map(c => c.value);
            if (!confirm(`Are you sure you want to generate content for ${selected.length} pages?`)) return;

            const bulkBtn = document.querySelector('#bulkBar button');
            const originalText = bulkBtn.innerText;
            bulkBtn.disabled = true;

            let count = 0;
            for (const id of selected) {
                count++;
                bulkBtn.innerText = `Generating ${count} of ${selected.length}...`;
                const btn = document.querySelector(`tr[data-id="${id}"] button`);
                if (btn) {
                    await generateAI(id, btn);
                    // Add 5 second delay to stay safely under free tier rate limits (15 RPM)
                    await new Promise(resolve => setTimeout(resolve, 5000));
                }
            }
            bulkBtn.innerText = originalText;
            bulkBtn.disabled = false;
            alert('Bulk generation completed!');
        }
    </script>
</body>
</html>
