<?php
// debug_pause.php
// Taruh file ini di folder yang sama dengan config.php
// Akses: http://localhost/debug_pause.php?tv_id=1
// HAPUS FILE INI setelah selesai debug!

include 'config.php';

$tv_id = isset($_GET['tv_id']) ? (int)$_GET['tv_id'] : 0;
$test_adb = isset($_GET['test_adb']) ? true : false;
$test_pause = isset($_GET['test_pause']) ? true : false;

echo "<style>body{font-family:monospace;background:#111;color:#0f0;padding:20px} .ok{color:#0f0} .err{color:#f44} .warn{color:#ff0} pre{background:#222;padding:10px;border-radius:5px} h2{color:#fff} hr{border-color:#333}</style>";
echo "<h2>🔧 Escobar Pause Debug Tool</h2>";

// ── 1. Cek koneksi DB ──────────────────────────────────────
echo "<h2>1. Koneksi Database</h2>";
if ($conn && !$conn->connect_error) {
    echo "<span class='ok'>✅ DB OK: " . $_CONF['n'] . "</span><br>";
} else {
    echo "<span class='err'>❌ DB ERROR: " . $conn->connect_error . "</span><br>";
    die();
}

// ── 2. Cek ADB path ──────────────────────────────────────
echo "<h2>2. ADB Path</h2>";
$adb_path = get_setting($conn, 'adb_path');
echo "adb_path dari DB: <b>" . htmlspecialchars($adb_path) . "</b><br>";
if (empty($adb_path)) {
    echo "<span class='err'>❌ adb_path KOSONG di database! Isi dulu di Settings.</span><br>";
} elseif (!file_exists($adb_path)) {
    echo "<span class='err'>❌ File ADB tidak ditemukan di path tersebut!</span><br>";
    echo "<span class='warn'>⚠ Pastikan path benar, contoh: C:\\platform-tools\\adb.exe</span><br>";
} else {
    echo "<span class='ok'>✅ File ADB ditemukan</span><br>";
    // Test ADB version
    $ver = @shell_exec("\"$adb_path\" version 2>&1");
    echo "ADB Version: <pre>" . htmlspecialchars($ver) . "</pre>";
}

// ── 3. Cek Data TV ──────────────────────────────────────
echo "<h2>3. Data TV (tv_id=$tv_id)</h2>";
if (!$tv_id) {
    echo "<span class='warn'>⚠ Tambahkan ?tv_id=X ke URL. Daftar TV:</span><br>";
    $tvs = $conn->query("SELECT id, nama_tv, ip_address, status, current_trx_id FROM tvs");
    echo "<table border=1 style='border-color:#333;border-collapse:collapse'>";
    echo "<tr><th>ID</th><th>Nama</th><th>IP</th><th>Status</th><th>Trx ID</th><th>Link</th></tr>";
    while ($tv = $tvs->fetch_assoc()) {
        $link = "?tv_id=" . $tv['id'];
        echo "<tr><td>{$tv['id']}</td><td>{$tv['nama_tv']}</td><td>{$tv['ip_address']}</td><td>{$tv['status']}</td><td>{$tv['current_trx_id']}</td><td><a href='$link'>Debug</a></td></tr>";
    }
    echo "</table>";
    die();
}

$tv = $conn->query("SELECT * FROM tvs WHERE id=$tv_id")->fetch_assoc();
if (!$tv) {
    echo "<span class='err'>❌ TV id=$tv_id tidak ditemukan!</span><br>";
    die();
}

echo "Nama TV   : <b>{$tv['nama_tv']}</b><br>";
echo "IP Address: <b>{$tv['ip_address']}</b><br>";
echo "Status    : <b style='color:" . ($tv['status']=='active'?'#0f0':'#ff0') . "'>{$tv['status']}</b><br>";
echo "Trx ID    : <b>{$tv['current_trx_id']}</b><br>";

$trx_id = $tv['current_trx_id'];
$ip     = $tv['ip_address'];

// ── 4. Cek Transaksi ──────────────────────────────────────
echo "<h2>4. Transaksi Aktif</h2>";
if (!$trx_id) {
    echo "<span class='err'>❌ current_trx_id = NULL — TV tidak punya transaksi aktif!</span><br>";
    echo "<span class='warn'>⚠ Inilah kenapa PAUSE tidak jalan: kondisi if(\$trx_id) GAGAL di process.php</span><br>";
} else {
    $trx = $conn->query("SELECT * FROM transactions WHERE id=$trx_id")->fetch_assoc();
    if (!$trx) {
        echo "<span class='err'>❌ Trx #$trx_id tidak ada di tabel transactions!</span><br>";
    } else {
        echo "ID        : <b>{$trx['id']}</b><br>";
        echo "Status    : <b style='color:" . ($trx['status']=='ongoing'?'#0f0':'#ff0') . "'>{$trx['status']}</b><br>";
        echo "Jenis     : <b>{$trx['jenis_paket']}</b><br>";
        echo "Start Time: <b>{$trx['start_time']}</b><br>";
        echo "Target    : <b>{$trx['target_selesai']}</b><br>";
        echo "Remaining : <b>{$trx['remaining_seconds']}</b> detik<br>";

        if ($trx['status'] !== 'ongoing') {
            echo "<span class='err'>❌ STATUS BUKAN 'ongoing' — kondisi pause GAGAL di process.php!</span><br>";
            echo "<span class='warn'>Status saat ini: '{$trx['status']}' — harus 'ongoing' agar bisa di-pause</span><br>";
        } else {
            echo "<span class='ok'>✅ Status ongoing — siap di-pause</span><br>";
        }
    }
}

