<?php
/**
 * ============================================================
 *  ESCOBAR WEB — PAGE LOADING DEBUG TOOL
 *  Simpan file ini di folder root web (sejajar config.php)
 *  Akses via: http://localhost/escobarweb/page_debug.php
 * ============================================================
 */

// ── Bootstrap minimal (tanpa license check agar bisa jalan) ──
ob_start();
if (session_status() === PHP_SESSION_NONE) session_start();
date_default_timezone_set('Asia/Jakarta');

$GLOBAL_START = microtime(true);

// ── Koneksi DB langsung (tanpa include config.php agar tidak trigger license) ──
$_conf = ['h' => 'localhost', 'u' => 'root', 'p' => '', 'n' => 'db_rental_ps'];
$conn  = @new mysqli($_conf['h'], $_conf['u'], $_conf['p'], $_conf['n']);
$db_ok = ($conn && !$conn->connect_error);

// ============================================================
//  ACTION: License Check Test
// ============================================================
if (isset($_GET['test_license'])) {
    $lic = '';
    if ($db_ok) {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_name = 'license_key' LIMIT 1");
        if ($r) { $row = $r->fetch_assoc(); $lic = trim($row['setting_value'] ?? ''); }
    }
    $t0 = microtime(true);
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => 'https://escobargame.site/license/api.php',
        CURLOPT_POST           => 1,
        CURLOPT_POSTFIELDS     => http_build_query(['action' => 'validate', 'license_key' => $lic, 'domain' => $_SERVER['HTTP_HOST']]),
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_TIMEOUT        => 5,
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_SSL_VERIFYPEER => 0,
    ]);
    $res  = curl_exec($ch);
    $info = curl_getinfo($ch);
    $err  = curl_error($ch);
    curl_close($ch);
    $dur  = round((microtime(true) - $t0) * 1000);
    header('Content-Type: application/json');
    echo json_encode([
        'duration_ms'   => $dur,
        'http_code'     => $info['CURLINFO_HTTP_CODE'] ?? $info['http_code'],
        'connect_time'  => round($info['connect_time'] * 1000) . 'ms',
        'total_time'    => round($info['total_time'] * 1000) . 'ms',
        'curl_error'    => $err ?: null,
        'response'      => $res ?: null,
        'session_cache' => [
            'lic_status'     => $_SESSION['lic_status'] ?? 'NOT SET',
            'lic_last_check' => isset($_SESSION['lic_last_check'])
                ? date('H:i:s', $_SESSION['lic_last_check']) . ' (' . (time() - $_SESSION['lic_last_check']) . 's ago)'
                : 'NOT SET',
        ],
    ], JSON_PRETTY_PRINT);
    exit;
}

// ============================================================
//  ACTION: ADB Speed Test
// ============================================================
if (isset($_GET['test_adb'])) {
    $adb_path = '';
    if ($db_ok) {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_name = 'adb_path' LIMIT 1");
        if ($r) { $row = $r->fetch_assoc(); $adb_path = trim($row['setting_value'] ?? ''); }
    }
    $t0  = microtime(true);
    $out = file_exists($adb_path) ? @shell_exec("\"$adb_path\" devices 2>&1") : null;
    $dur = round((microtime(true) - $t0) * 1000);
    header('Content-Type: application/json');
    echo json_encode([
        'duration_ms' => $dur,
        'adb_path'    => $adb_path,
        'path_exists' => file_exists($adb_path),
        'output'      => $out,
    ], JSON_PRETTY_PRINT);
    exit;
}

