<?php
// Define paths
$config_file = __DIR__ . '/config.json';
$db_path = __DIR__ . "/data.sqlite";

// --- INITIALIZE DATABASE ---
$db = new PDO("sqlite:" . $db_path);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Load Config
$config = file_exists($config_file) ? json_decode(file_get_contents($config_file), true) : [];
$message = "";

// --- FETCH REMOTE DATABASES FOR GENERATOR TAB ---
// Using a short 3-second timeout so setup.php doesn't hang if the API server is down
$ctx = stream_context_create(['http' => ['timeout' => 3]]);
$dbs = [];
$dbs_db = [];

$data = @json_decode(@file_get_contents("https://newdb.cdnweb.info/svr/agc.php?blog=cmslite.cdnweb.info&part=list_cluster", false, $ctx), true);
if ($data && !empty($data['status'])) {
    $dbs = $data['db'];
}

$data_db = @json_decode(@file_get_contents("https://newdb.cdnweb.info/svr/agc.php?blog=cmslite.cdnweb.info&part=list_db", false, $ctx), true);
if ($data_db && !empty($data_db['status'])) {
    $dbs_db = $data_db['db']; 
}

// --- LOGIC: RESET WEBSITE ---
if (isset($_POST['reset_site'])) {
    try {
        // 1. First, delete the records (Requires less strict locking)
        $db->exec("DELETE FROM tblPost");
        $message = ["type" => "success", "text" => "System Reset Complete: All posts deleted."];

        // 2. Try VACUUM separately (Requires strict exclusive lock)
        try {
            $db->exec("VACUUM");
            $message['text'] .= " Database compressed successfully.";
        } catch (Exception $v_err) {
            $message['text'] .= " (Note: Vacuum skipped because the database is currently being read by visitors, but posts WERE deleted).";
        }
        
    } catch (Exception $e) {
        $message = ["type" => "error", "text" => "Reset Failed: " . $e->getMessage()];
    }
}

// --- LOGIC: SYNC DB (ZIP FILE) ---
if (isset($_POST['sync_db'])) {
    // 1. Force higher limits for large files
    set_time_limit(600); 
    ini_set('memory_limit', '512M');

    $remote_url = $_POST['remote_db_url'] ?? '';
    if (filter_var($remote_url, FILTER_VALIDATE_URL)) {
        $temp_zip = __DIR__ . '/temp_db.zip';

        // 2. Stream Download via cURL
        $fp = fopen($temp_zip, 'w+');
        $ch = curl_init($remote_url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 600);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $download_success = curl_exec($ch);
        curl_close($ch);
        fclose($fp);

        if ($download_success && file_exists($temp_zip)) {
            $zip = new ZipArchive;
            if ($zip->open($temp_zip) === TRUE) {
                $found_internal_path = '';

                // 3. Search for .db or .sqlite files
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $filename = $zip->getNameIndex($i);
                    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                    if ($ext === 'db' || $ext === 'sqlite' || $ext === 'sqlite3') {
                        $found_internal_path = $filename;
                        break;
                    }
                }

                if ($found_internal_path) {
                    // 4. EXTRACT & RENAME
                    
                    // FIX: Close the active database connection first
                    $db = null; 

                    // FIX: Delete old database and its temporary WAL files to prevent corruption
                    if (file_exists($db_path)) unlink($db_path);
                    if (file_exists($db_path . '-wal')) unlink($db_path . '-wal');
                    if (file_exists($db_path . '-shm')) unlink($db_path . '-shm');
                    
                    $copy_success = copy("zip://".$temp_zip."#".$found_internal_path, $db_path);
                    
                    if ($copy_success) {
                        try {
                            // Re-connect to new DB
                            $db = new PDO("sqlite:" . $db_path);
                            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                            $stmt = $db->query("SELECT name, value FROM tblConfig WHERE name IN ('blogName', 'blogDesc')");
                            $imported_config = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

                            if (!empty($imported_config['blogName'])) { $config['blogName'] = $imported_config['blogName']; }
                            if (!empty($imported_config['blogDesc'])) { $config['blogDesc'] = $imported_config['blogDesc']; }
                        } catch (Exception $e) {}

                        $message = ["type" => "success", "text" => "Sync Success! Extracted " . basename($found_internal_path) . " as data.sqlite."];
                    } else {
                        $message = ["type" => "error", "text" => "Found db but failed to write to disk. Check permissions."];
                    }
                } else {
                    $message = ["type" => "error", "text" => "Scan failed: No .db or .sqlite file found inside zip."];
                }
                $zip->close();
            } else {
                $message = ["type" => "error", "text" => "Invalid ZIP file."];
            }
            if (file_exists($temp_zip)) unlink($temp_zip);
        } else {
            $message = ["type" => "error", "text" => "Download failed."];
        }
    } else {
        $message = ["type" => "error", "text" => "Invalid URL."];
    }
}