// ── 5. Cek ADB Devices ──────────────────────────────────────
echo "<h2>5. ADB Devices</h2>";
if (!empty($adb_path) && file_exists($adb_path)) {
    $devices_raw = @shell_exec("\"$adb_path\" devices 2>&1");
    echo "<pre>" . htmlspecialchars($devices_raw) . "</pre>";

    $s = (strpos($ip, ':') === false) ? trim($ip) . ":5555" : trim($ip);
    if (strpos($devices_raw, $s) !== false && strpos($devices_raw, 'device') !== false) {
        echo "<span class='ok'>✅ TV $s terdeteksi oleh ADB</span><br>";
    } else {
        echo "<span class='err'>❌ TV $s TIDAK terdeteksi oleh ADB!</span><br>";
        echo "<span class='warn'>⚠ Coba connect manual: adb connect $s</span><br>";
    }
} else {
    echo "<span class='err'>❌ ADB tidak bisa dijalankan</span><br>";
}

// ── 6. Test ADB Connect ──────────────────────────────────────
echo "<h2>6. Test ADB Connect ke TV</h2>";
if (!empty($adb_path) && file_exists($adb_path) && $ip) {
    $s = (strpos($ip, ':') === false) ? trim($ip) . ":5555" : trim($ip);

    // Gunakan shell_exec (blocking) untuk dapat output
    $connect_out = @shell_exec("\"$adb_path\" connect $s 2>&1");
    echo "Output connect: <pre>" . htmlspecialchars($connect_out) . "</pre>";

    if (strpos($connect_out, 'connected') !== false) {
        echo "<span class='ok'>✅ ADB connect berhasil</span><br>";
    } elseif (strpos($connect_out, 'already') !== false) {
        echo "<span class='ok'>✅ ADB sudah connected sebelumnya</span><br>";
    } else {
        echo "<span class='err'>❌ ADB connect GAGAL — cek IP TV dan pastikan ADB debugging aktif</span><br>";
    }
} else {
    echo "<span class='warn'>⚠ Skip: ADB path kosong atau tidak ada</span><br>";
}

// ── 7. Test Kirim PAUSE langsung ──────────────────────────────────────
echo "<h2>7. Test Kirim PAUSE ke TV</h2>";
if ($test_pause && !empty($adb_path) && file_exists($adb_path) && $ip) {
    $s = (strpos($ip, ':') === false) ? trim($ip) . ":5555" : trim($ip);

    // Connect dulu
    $c1 = @shell_exec("\"$adb_path\" connect $s 2>&1");
    echo "Connect: <pre>" . htmlspecialchars($c1) . "</pre>";
    sleep(1);

    // Kirim PAUSE — BLOCKING agar dapat output langsung
    $pause_cmd = "\"$adb_path\" -s $s shell am start-foreground-service -n com.example.escobar_tv_client/.OverlayService --es action PAUSE";
    echo "Command: <pre>" . htmlspecialchars($pause_cmd) . "</pre>";

    $pause_out = @shell_exec($pause_cmd . " 2>&1");
    echo "Output: <pre>" . htmlspecialchars($pause_out) . "</pre>";

    if (strpos($pause_out, 'Starting service') !== false || strpos($pause_out, 'start') !== false) {
        echo "<span class='ok'>✅ Command dikirim ke Android</span><br>";
    } elseif (empty($pause_out)) {
        echo "<span class='warn'>⚠ Output kosong — mungkin berhasil, cek TV</span><br>";
    } else {
        echo "<span class='err'>❌ Ada error: " . htmlspecialchars($pause_out) . "</span><br>";
    }

    // Tulis ke debug log
    $log = date('Y-m-d H:i:s') . " | DEBUG_PAUSE | IP: $s | CMD: $pause_cmd | OUT: $pause_out\n";
    @file_put_contents(__DIR__ . "/adb_debug.log", $log, FILE_APPEND);
    echo "<span class='ok'>✅ Log ditulis ke adb_debug.log</span><br>";
    echo "<br><b>Cek TV sekarang — apakah overlay DIJEDA?</b><br>";

} else {
    echo "<a href='?tv_id=$tv_id&test_pause=1' style='background:#333;color:#0f0;padding:10px;text-decoration:none;border-radius:5px'>▶ Klik ini untuk kirim PAUSE ke TV sekarang</a><br>";
    echo "<br><span class='warn'>⚠ Pastikan overlay sudah aktif di TV sebelum test ini</span><br>";
}