// ============================================================
//  ACTION: DB Query Speed Test
// ============================================================
if (isset($_GET['test_db'])) {
    $results = [];
    if ($db_ok) {
        $queries = [
            'system_settings' => "SELECT COUNT(*) as n FROM system_settings",
            'tvs'             => "SELECT COUNT(*) as n FROM tvs",
            'transactions'    => "SELECT COUNT(*) as n FROM transactions",
            'packages'        => "SELECT COUNT(*) as n FROM packages",
            'members'         => "SELECT COUNT(*) as n FROM members",
            'overlay_settings'=> "SELECT COUNT(*) as n FROM overlay_settings",
            'tuya_devices'    => "SHOW TABLES LIKE 'tuya_devices'",
        ];
        foreach ($queries as $name => $sql) {
            $t0 = microtime(true);
            $r  = $conn->query($sql);
            $ms = round((microtime(true) - $t0) * 1000);
            $results[$name] = ['ms' => $ms, 'ok' => (bool)$r];
        }
        // Simulate preload_settings (baca semua settings)
        $t0 = microtime(true);
        $r  = $conn->query("SELECT setting_name, setting_value FROM system_settings");
        $cnt = 0;
        while ($r && $r->fetch_assoc()) $cnt++;
        $results['preload_all_settings'] = [
            'ms'    => round((microtime(true) - $t0) * 1000),
            'rows'  => $cnt,
        ];
    }
    header('Content-Type: application/json');
    echo json_encode(['db_ok' => $db_ok, 'queries' => $results], JSON_PRETTY_PRINT);
    exit;
}

// ============================================================
//  ACTION: Simulate Full Page Load (seperti pindah menu)
// ============================================================
if (isset($_GET['simulate_page'])) {
    $page = $_GET['page'] ?? 'index';
    $log  = [];

    // Step 1: DB connect
    $t = microtime(true);
    $c2 = new mysqli('localhost', 'root', '', 'db_rental_ps');
    $log[] = ['step' => '1. DB connect', 'ms' => ms($t)];

    // Step 2: preload_settings
    $t = microtime(true);
    $r = $c2->query("SELECT setting_name, setting_value FROM system_settings");
    $settings = [];
    while ($row = $r->fetch_assoc()) $settings[$row['setting_name']] = $row['setting_value'];
    $log[] = ['step' => '2. preload_settings (' . count($settings) . ' keys)', 'ms' => ms($t)];

    // Step 3: License check simulation
    $lic_status = $_SESSION['lic_status'] ?? '';
    $lic_last   = $_SESSION['lic_last_check'] ?? 0;
    $need_check = (time() - $lic_last) > 3600 || $lic_status !== 'success';
    if ($need_check) {
        $t = microtime(true);
        $lic_key = trim($settings['license_key'] ?? '');
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => 'https://escobargame.site/license/api.php',
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => http_build_query(['action' => 'validate', 'license_key' => $lic_key, 'domain' => $_SERVER['HTTP_HOST']]),
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_TIMEOUT        => 3,
            CURLOPT_CONNECTTIMEOUT => 2,
            CURLOPT_SSL_VERIFYPEER => 0,
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        $log[] = ['step' => '3. LICENSE CHECK via cURL (TRIGGERED!)', 'ms' => ms($t), 'warn' => true, 'response' => substr($res, 0, 100)];
    } else {
        $log[] = ['step' => '3. License check SKIPPED (cached session, ' . (time() - $lic_last) . 's ago)', 'ms' => 0, 'warn' => false];
    }

    // Step 4: ADB list (hanya index.php)
    if ($page === 'index') {
        $adb_path = $settings['adb_path'] ?? '';
        $t = microtime(true);
        if (!empty($adb_path) && file_exists($adb_path)) {
            @shell_exec("\"$adb_path\" devices 2>&1");
            $log[] = ['step' => '4. getADBList() — shell_exec adb devices', 'ms' => ms($t), 'warn' => true];
        } else {
            $log[] = ['step' => '4. getADBList() — SKIP (adb_path kosong/tidak ada)', 'ms' => ms($t), 'warn' => false];
        }
    }

    // Step 5: Page queries
    $t = microtime(true);
    if ($page === 'index') {
        $c2->query("SELECT * FROM tvs ORDER BY nama_tv ASC");
        $c2->query("SELECT * FROM packages ORDER BY durasi_menit ASC");
        $c2->query("SELECT id, nama_member, saldo FROM members ORDER BY nama_member ASC");
        $c2->query("SELECT * FROM sticks WHERE status = 'available'");
        $c2->query("SELECT id, nama_tv FROM tvs WHERE status = 'available' ORDER BY nama_tv ASC");
        $c2->query("SHOW TABLES LIKE 'tuya_devices'");
    } elseif ($page === 'history') {
        $c2->query("SELECT * FROM transactions ORDER BY created_at DESC LIMIT 50");
    } elseif ($page === 'closing') {
        $c2->query("SELECT * FROM transactions WHERE DATE(created_at) = CURDATE()");
    }
    $log[] = ['step' => "5. Page queries ($page)", 'ms' => ms($t)];

    $total = round((microtime(true) - $GLOBAL_START) * 1000);
    header('Content-Type: application/json');
    echo json_encode(['page' => $page, 'total_ms' => $total, 'steps' => $log], JSON_PRETTY_PRINT);
    exit;
}