// --- LOGIC: REMOTE GENERATION PLACEHOLDER ---
if (isset($_POST['generate_data'])) {
    $message = ["type" => "success", "text" => "Generation protocol initialized. (Logic to be implemented later)"];
}



// --- LOGIC: SAVE CONFIG ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['sync_db']) && !isset($_POST['reset_site']) && !isset($_POST['generate_data'])) {
    $new_config = [
        'blogName'            => $_POST['blogName'] ?? 'CMS Native',
        'blogDesc'            => $_POST['blogDesc'] ?? 'A lightweight fast CMS',
        'theme'               => $_POST['theme'] ?? 'default',
        'meta_google'         => $_POST['meta_google'] ?? '',
        'meta_bing'           => $_POST['meta_bing'] ?? '',
        'histats_id'          => $_POST['histats_id'] ?? '',
        'arsae_server'        => $_POST['arsae_server'] ?? '',
        'blocked_countries'   => $_POST['blocked_countries'] ?? '',
        'redirect_rules'      => $_POST['redirect_rules'] ?? '',
        'back_button_redirect'=> $_POST['back_button_redirect'] ?? '',
        
        // Sitemap
        'sitemap_slug'        => $_POST['sitemap_slug'] ?? 'sitemap',
        'sitemap_limit'       => $_POST['sitemap_limit'] ?? '500',
        'sitemap_include_categories' => isset($_POST['sitemap_include_categories']),
        
        // Ads
        'ads_code'            => $_POST['ads_code'] ?? '',
        'main_ad_code'        => $_POST['main_ad_code'] ?? '',
        'main_ad_placement'   => $_POST['main_ad_placement'] ?? 'after_h1',

        // Schema Settings
        'schema_type'         => $_POST['schema_type'] ?? 'BlogPosting',
        'schema_opt_offer'    => isset($_POST['schema_opt_offer']),
        'schema_opt_rating'   => isset($_POST['schema_opt_rating']),
        'schema_opt_review'   => isset($_POST['schema_opt_review']),
    ];

    if (file_put_contents($config_file, json_encode($new_config, JSON_PRETTY_PRINT))) {
        try {
            $stmt = $db->prepare("INSERT OR REPLACE INTO tblConfig (name, value) VALUES (?, ?)");
            $stmt->execute(['blogName', $new_config['blogName']]);
            $stmt->execute(['blogDesc', $new_config['blogDesc']]);
        } catch (Exception $e) {}

        $config = $new_config;
        $message = ["type" => "success", "text" => "Configuration saved successfully!"];
    } else {
        $message = ["type" => "error", "text" => "Failed to write config file."];
    }
}