// ── 8. Test ADB shell langsung ──────────────────────────────────────
echo "<h2>8. Test ADB Shell (getprop)</h2>";
if ($test_adb && !empty($adb_path) && file_exists($adb_path) && $ip) {
    $s = (strpos($ip, ':') === false) ? trim($ip) . ":5555" : trim($ip);
    $prop_out = @shell_exec("\"$adb_path\" -s $s shell getprop ro.build.version.release 2>&1");
    echo "Android version di TV: <pre>" . htmlspecialchars($prop_out) . "</pre>";
    if (!empty($prop_out) && is_numeric(trim($prop_out))) {
        echo "<span class='ok'>✅ ADB shell berfungsi — Android " . trim($prop_out) . "</span><br>";
    } else {
        echo "<span class='err'>❌ ADB shell gagal atau tidak ada response</span><br>";
    }
} else {
    echo "<a href='?tv_id=$tv_id&test_adb=1' style='background:#333;color:#0f0;padding:10px;text-decoration:none;border-radius:5px'>▶ Klik ini untuk test ADB shell</a><br>";
}

// ── 9. Cek PHP: kenapa adb_debug.log tidak terbuat ──────────────────────────────────────
echo "<h2>9. Diagnosa: Kenapa adb_debug.log Tidak Ada?</h2>";
$log_file = __DIR__ . "/adb_debug.log";
if (file_exists($log_file)) {
    echo "<span class='ok'>✅ adb_debug.log ADA</span><br>";
    echo "<pre>" . htmlspecialchars(file_get_contents($log_file)) . "</pre>";
} else {
    echo "<span class='warn'>⚠ adb_debug.log belum ada</span><br>";
    // Coba buat
    $test_write = @file_put_contents($log_file, date('Y-m-d H:i:s') . " | DEBUG_TEST | File berhasil dibuat\n");
    if ($test_write !== false) {
        echo "<span class='ok'>✅ PHP bisa menulis file di folder ini — log akan muncul setelah PAUSE dikirim</span><br>";
    } else {
        echo "<span class='err'>❌ PHP TIDAK BISA menulis file di folder ini!</span><br>";
        echo "<span class='err'>   Ini berarti controlTV() berjalan tapi log gagal ditulis.</span><br>";
        echo "<span class='warn'>   Kemungkinan penyebab: permission folder tidak allow write dari web server</span><br>";
        echo "   Coba: <code>chmod 777 " . __DIR__ . "</code><br>";
    }
}

// ── 10. Simulasi logika PAUSE di process.php ──────────────────────────────────────
echo "<h2>10. Simulasi Kondisi PAUSE di process.php</h2>";
echo "Mengecek apakah kondisi-kondisi di case 'pause': terpenuhi...<br><br>";

// Cek $tv_id
echo "\$tv_id = $tv_id → " . ($tv_id ? "<span class='ok'>✅ OK</span>" : "<span class='err'>❌ FAIL — tv_id kosong</span>") . "<br>";

// Cek $trx_id
echo "\$trx_id = $trx_id → " . ($trx_id ? "<span class='ok'>✅ OK</span>" : "<span class='err'>❌ FAIL — trx_id NULL, kondisi if(\$trx_id) GAGAL</span>") . "<br>";

// Cek status transaksi
if ($trx_id) {
    $trx = $conn->query("SELECT status, jenis_paket FROM transactions WHERE id=$trx_id")->fetch_assoc();
    $status_ok = ($trx && $trx['status'] === 'ongoing');
    echo "status transaksi = '{$trx['status']}' → " . ($status_ok ? "<span class='ok'>✅ ongoing — kondisi terpenuhi</span>" : "<span class='err'>❌ FAIL — harus 'ongoing', ini '{$trx['status']}'</span>") . "<br>";

    if (!$status_ok) {
        echo "<br><span class='err'>🚨 INI PENYEBAB PAUSE TIDAK JALAN!</span><br>";
        echo "Status transaksi bukan 'ongoing' sehingga blok kode pause tidak dieksekusi.<br>";
        if ($trx['status'] === 'paused') {
            echo "<span class='warn'>Status sudah 'paused' — kemungkinan pause berhasil sebelumnya tapi overlay tidak update</span><br>";
        }
    }

    // Cek $ip
    echo "\$ip = '$ip' → " . (!empty($ip) ? "<span class='ok'>✅ OK</span>" : "<span class='err'>❌ FAIL — IP kosong</span>") . "<br>";
}

// ── 11. Cek process.php dipanggil dengan benar ──────────────────────────────────────
echo "<h2>11. Cara Panggil process.php untuk PAUSE</h2>";
echo "URL yang benar:<br>";
echo "<pre>POST process.php?action=pause&tv_id=$tv_id</pre>";
echo "atau:<br>";
echo "<pre>GET/POST process.php dengan body: action=pause&tv_id=$tv_id</pre>";
echo "<br>";
echo "<a href='../process.php?action=pause&tv_id=$tv_id&ajax=1' target='_blank' style='background:#1a3a1a;color:#0f0;padding:10px;text-decoration:none;border-radius:5px'>▶ Test kirim PAUSE via process.php (buka tab baru)</a><br>";

echo "<br><hr><br>";
echo "<span style='color:#555'>Debug selesai. HAPUS file debug_pause.php setelah selesai!</span>";
?>