<?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 World-Class UI/UX Designer and SEO Expert. Your mission is to create a STUNNING, HIGH-CONVERTING service page for '$serviceName' in '$cityName'.
    
    CRITICAL: You MUST return a valid JSON object.
    
    AESTHETIC GUIDELINES:
    - Use the Tailwind CSS framework.
    - Colors to use: 'primary' (#FF0000), 'primary-dark' (#CC0000), 'accent' (#43CBF5), and 'dark' (#1A1A1A).
    - Design Style: High-end SaaS/Tech style. Use gradients (e.g., bg-gradient-to-r from-red-600 to-red-800), glassmorphism (bg-white/10 backdrop-blur-md), and soft shadows.
    - Layout: Use varied grid structures, overlapping elements, and ample white space.
    - Visuals: Use FontAwesome 6 icons (fas fa-...).
    
    JSON Fields:
    1. 'seo_title': High-CTR meta title (under 60 chars) including '$cityName'.
    2. 'seo_description': Engaging meta description (under 160 chars).
    3. 'seo_keywords': 10-15 local keywords.
    4. 'html_content': Use the EXACT HTML structure below but FILL IT with rich, deep-dive content:
       
       <!-- AI_FULL_CONTENT -->
       <section class='relative py-20 overflow-hidden'>
          <div class='absolute top-0 right-0 -mr-20 -mt-20 w-96 h-96 bg-red-50 rounded-full blur-3xl opacity-50'></div>
          <div class='relative container mx-auto px-4'>
             <div class='max-w-3xl'>
                <h2 class='text-4xl md:text-5xl font-extrabold mb-6 leading-tight'>
                   Next-Gen <span class='text-transparent bg-clip-text bg-gradient-to-r from-red-600 to-red-800'>$serviceName</span> 
                   Excellence in $cityName
                </h2>
                <p class='text-xl text-gray-600 leading-relaxed mb-8'>[250+ word deep-dive into why $serviceName is critical for businesses in $cityName, mentioning local market trends and growth opportunities]</p>
                <div class='flex flex-wrap gap-4'>
                   <span class='px-4 py-2 bg-red-50 text-red-600 rounded-full text-sm font-bold border border-red-100'>#1 Rated in $cityName</span>
                   <span class='px-4 py-2 bg-blue-50 text-blue-600 rounded-full text-sm font-bold border border-blue-100'>$serviceName Experts</span>
                </div>
             </div>
          </div>
       </section>

       <section class='py-20 bg-gray-50 rounded-[3rem] my-12 mx-4'>
          <div class='container mx-auto px-6'>
             <div class='text-center mb-16'>
                <h3 class='text-3xl font-bold mb-4'>Why Choose Finggu for $serviceName?</h3>
                <p class='text-gray-600 max-w-2xl mx-auto'>We don't just provide services; we build local success stories in $cityName through strategic digital intervention.</p>
             </div>
             <div class='grid md:grid-cols-3 gap-8'>
                <!-- Create 3 unique, detailed service benefit cards with icons, rich descriptions (100 words each), and hover effects -->
                <div class='bg-white p-8 rounded-2xl shadow-sm hover:shadow-xl transition-all border border-gray-100 group'>
                   <div class='w-14 h-14 bg-red-100 rounded-xl flex items-center justify-center mb-6 group-hover:scale-110 transition-transform'>
                      <i class='fas fa-chart-line text-2xl text-red-600'></i>
                   </div>
                   <h4 class='text-xl font-bold mb-4'>[Benefit Title]</h4>
                   <p class='text-gray-600 text-sm'>[Detailed benefit description focused on $cityName market]</p>
                </div>
                <!-- Card 2 & 3 -->
             </div>
          </div>
       </section>

       <section class='py-20 bg-white border-y border-gray-100'>
          <div class='container mx-auto px-4'>
             <div class='flex flex-col md:flex-row items-center gap-16'>
                <div class='md:w-1/2'>
                   <h3 class='text-3xl font-bold mb-8'>Strategic $serviceName Workflow</h3>
                   <div class='space-y-8'>
                      <!-- 4 Step Process with high-end visual indicators -->
                      <div class='flex gap-6'>
                         <div class='flex-shrink-0 w-12 h-12 rounded-full bg-red-600 text-white flex items-center justify-center font-bold shadow-lg shadow-red-200'>1</div>
                         <div><h4 class='font-bold mb-2'>[Workflow Step]</h4><p class='text-gray-600'>[Deep detail about this phase of $serviceName]</p></div>
                      </div>
                      <!-- Steps 2, 3, 4 -->
                   </div>
                </div>
                <div class='md:w-1/2 bg-gradient-to-br from-red-600 to-red-900 p-1 rounded-3xl'>
                   <div class='bg-white p-10 rounded-[1.4rem]'>
                      <h4 class='text-2xl font-bold mb-6 text-gray-900'>$cityName Market Analysis</h4>
                      <p class='text-gray-700 leading-relaxed mb-6'>[500+ words of extremely high-quality industry-specific content for $serviceName, focusing on $cityName competition, consumer behavior, and technical optimization strategies]</p>
                   </div>
                </div>
             </div>
          </div>
       </section>

       <section class='py-20'>
          <div class='container mx-auto px-4 max-w-4xl'>
             <h3 class='text-3xl font-bold mb-12 text-center'>Frequently Asked Questions</h3>
             <div class='space-y-6'>
                <!-- 5 FAQ blocks with a modern professional accordion-style look (closed by default) -->
                <div class='border border-gray-100 rounded-xl p-6 hover:bg-gray-50 transition-colors'>
                   <h4 class='text-lg font-bold mb-3 flex items-center'><i class='fas fa-question-circle text-red-600 mr-3'></i> [FAQ Question?]</h4>
                   <p class='text-gray-600'>[Comprehensive expert answer]</p>
                </div>
             </div>
          </div>
       </section>";

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

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

    $aiResponseJSON = $aiResult['content'];
    $providerUsed = $aiResult['provider'];


    // Clean up content (remove markdown code blocks if any to get valid JSON)
    $aiResponseJSON = preg_replace('/```json/', '', $aiResponseJSON);
    $aiResponseJSON = preg_replace('/```/', '', $aiResponseJSON);
    $aiResponseJSON = trim($aiResponseJSON);

    $aiData = json_decode($aiResponseJSON, true);
    
    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 = 20;
$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 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';
                    alert('Success! Content updated using ' + (result.provider || 'AI') + '.');
                } 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>