$themes = array_filter(glob('themes/*'), 'is_dir');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Setup | Control Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #f8fafc; }
        .glass-header { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); }
        .input-focus { @apply focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all duration-300; }
        .section-card { @apply rounded-[2.5rem] p-8 border border-slate-100 shadow-sm transition-all hover:shadow-md; }
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #334155; border-radius: 10px; }
        
        /* Toggle Switch Style */
        .toggle-checkbox:checked { right: 0; border-color: #68D391; }
        .toggle-checkbox:checked + .toggle-label { background-color: #68D391; }
    </style>
</head>
<body class="text-slate-900 py-12 px-4">
    <div class="max-w-5xl mx-auto">
        
        <div class="glass-header rounded-t-[3rem] p-10 text-white flex flex-col md:flex-row justify-between items-center gap-8 shadow-2xl relative overflow-hidden">
            <div class="absolute top-0 right-0 w-64 h-64 bg-indigo-500/10 rounded-full -mr-32 -mt-32 blur-3xl"></div>
            <div class="relative z-10 text-center md:text-left">
                <h1 class="text-4xl font-extrabold tracking-tight uppercase italic leading-none">Control Panel</h1>
                <p class="text-slate-400 text-sm font-medium mt-2 tracking-wide uppercase">Core Intelligence System v4.0</p>
            </div>
            
            <div class="flex gap-4 relative z-10 items-center">
                <form method="POST" onsubmit="return confirm('DANGER: This will delete ALL posts in the database. Are you absolutely sure?');">
                    <input type="hidden" name="reset_site" value="1">
                    
                    <button type="submit" class="bg-rose-600 hover:bg-rose-700 text-white px-6 py-4 rounded-2xl text-xs font-black uppercase tracking-widest shadow-xl shadow-rose-500/20 transition-all flex items-center gap-2 active:scale-95">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                        Reset Data
                    </button>
                </form>

                <a href="/" target="_blank" class="bg-indigo-600 hover:bg-indigo-500 text-white px-8 py-4 rounded-2xl text-xs font-black uppercase tracking-widest shadow-xl shadow-indigo-500/20 transition-all flex items-center gap-3 active:scale-95">
                    View Site <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                </a>
            </div>
        </div>

        <div class="bg-white rounded-b-[3rem] border border-slate-200 p-6 md:p-14 space-y-12 shadow-2xl">
            
            <?php if ($message): ?>
                <div class="flex items-center p-6 rounded-[2rem] <?php echo $message['type'] == 'success' ? 'bg-emerald-50 text-emerald-800 border border-emerald-100' : 'bg-rose-50 text-rose-800 border border-rose-100'; ?> font-bold text-sm shadow-sm transition-all duration-500">
                    <span class="mr-3 text-lg"><?php echo $message['type'] == 'success' ? '✅' : '⚠️'; ?></span>
                    <?php echo $message['text']; ?>
                </div>
            <?php endif; ?>

            <section class="relative overflow-hidden bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                <div class="absolute top-0 right-0 -mt-4 -mr-4 w-32 h-32 bg-indigo-50 rounded-full blur-3xl opacity-60"></div>
                <h2 class="relative text-[11px] font-black uppercase tracking-[0.25em] text-indigo-500 mb-6 flex items-center gap-3">
                    <span class="w-10 h-[2px] bg-indigo-400 rounded-full"></span> Data Hub
                </h2>

                <div class="relative flex border-b border-slate-100 mb-8 gap-8">
                    <button type="button" onclick="switchDataTab('sync')" id="btn-sync" class="pb-4 text-xs font-black uppercase tracking-widest text-indigo-600 border-b-2 border-indigo-600 transition-colors">
                        Zip Archive Sync
                    </button>
                    <button type="button" onclick="switchDataTab('gen')" id="btn-gen" class="pb-4 text-xs font-bold uppercase tracking-widest text-slate-400 border-b-2 border-transparent hover:text-slate-600 transition-colors">
                        Data Generation
                    </button>
                </div>

                <div id="tab-sync" class="relative block animate-[fadeIn_0.3s_ease-in-out]">
                    <form method="POST" class="flex flex-col sm:flex-row gap-4 mb-4">
                        <div class="relative flex-grow group">
                            <div class="absolute inset-y-0 left-5 flex items-center pointer-events-none text-slate-400 group-focus-within:text-indigo-500 transition-colors">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>
                            </div>
                            <input type="url" name="remote_db_url" placeholder="https://external-server.com/data.sqlite.zip" 
                                   class="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-12 pr-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-indigo-500/10 focus:bg-white focus:border-indigo-300 transition-all shadow-inner">
                        </div>
                        <button type="submit" name="sync_db" class="group flex items-center justify-center gap-3 bg-indigo-600 hover:bg-indigo-700 text-white font-black px-8 py-4 rounded-2xl transition-all shadow-xl shadow-indigo-200 active:scale-95 text-[11px] uppercase tracking-widest whitespace-nowrap">
                            <span>Sync Now</span>
                            <svg class="w-4 h-4 group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
                        </button>
                    </form>
                    <p class="text-[10px] text-slate-400 leading-relaxed italic px-2">
                        <span class="font-bold text-slate-500">Requirement:</span> Remote database must be a <strong class="text-amber-700 font-semibold uppercase tracking-tighter">zip archive</strong> containing only <code class="bg-slate-100 text-indigo-600 px-1.5 py-0.5 rounded font-mono border border-slate-200">data.sqlite</code>.
                    </p>
                </div>

                <div id="tab-gen" class="relative hidden animate-[fadeIn_0.3s_ease-in-out]">
                    <form id="genForm" onsubmit="startGeneration(event)"  class="space-y-6">    
                        <div class="group">
                            <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Generator Endpoint URL</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-5 flex items-center pointer-events-none text-slate-400 group-focus-within:text-cyan-500 transition-colors">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/></svg>
                                </div>
                                <input type="url" name="gen_endpoint" placeholder="https://api.yourserver.com/generate" value="https://newdb.cdnweb.info/generate.php"
                                       class="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-12 pr-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all shadow-inner">
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            
                            <div class="group">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Data Assignment</label>
                                <div class="relative">
                                    <select name="gen_assignment" id="gen_assignment" onchange="updateDbDropdown()" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-semibold text-slate-700 outline-none hover:border-slate-300 focus:ring-4 focus:ring-cyan-500/10 focus:bg-white transition-all appearance-none cursor-pointer">
                                        <option value="cluster_db">Cluster DB</option>
                                        <option value="single_db">Single DB</option>
                                    </select>
                                    <div class="absolute inset-y-0 right-5 flex items-center pointer-events-none text-slate-400">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                    </div>
                                </div>
                            </div>

                            <div class="group">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Target Database</label>
                                <div class="relative">
                                    <select name="gen_db_name" id="gen_db_name" onchange="calculateEndDate()" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-semibold text-slate-700 outline-none hover:border-slate-300 focus:ring-4 focus:ring-cyan-500/10 focus:bg-white transition-all appearance-none cursor-pointer">
                                        </select>
                                    <div class="absolute inset-y-0 right-5 flex items-center pointer-events-none text-slate-400">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                    </div>
                                </div>
                            </div>

                            <div class="group">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Start Date</label>
                                <input type="date" name="gen_start_date" id="gen_start_date" onchange="calculateEndDate()" value="<?php echo date('Y-m-d', strtotime('-60 days')); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-3.5 text-sm font-semibold text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all">
                            </div>

                            <div class="group">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Total Posts to Generate</label>
                                <input type="number" name="gen_total_post" id="gen_total_post" oninput="calculateEndDate()" value="20000" min="1" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-bold text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all">
                            </div>

                            <div class="group md:col-span-2 lg:col-span-1">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Posts Per Day</label>
                                <input type="number" name="gen_posts_per_day" id="gen_posts_per_day" oninput="calculateEndDate()" value="150" placeholder="10" min="1" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-bold text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all">
                            </div>

                            <div class="group md:col-span-2 lg:col-span-1">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Slug Structure</label>
                                <input type="text" name="gen_slug_structure" placeholder="e.g. {title_3}-{keyword}" value="{title_5}" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all">
                                <p class="mt-2 text-[10px] text-slate-400 italic leading-relaxed">
                                    <span class="font-bold text-slate-500">Supported Formats:</span> 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{title}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{keyword}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{title_x}</code> 
                                    (where <span class="font-semibold text-slate-500">x</span> is number of words taken).
                                </p>
                            </div>
                            
                            <div class="group md:col-span-2">
                                <label class="flex items-center gap-2 text-[10px] font-bold text-slate-500 mb-2 uppercase tracking-wider">Permalink Format</label>
                                <input type="text" name="gen_permalink_format" placeholder="/{year}/{month}/{slug}.html" value="/{slug}/" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-cyan-500/10 focus:bg-white focus:border-cyan-300 transition-all">
                                <p class="mt-2 text-[10px] text-slate-400 italic leading-relaxed">
                                    <span class="font-bold text-slate-500">Supported Spintax:</span> 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{slug}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{category}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{id}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{year}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{month}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{day}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{first}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{index}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{index2}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{index3}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{random:x}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{random2:x}</code>, 
                                    <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded font-mono border border-slate-200">{random3:x}</code>
                                </p>
                            </div>

                            <div class="group md:col-span-2 bg-cyan-50 border border-cyan-100 rounded-2xl p-4 mt-2 shadow-inner flex items-start gap-3 transition-all">
                                <svg class="w-5 h-5 text-cyan-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                                <p id="schedule_note" class="text-[11px] text-cyan-800 leading-relaxed font-medium">
                                    <em>Please configure your parameters to see the schedule estimate.</em>
                                </p>
                            </div>

                        </div>
                        <div class="pt-2">
                            <button type="submit" name="generate_data" class="w-full flex items-center justify-center gap-3 bg-cyan-600 hover:bg-cyan-700 text-white font-black px-8 py-4 rounded-2xl transition-all shadow-xl shadow-cyan-200 active:scale-[0.98] text-[11px] uppercase tracking-[0.2em]">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/></svg>
                                Initialize Generation Protocol
                            </button>
                        </div>
                    </form>
                </div>
            </section>
            <script>
                // Add this inside your existing <script> tags
                // --- SUBMIT GENERATION TO AJAX.PHP ---
                async function startGeneration(e) {
                    e.preventDefault(); // Stop standard form submission
                    
                    const form = document.getElementById('genForm');
                    const submitBtn = form.querySelector('button[name="generate_data"]');
                    
                    // 1. Update UI to "Initializing"
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = `<svg class="animate-spin h-5 w-5 mr-3 text-white" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Initializing...`;

                    try {
                        // 2. Base64 Encode the payload to bypass Web Application Firewalls (403 Errors)
                        const formData = new FormData(form);
                        const dataObj = Object.fromEntries(formData.entries());
                        // Add the blog URL to the object before encoding
                        dataObj.blog_url = window.location.hostname;
                        
                        const encodedPayload = btoa(JSON.stringify(dataObj));
                        
                        const safeFormData = new FormData();
                        safeFormData.append('payload', encodedPayload);

                        const endpointUrl = dataObj.gen_endpoint; // Save this for polling later

                        // 3. Request Generation from our new ajax.php file
                        let res = await fetch('ajax.php?action=start_gen', { method: 'POST', body: safeFormData });
                        let data = await res.json();
                        
                        if (data.status === 'error') throw new Error(data.message);
                        
                        const taskId = data.task_id;  
                        
                        // 4. Start Polling the Status
                        submitBtn.innerHTML = `<svg class="animate-spin h-5 w-5 mr-3 text-white" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Processing Remote Data...`;
                        
                        let pollInterval = setInterval(async () => {
                            let pollData = new FormData();
                            pollData.append('endpoint', endpointUrl);
                            pollData.append('task_id', taskId);

                            
                            let pollRes = await fetch('ajax.php?action=check_status', { method: 'POST', body: pollData });
                            let statusData = await pollRes.json();
                            
                            if (statusData.status === 'finish' && statusData.url_zip) {
                                clearInterval(pollInterval);
                                
                                // 5. Remote generation is done. Tell ajax.php to download it.
                                submitBtn.innerHTML = `<svg class="animate-spin h-5 w-5 mr-3 text-white" viewBox="0 0 24 24" fill="none"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Downloading & Syncing...`;
                                
                                let processData = new FormData();
                                processData.append('url_zip', statusData.url_zip);
                                
                                let processRes = await fetch('ajax.php?action=process_zip', { method: 'POST', body: processData });
                                let finalData = await processRes.json();
                                
                                if (finalData.status === 'success') {
                                    
                                    // 6. Request Deletion (Fire and Forget)
                                    let deleteData = new FormData();
                                    // Use the taskId we already saved in the outer scope
                                    deleteData.append('task_id', taskId); 
                                    // Pass endpoint so ajax.php knows where to send the delete command
                                    deleteData.append('endpoint', endpointUrl); 
                                    
                                    // keepalive: true ensures the request isn't cancelled by the page reload
                                    fetch('ajax.php?action=request_delete', { 
                                        method: 'POST', 
                                        body: deleteData, 
                                        keepalive: true 
                                    });

                                    // Alert user and reload
                                    //alert('Success: ' + finalData.message);
                                    window.location.reload(); 
                                    
                                } else {
                                    throw new Error(finalData.message);
                                }
                            }
                        }, 5000); // Poll every 5 seconds

                    } catch (err) {
                        alert("Error: " + err.message);
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = "Initialize Generation Protocol";
                    }
                }
            </script>
            <script>
                // 1. Pass PHP data to Javascript
                const clusterDbs = <?php echo json_encode($dbs); ?>;
                const singleDbs = <?php echo json_encode($dbs_db); ?>;

                // 2. Tab Switching Logic
                function switchDataTab(tabId) {
                    const tabSync = document.getElementById('tab-sync');
                    const tabGen = document.getElementById('tab-gen');
                    const btnSync = document.getElementById('btn-sync');
                    const btnGen = document.getElementById('btn-gen');

                    if (tabId === 'sync') {
                        tabSync.classList.remove('hidden');
                        tabGen.classList.add('hidden');
                        
                        btnSync.className = "pb-4 text-xs font-black uppercase tracking-widest text-indigo-600 border-b-2 border-indigo-600 transition-colors";
                        btnGen.className = "pb-4 text-xs font-bold uppercase tracking-widest text-slate-400 border-b-2 border-transparent hover:text-slate-600 transition-colors";
                    } else {
                        tabGen.classList.remove('hidden');
                        tabSync.classList.add('hidden');
                        
                        btnGen.className = "pb-4 text-xs font-black uppercase tracking-widest text-cyan-600 border-b-2 border-cyan-600 transition-colors";
                        btnSync.className = "pb-4 text-xs font-bold uppercase tracking-widest text-slate-400 border-b-2 border-transparent hover:text-slate-600 transition-colors";
                        
                        // Populate DB dropdown if it is empty (first time opening tab)
                        if (document.getElementById('gen_db_name').options.length === 0) {
                            updateDbDropdown();
                        }
                    }
                }

                // 3. Update Dropdown based on Assignment Type
                function updateDbDropdown() {
                    const type = document.getElementById('gen_assignment').value;
                    const dbSelect = document.getElementById('gen_db_name');
                    dbSelect.innerHTML = ''; // Clear current options

                    const dataList = (type === 'cluster_db') ? clusterDbs : singleDbs;

                    if (!dataList || dataList.length === 0) {
                        dbSelect.innerHTML = '<option value="">No databases available or API failed</option>';
                        calculateEndDate();
                        return;
                    }

                    dataList.forEach(db => {
                        const opt = document.createElement('option');
                        opt.value = db.niche;
                        opt.setAttribute('data-count', db.count); // Store count for reference
                        const formattedCount = parseInt(db.count).toLocaleString();
                        opt.textContent = `${db.niche} (${formattedCount} posts)`;
                        dbSelect.appendChild(opt);
                    });

                    // Trigger estimation calculation
                    calculateEndDate();
                }

                // 4. Calculate Dynamic End Date Estimate
                function calculateEndDate() {
                    const startDateInput = document.getElementById('gen_start_date').value;
                    const totalPosts = parseInt(document.getElementById('gen_total_post').value); 
                    const postsPerDay = parseInt(document.getElementById('gen_posts_per_day').value);
                    const dbSelect = document.getElementById('gen_db_name');
                    const noteEl = document.getElementById('schedule_note');

                    // Validation checks
                    if (!startDateInput || !postsPerDay || postsPerDay <= 0 || !totalPosts || totalPosts <= 0 || !dbSelect || dbSelect.options.length === 0) {
                        noteEl.innerHTML = "<em>Please fill out Start Date, Total Posts, and Posts Per Day to see the schedule estimate.</em>";
                        return;
                    }

                    // Math: Total Days required
                    const totalDays = Math.ceil(totalPosts / postsPerDay);
                    
                    // Add total days to the Start Date
                    const startDateObj = new Date(startDateInput);
                    startDateObj.setDate(startDateObj.getDate() + totalDays);
                    
                    // Format output
                    const options = { year: 'numeric', month: 'long', day: 'numeric' };
                    const endDateFormatted = startDateObj.toLocaleDateString(undefined, options);

                    // Update UI Note
                    noteEl.innerHTML = `<span class="text-cyan-600 font-extrabold tracking-wide uppercase text-[9px]">Live Estimation:</span><br> All <strong>${totalPosts.toLocaleString()}</strong> posts will be scheduled from start date until <strong class="text-slate-900 border-b border-cyan-400 pb-0.5">${endDateFormatted}</strong> (approx. ${totalDays.toLocaleString()} days).`;
                }
            </script>
            <form method="POST" class="space-y-16 pb-32 md:pb-24">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
                    <section class="relative bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                        <h3 class="text-[11px] font-black uppercase tracking-[0.25em] text-slate-400 mb-8 flex items-center gap-3">
                            <span class="w-10 h-[2px] bg-slate-200 rounded-full"></span> Global Logic
                        </h3>
                        <div class="space-y-6">
                            <div class="group">
                                <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">Active Theme</label>
                                <div class="relative">
                                    <select name="theme" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-semibold text-slate-700 outline-none hover:border-slate-300 focus:ring-4 focus:ring-slate-500/10 focus:bg-white transition-all appearance-none cursor-pointer">
                                        <?php foreach ($themes as $t): $t_name = basename($t); ?>
                                            <option value="<?php echo $t_name; ?>" <?php echo ($config['theme'] ?? '') == $t_name ? 'selected' : ''; ?>>🎨 &nbsp;<?php echo ucfirst($t_name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="absolute inset-y-0 right-5 flex items-center pointer-events-none text-slate-400">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                    </div>
                                </div>
                            </div>
                            <div class="group">
                                <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">Histats Tracking ID</label>
                                <input type="text" name="histats_id" value="<?php echo htmlspecialchars($config['histats_id'] ?? ''); ?>" placeholder="e.g. 1234567" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-slate-500/10">
                            </div>
                            <div class="group">
                                <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">ARSAE Domain</label>
                                <input type="text" name="arsae_server" value="<?php echo htmlspecialchars($config['arsae_server'] ?? ''); ?>" placeholder="e.g. https://domain.com" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-slate-500/10">
                            </div>
                        </div>
                    </section>
                
                    <section class="relative bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                        <h3 class="text-[11px] font-black uppercase tracking-[0.25em] text-slate-400 mb-8 flex items-center gap-3">
                            <span class="w-10 h-[2px] bg-slate-200 rounded-full"></span> Sitemap Engine
                        </h3>
                        <div class="space-y-6">
                            <div class="group">
                                <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">Sitemap Filename (Slug)</label>
                                <input type="text" name="sitemap_slug" value="<?php echo htmlspecialchars($config['sitemap_slug'] ?? 'sitemap'); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl pl-8 pr-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-slate-500/10">
                            </div>
                            <div class="group">
                                <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">URLs per Sitemap File</label>
                                <input type="number" name="sitemap_limit" value="<?php echo htmlspecialchars($config['sitemap_limit'] ?? '500'); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-bold text-slate-700 outline-none focus:ring-4 focus:ring-slate-500/10">
                            </div>
                            
                            <div class="flex items-center gap-3 p-4 bg-slate-50 rounded-2xl border border-slate-100 mt-2">
                                <div class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in">
                                    <input type="checkbox" name="sitemap_include_categories" id="cat_sitemap" class="absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer toggle-checkbox" <?php echo !empty($config['sitemap_include_categories']) ? 'checked' : ''; ?>/>
                                    <label for="cat_sitemap" class="block overflow-hidden h-5 rounded-full bg-slate-300 cursor-pointer toggle-label"></label>
                                </div>
                                <label for="cat_sitemap" class="text-xs font-bold text-slate-600 uppercase tracking-wide cursor-pointer">Include Category Sitemaps</label>
                            </div>
                        </div>
                    </section>
                </div>

                <section class="relative bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                    <h3 class="flex items-center gap-4 text-[11px] font-black uppercase tracking-[0.3em] text-amber-600 mb-10">
                        <span class="flex h-2 w-12 rounded-full bg-gradient-to-r from-amber-500 to-amber-200"></span> Ownership & Identity
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-10 mb-10 pb-10 border-b border-slate-100">
                        <div class="group">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase mb-3">Blog Name</label>
                            <input type="text" name="blogName" value="<?php echo htmlspecialchars($config['blogName'] ?? ''); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-bold text-slate-700 outline-none focus:ring-4 focus:ring-amber-500/10">
                        </div>
                        <div class="group">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase mb-3">Blog Description</label>
                            <input type="text" name="blogDesc" value="<?php echo htmlspecialchars($config['blogDesc'] ?? ''); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-medium text-slate-600 outline-none focus:ring-4 focus:ring-amber-500/10">
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-10">
                        <div class="group">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase mb-3">Google Verification</label>
                            <input type="text" name="meta_google" value="<?php echo htmlspecialchars($config['meta_google'] ?? ''); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-mono outline-none focus:ring-4 focus:ring-amber-500/10">
                        </div>
                        <div class="group">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase mb-3">Bing Verification</label>
                            <input type="text" name="meta_bing" value="<?php echo htmlspecialchars($config['meta_bing'] ?? ''); ?>" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-mono outline-none focus:ring-4 focus:ring-amber-500/10">
                        </div>
                    </div>
                </section>

                <section class="relative bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                    <h3 class="flex items-center gap-4 text-[11px] font-black uppercase tracking-[0.3em] text-cyan-600 mb-10">
                        <span class="flex h-2 w-12 rounded-full bg-gradient-to-r from-cyan-500 to-cyan-200"></span> Structured Data (Schema)
                    </h3>
                    
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
                        <div class="space-y-6">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase tracking-wider">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 6h16M4 12h16m-7 6h7"/></svg>
                                Primary Post Type
                            </label>
                            <div class="relative">
                                <select name="schema_type" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-semibold text-slate-700 outline-none hover:border-cyan-300 focus:ring-4 focus:ring-cyan-500/10 focus:bg-white transition-all appearance-none cursor-pointer">
                                    <option value="BlogPosting" <?php echo ($config['schema_type'] ?? '') == 'BlogPosting' ? 'selected' : ''; ?>>BlogPosting (Default)</option>
                                    <option value="NewsArticle" <?php echo ($config['schema_type'] ?? '') == 'NewsArticle' ? 'selected' : ''; ?>>NewsArticle</option>
                                    <option value="Article" <?php echo ($config['schema_type'] ?? '') == 'Article' ? 'selected' : ''; ?>>Article</option>
                                </select>
                                <div class="absolute inset-y-0 right-5 flex items-center pointer-events-none text-slate-400">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                                </div>
                            </div>
                            <p class="text-[10px] text-slate-400 italic">Determines the JSON-LD <code class="bg-slate-100 text-cyan-600 px-1 py-0.5 rounded">@type</code> for search engines.</p>
                        </div>

                        <div class="space-y-4">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 uppercase tracking-wider mb-2">Optional Schemas</label>
                            
                            <div class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl border border-slate-100">
                                <div class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in">
                                    <input type="checkbox" name="schema_opt_offer" id="sch_offer" class="absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer toggle-checkbox" <?php echo !empty($config['schema_opt_offer']) ? 'checked' : ''; ?>/>
                                    <label for="sch_offer" class="block overflow-hidden h-5 rounded-full bg-slate-300 cursor-pointer toggle-label"></label>
                                </div>
                                <label for="sch_offer" class="text-xs font-bold text-slate-600 uppercase tracking-wide cursor-pointer">Offer / Product</label>
                            </div>

                            <div class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl border border-slate-100">
                                <div class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in">
                                    <input type="checkbox" name="schema_opt_rating" id="sch_rating" class="absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer toggle-checkbox" <?php echo !empty($config['schema_opt_rating']) ? 'checked' : ''; ?>/>
                                    <label for="sch_rating" class="block overflow-hidden h-5 rounded-full bg-slate-300 cursor-pointer toggle-label"></label>
                                </div>
                                <label for="sch_rating" class="text-xs font-bold text-slate-600 uppercase tracking-wide cursor-pointer">Aggregate Rating</label>
                            </div>

                            <div class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl border border-slate-100">
                                <div class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in">
                                    <input type="checkbox" name="schema_opt_review" id="sch_review" class="absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer toggle-checkbox" <?php echo !empty($config['schema_opt_review']) ? 'checked' : ''; ?>/>
                                    <label for="sch_review" class="block overflow-hidden h-5 rounded-full bg-slate-300 cursor-pointer toggle-label"></label>
                                </div>
                                <label for="sch_review" class="text-xs font-bold text-slate-600 uppercase tracking-wide cursor-pointer">Review / Critique</label>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="relative bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                    <h3 class="flex items-center gap-4 text-[12px] font-black uppercase tracking-[0.3em] text-indigo-600 mb-10">
                        <span class="flex h-2 w-12 rounded-full bg-gradient-to-r from-indigo-500 to-indigo-200"></span> Monetization Hub
                    </h3>
                    <div class="grid grid-cols-1 lg:grid-cols-12 gap-10">
                        <div class="lg:col-span-4 space-y-6">
                            <label class="inline-flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">Placement Logic</label>
                            <select name="main_ad_placement" class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm font-semibold text-slate-700 outline-none focus:ring-4 focus:ring-indigo-500/10 focus:bg-white transition-all appearance-none cursor-pointer">
                                <option value="after_h1" <?php echo ($config['main_ad_placement'] ?? '') == 'after_h1' ? 'selected' : ''; ?>>Below Title (H1)</option>
                                <option value="before_h2" <?php echo ($config['main_ad_placement'] ?? '') == 'before_h2' ? 'selected' : ''; ?>>Above Content (H2)</option>
                                <option value="floating" <?php echo ($config['main_ad_placement'] ?? '') == 'floating' ? 'selected' : ''; ?>>Sticky Floating</option>
                            </select>
                        </div>
                        <div class="lg:col-span-8">
                            <label class="inline-flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider">Advertisement Script</label>
                            <textarea name="main_ad_code" rows="5" class="w-full bg-[#1e293b] text-indigo-100 font-mono text-[11px] rounded-[2rem] px-8 py-6 outline-none border-2 border-transparent focus:border-indigo-500/50 shadow-2xl transition-all placeholder-slate-500"><?php echo htmlspecialchars($config['main_ad_code'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </section>

                <section class="relative overflow-hidden bg-white border border-slate-200 rounded-[2.5rem] p-8 md:p-10 shadow-sm transition-all hover:shadow-md">
                    <h3 class="flex items-center gap-4 text-[11px] font-black uppercase tracking-[0.3em] text-rose-500 mb-10">
                        <span class="flex h-2 w-12 rounded-full bg-gradient-to-r from-rose-500 to-rose-200"></span> Security & Firewall
                    </h3>

                    <div class="mb-10 group">
                        <label class="flex items-center gap-2 text-[11px] font-bold text-slate-500 mb-3 uppercase tracking-wider group-hover:text-rose-600 transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
                            Back Button Redirect URL
                        </label>
                        <input type="url" name="back_button_redirect" value="<?php echo htmlspecialchars($config['back_button_redirect'] ?? ''); ?>" placeholder="https://external-redirect.com" 
                               class="w-full bg-slate-50 border border-slate-200 rounded-2xl px-6 py-4 text-sm font-mono text-slate-700 outline-none focus:ring-4 focus:ring-rose-500/10 transition-all">
                        <p class="mt-2 text-[10px] text-slate-400 italic">Triggers a direct redirect when users attempt to go back in their browser history.</p>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-10">
                        <div class="group bg-slate-900 p-8 rounded-[2rem] border border-slate-800 hover:shadow-xl transition-all duration-500">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-rose-400 mb-4 uppercase tracking-wider">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                Geofence Block (ISO)
                            </label>
                            <input type="text" name="blocked_countries" value="<?php echo htmlspecialchars($config['blocked_countries'] ?? ''); ?>" placeholder="JP, CN, RU..." 
                                   class="w-full bg-slate-800 border border-slate-700 rounded-2xl px-6 py-4 font-mono text-xs text-white outline-none focus:ring-4 focus:ring-rose-500/20 transition-all">
                        </div>
                
                        <div class="group bg-slate-900 p-8 rounded-[2rem] border border-slate-800 hover:shadow-xl transition-all duration-500">
                            <label class="flex items-center gap-2 text-[11px] font-bold text-indigo-400 mb-4 uppercase tracking-wider">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
                                Smart Redirects (JSON)
                            </label>
                            <textarea name="redirect_rules" rows="4" placeholder='{"US":"https://site.com"}' 
                                      class="w-full bg-slate-800 border border-slate-700 rounded-2xl px-6 py-4 font-mono text-xs text-white outline-none focus:ring-4 focus:ring-indigo-500/20 transition-all resize-none"><?php echo htmlspecialchars($config['redirect_rules'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="relative group">
                        <div class="relative bg-[#020617] rounded-[2.5rem] p-8 border border-slate-800 shadow-2xl">
                            <label class="flex items-center gap-3 text-[11px] font-bold text-slate-400 uppercase tracking-widest mb-5">Global Header Scripts</label>
                            <textarea name="ads_code" rows="4" class="w-full bg-transparent text-emerald-500 font-mono text-[11px] outline-none custom-scrollbar"><?php echo htmlspecialchars($config['ads_code'] ?? ''); ?></textarea>
                        </div>
                    </div>
                </section>
                
<div class="fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-full max-w-sm px-4 md:max-w-xl">
    <button
        type="submit"
        class="w-full min-h-[52px] bg-slate-900 hover:bg-indigo-600 text-white font-black uppercase tracking-[0.2em] md:tracking-[0.3em] py-4 px-6 rounded-2xl md:rounded-[2rem] shadow-2xl transition-all duration-500 active:scale-[0.97] text-xs md:text-sm">
        Apply System Configuration
    </button>
</div>
                </div>
            </form>
        </div>
        
        <div class="mt-12 text-center">
            <p class="text-slate-400 text-[9px] uppercase font-bold tracking-[0.5em] inline-block py-2 px-6 bg-white border border-slate-200 rounded-full">
                Designed for Speed & Automation
            </p>
        </div>
    </div>
</body>
</html>