// ============================================================
//  ACTION: Real Page Timer (pasang ke halaman asli)
// ============================================================
if (isset($_GET['install_timer'])) {
    // Instruksi inject timing ke halaman nyata
    header('Content-Type: text/plain');
    echo "Tambahkan kode berikut di PALING ATAS config.php (baris pertama setelah <?php):\n\n";
    echo '// === PAGE TIMER DEBUG ===\n';
    echo '$__PAGE_START = microtime(true);' . "\n";
    echo 'register_shutdown_function(function() use (&$__PAGE_START) {' . "\n";
    echo '    $dur = round((microtime(true) - $__PAGE_START) * 1000);' . "\n";
    echo '    $page = basename($_SERVER["PHP_SELF"]);' . "\n";
    echo '    $log = date("Y-m-d H:i:s") . " | PAGE: $page | TOTAL: {$dur}ms\\n";' . "\n";
    echo '    @file_put_contents(__DIR__ . "/page_timing.log", $log, FILE_APPEND);' . "\n";
    echo '});' . "\n";
    echo '// === END PAGE TIMER DEBUG ===\n';
    exit;
}

// ============================================================
//  Helper
// ============================================================
function ms($t) { return round((microtime(true) - $t) * 1000); }

?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Escobar Web — Page Debug</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { background: #0f172a; color: #e2e8f0; font-family: 'Segoe UI', sans-serif; padding: 24px; }
  h1  { color: #06b6d4; font-size: 1.5rem; margin-bottom: 4px; }
  .sub { color: #64748b; font-size: 0.85rem; margin-bottom: 28px; }
  .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; margin-bottom: 28px; }
  .card { background: #1e293b; border: 1px solid #334155; border-radius: 14px; padding: 20px; }
  .card h2 { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; margin-bottom: 12px; }
  .card .val { font-size: 2rem; font-weight: 700; font-family: monospace; }
  .good { color: #10b981; }
  .warn { color: #f59e0b; }
  .bad  { color: #ef4444; }
  .btn { display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; border-radius: 10px;
         background: #06b6d4; color: #000; font-weight: 700; border: none; cursor: pointer;
         font-size: 0.85rem; text-decoration: none; transition: 0.2s; margin: 4px; }
  .btn:hover { filter: brightness(1.15); transform: translateY(-1px); }
  .btn-warn { background: #f59e0b; }
  .btn-red  { background: #ef4444; color: #fff; }
  .btn-gray { background: #334155; color: #e2e8f0; }
  pre  { background: #0f172a; border: 1px solid #334155; border-radius: 10px; padding: 16px;
         font-size: 0.78rem; overflow-x: auto; white-space: pre-wrap; margin-top: 12px; max-height: 400px; overflow-y: auto; }
  .section { background: #1e293b; border: 1px solid #334155; border-radius: 14px; padding: 20px; margin-bottom: 16px; }
  .section h2 { font-size: 1rem; font-weight: 700; color: #06b6d4; margin-bottom: 12px; }
  .badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; margin-left: 6px; }
  .badge-warn { background: rgba(245,158,11,0.2); color: #f59e0b; border: 1px solid rgba(245,158,11,0.4); }
  .badge-bad  { background: rgba(239,68,68,0.2); color: #ef4444; border: 1px solid rgba(239,68,68,0.4); }
  .badge-ok   { background: rgba(16,185,129,0.2); color: #10b981; border: 1px solid rgba(16,185,129,0.4); }
  #output { display: none; }
  .spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid rgba(0,0,0,0.3); border-top-color: #000; border-radius: 50%; animation: spin 0.6s linear infinite; vertical-align: middle; }
  @keyframes spin { to { transform: rotate(360deg); } }
  table { width: 100%; border-collapse: collapse; margin-top: 8px; }
  td, th { padding: 8px 12px; text-align: left; border-bottom: 1px solid #334155; font-size: 0.83rem; }
  th { color: #94a3b8; font-weight: 600; }
</style>
</head>
<body>

<h1>🔍 Escobar Web — Page Loading Debug</h1>
<p class="sub">Tool untuk mencari penyebab loading lambat saat pindah menu</p>

<!-- Ringkasan Status -->
<div class="grid">
  <div class="card">
    <h2>Status Database</h2>
    <div class="val <?= $db_ok ? 'good' : 'bad' ?>"><?= $db_ok ? '✓ OK' : '✗ GAGAL' ?></div>
    <?php if ($db_ok): ?>
    <div style="color:#94a3b8;font-size:0.82rem;margin-top:8px;">
      <?php
        $r = $conn->query("SELECT COUNT(*) as n FROM tvs");
        $tvs = $r ? $r->fetch_assoc()['n'] : '?';
        echo "$tvs TV terdaftar";
      ?>
    </div>
    <?php endif; ?>
  </div>

  <div class="card">
    <h2>License Session Cache</h2>
    <?php
      $lic_ok   = ($_SESSION['lic_status'] ?? '') === 'success';
      $lic_age  = isset($_SESSION['lic_last_check']) ? (time() - $_SESSION['lic_last_check']) : null;
      $need_req = !$lic_ok || ($lic_age !== null && $lic_age > 3600);
    ?>
    <div class="val <?= $need_req ? 'bad' : 'good' ?>">
      <?= $need_req ? '⚠ AKAN REQUEST' : '✓ CACHED' ?>
    </div>
    <div style="color:#94a3b8;font-size:0.82rem;margin-top:8px;">
      Status: <strong><?= htmlspecialchars($_SESSION['lic_status'] ?? 'belum ada') ?></strong><br>
      Cache: <?= $lic_age !== null ? $lic_age . 's lalu (max 3600s)' : 'belum pernah' ?><br>
      <?php if ($need_req): ?>
      <span style="color:#ef4444;font-weight:700;">→ Setiap pindah menu akan cURL ke server lisensi!</span>
      <?php else: ?>
      <span style="color:#10b981;">→ Aman, tidak akan request selama <?= 3600 - $lic_age ?>s lagi</span>
      <?php endif; ?>
    </div>
  </div>

  <div class="card">
    <h2>ADB Path</h2>
    <?php
      $adb_path = '';
      if ($db_ok) {
        $r = $conn->query("SELECT setting_value FROM system_settings WHERE setting_name='adb_path' LIMIT 1");
        if ($r) { $row = $r->fetch_assoc(); $adb_path = trim($row['setting_value'] ?? ''); }
      }
      $adb_exists = !empty($adb_path) && file_exists($adb_path);
    ?>
    <div class="val <?= $adb_exists ? 'warn' : 'good' ?>">
      <?= $adb_exists ? '⚡ ADA' : '— Tidak ada' ?>
    </div>
    <div style="color:#94a3b8;font-size:0.82rem;margin-top:8px;">
      Path: <code><?= htmlspecialchars($adb_path ?: '(kosong)') ?></code><br>
      <?= $adb_exists ? '<span style="color:#f59e0b;">→ Dashboard akan jalankan `adb devices` setiap load!</span>' : '<span style="color:#10b981;">→ ADB skip, tidak blocking</span>' ?>
    </div>
  </div>

  <div class="card">
    <h2>Page Load Time (halaman ini)</h2>
    <?php $elapsed = ms($GLOBAL_START); ?>
    <div class="val <?= $elapsed < 200 ? 'good' : ($elapsed < 800 ? 'warn' : 'bad') ?>">
      <?= $elapsed ?>ms
    </div>
    <div style="color:#94a3b8;font-size:0.82rem;margin-top:8px;">
      (Tanpa license check & ADB)
    </div>
  </div>
</div>

<!-- Diagnosa Penyebab -->
<div class="section">
  <h2>⚡ Diagnosa Penyebab Loading Lambat</h2>
  <table>
    <tr><th>Penyebab</th><th>Status</th><th>Dampak</th></tr>

    <tr>
      <td><strong>License cURL check</strong><br>
        <small>config.php baris 79–80: setiap pindah menu → cURL ke escobargame.site</small></td>
      <td><?= $need_req
        ? '<span class="badge badge-bad">AKTIF SEKARANG</span>'
        : '<span class="badge badge-ok">Cached ('.($lic_age).'s)</span>' ?></td>
      <td>+2–5 detik (timeout 3s connect + 3s transfer)</td>
    </tr>

    <tr>
      <td><strong>getADBList() — shell_exec adb devices</strong><br>
        <small>index.php baris 9: blocking shell call tiap load dashboard</small></td>
      <td><?= $adb_exists
        ? '<span class="badge badge-warn">AKTIF di index.php</span>'
        : '<span class="badge badge-ok">Skip (path kosong)</span>' ?></td>
      <td>+0.5–3 detik tergantung jaringan lokal</td>
    </tr>

    <tr>
      <td><strong>warning_tos.php (19KB)</strong><br>
        <small>Di-include di SETIAP halaman via layout.php, load font + JS checkDevTools</small></td>
      <td><span class="badge badge-warn">Selalu aktif</span></td>
      <td>+50–200ms extra HTML render</td>
    </tr>

    <tr>
      <td><strong>External fonts & CDN</strong><br>
        <small>Google Fonts + Boxicons + SweetAlert2 di-load setiap halaman (tidak di-cache lokal)</small></td>
      <td><span class="badge badge-warn">Selalu aktif</span></td>
      <td>+0.5–2 detik di koneksi lambat</td>
    </tr>

    <tr>
      <td><strong>setInterval auto-reconnect ADB</strong><br>
        <small>index.php: autoReconnectAll tiap 30s + refreshADBStatus tiap 10s</small></td>
      <td><span class="badge badge-warn">Background fetch</span></td>
      <td>Tidak block halaman, tapi sibukkan server</td>
    </tr>

    <tr>
      <td><strong>sleep(1) di process.php & setup_tv.php</strong><br>
        <small>process.php baris 131, setup_tv.php baris 54+67</small></td>
      <td><span class="badge badge-warn">Saat aksi Tuya/setup</span></td>
      <td>+1–2 detik saat POST action tertentu</td>
    </tr>
  </table>
</div>

<!-- Test Buttons -->
<div class="section">
  <h2>🧪 Tes Langsung</h2>
  <p style="color:#94a3b8;font-size:0.85rem;margin-bottom:14px;">Klik tombol di bawah untuk mengukur waktu tiap komponen secara real-time:</p>

  <button class="btn" onclick="runTest('test_license', this)">⏱ Tes License cURL</button>
  <button class="btn btn-warn" onclick="runTest('test_adb', this)">⚡ Tes ADB Devices</button>
  <button class="btn btn-gray" onclick="runTest('test_db', this)">🗄 Tes Query DB</button>
  <button class="btn btn-gray" onclick="runSimulate('index')">📺 Simulasi Load index.php</button>
  <button class="btn btn-gray" onclick="runSimulate('history')">📋 Simulasi Load history.php</button>
  <button class="btn btn-gray" onclick="runSimulate('closing')">💰 Simulasi Load closing.php</button>

  <pre id="output"></pre>
</div>

<!-- Solusi -->
<div class="section">
  <h2>🔧 Solusi yang Direkomendasikan</h2>
  <table>
    <tr><th>#</th><th>Fix</th><th>Cara</th><th>Efek</th></tr>
    <tr>
      <td>1</td>
      <td><strong>Fix license check: perpanjang cache + fallback lebih toleran</strong></td>
      <td>Di config.php baris 71: ubah <code>_INT</code> dari 3600 → 7200<br>
          Atau tambahkan: hanya check jika session <em>belum ada sama sekali</em></td>
      <td>Eliminasi loading 2–5 detik hampir sepenuhnya</td>
    </tr>
    <tr>
      <td>2</td>
      <td><strong>Jadikan getADBList() async / lazy di index.php</strong></td>
      <td>Hapus <code>$adb_list = getADBList();</code> dari top-level index.php, pindah ke AJAX endpoint</td>
      <td>Halaman muncul dulu, status ADB load di background</td>
    </tr>
    <tr>
      <td>3</td>
      <td><strong>Cache external fonts & CDN secara lokal</strong></td>
      <td>Download Boxicons, Inter font, SweetAlert2 ke folder <code>/assets/</code> lokal</td>
      <td>Eliminasi 0.5–2 detik di koneksi lambat</td>
    </tr>
    <tr>
      <td>4</td>
      <td><strong>Pasang Page Timing Log ke semua halaman</strong></td>
      <td>Tambah kode berikut di baris pertama config.php:<br>
        <code>$__t=microtime(true);register_shutdown_function(function()use(&$__t){@file_put_contents(__DIR__.'/page_timing.log',date('H:i:s').' | '.basename($_SERVER['PHP_SELF']).' | '.round((microtime(true)-$__t)*1000)."ms\n",FILE_APPEND);});</code></td>
      <td>Log otomatis waktu tiap halaman ke <code>page_timing.log</code></td>
    </tr>
  </table>
</div>

<!-- Code Fix Siap Pakai -->
<div class="section">
  <h2>📋 Kode Fix — Copy & Paste ke config.php</h2>
  <p style="color:#94a3b8;font-size:0.85rem;margin-bottom:10px;">
    Ganti blok license check (sekitar baris 77–81 di config.php) dengan kode berikut:
  </p>
  <pre style="border-color:#06b6d4;">// ── LICENSE CHECK (FIXED: cache lebih lama, tidak block tiap halaman) ──
if (!in_array($pg, $_ALW)) {
    if (empty($lic)) { header("Location: activate.php"); exit; }
    if (!defined('LICENSE_KEY')) define('LICENSE_KEY', $lic);

    $lic_age    = time() - ($_SESSION['lic_last_check'] ?? 0);
    $lic_cached = ($_SESSION['lic_status'] ?? '') === 'success';

    // Cek hanya jika: belum pernah berhasil ATAU sudah > 2 jam
    // Sebelumnya cek tiap 1 jam — ini penyebab loading tiap pindah menu
    if (!$lic_cached || $lic_age > 7200) {
        _vls($conn);
    }
    // Bonus: log kapan license di-check (untuk debug)
    // @file_put_contents(__DIR__.'/lic_timing.log', date('H:i:s').' | '.$pg.' | age='.$lic_age.'s | cached='.($lic_cached?'yes':'no')."\n", FILE_APPEND);
}</pre>

  <p style="color:#94a3b8;font-size:0.85rem;margin: 14px 0 10px;">
    Dan untuk mematikan license sementara agar loading hilang total (testing saja):
  </p>
  <pre style="border-color:#f59e0b;">// TEMPORARY — untuk test apakah license = penyebab loading
// Tambah ini setelah preload_settings($conn):
$_SESSION['lic_status']       = 'success';
$_SESSION['lic_last_check']   = time();
$_SESSION['lic_last_success'] = time();
// Kalau setelah ini loading hilang = license check penyebabnya!
// Hapus kode ini setelah konfirmasi.</pre>
</div>

<script>
async function runTest(action, btn) {
  const out = document.getElementById('output');
  out.style.display = 'block';
  const orig = btn.innerHTML;
  btn.innerHTML = '<span class="spinner"></span> Testing...';
  btn.disabled = true;
  try {
    const t0 = performance.now();
    const res = await fetch('?'+action, { cache: 'no-store' });
    const data = await res.json();
    const total = Math.round(performance.now() - t0);
    out.innerHTML = '// ' + action + ' — browser round-trip: ' + total + 'ms\n' +
                    JSON.stringify(data, null, 2);
  } catch(e) {
    out.innerHTML = 'ERROR: ' + e.message;
  }
  btn.innerHTML = orig;
  btn.disabled = false;
}

async function runSimulate(page) {
  const out = document.getElementById('output');
  out.style.display = 'block';
  out.innerHTML = '⏳ Simulating ' + page + '.php load...';
  try {
    const t0 = performance.now();
    const res = await fetch('?simulate_page&page=' + page, { cache: 'no-store' });
    const data = await res.json();
    const total = Math.round(performance.now() - t0);
    let txt = '// Simulate ' + page + '.php — browser: ' + total + 'ms | server: ' + data.total_ms + 'ms\n\n';
    if (data.steps) {
      data.steps.forEach(s => {
        const icon = s.warn ? '⚠️' : '✓';
        const warn = s.warn ? ' ← SLOW' : '';
        txt += icon + '  ' + s.step + ' | ' + s.ms + 'ms' + warn + '\n';
      });
    }
    txt += '\n' + JSON.stringify(data, null, 2);
    out.innerHTML = txt;
  } catch(e) {
    out.innerHTML = 'ERROR: ' + e.message;
  }
}
</script>

</body>
</html>