<?php
// install_config.php
// Taruh di C:\xampp\htdocs\escobarweb\install_config.php
// Akses sekali: http://localhost/escobarweb/install_config.php
// HAPUS setelah selesai!

$new_config = '<?php
/**
 * @Escobar_Billing_Core
 * @Protected_File
 */
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }
date_default_timezone_set(\'Asia/Jakarta\');

$_CONF = [\'h\'=>\'localhost\', \'u\'=>\'root\', \'p\'=>\'\', \'n\'=>\'db_rental_ps\'];

try {
    $conn = new mysqli($_CONF[\'h\'], $_CONF[\'u\'], $_CONF[\'p\'], $_CONF[\'n\']);
    $conn->set_charset("utf8mb4");
    $conn->query("SET time_zone = \'+07:00\'");
} catch (Exception $e) { die("DB_ERR"); }

if (!function_exists(\'get_setting\')) {
    function get_setting($c, $k, $invalidate = false) {
        static $_CH = [];
        if ($invalidate) unset($_CH[$k]);
        if (isset($_CH[$k])) return $_CH[$k];
        $s = $c->prepare("SELECT setting_value FROM system_settings WHERE setting_name = ? LIMIT 1");
        $s->bind_param("s", $k); $s->execute();
        $v = ($r = $s->get_result()->fetch_assoc()) ? $r[\'setting_value\'] : \'\';
        $s->close(); return $_CH[$k] = $v;
    }
}

define(\'_API\', \'https://escobargame.site/license/api.php\');
define(\'_INT\', 0);
$lic = trim(get_setting($conn, \'license_key\'));
$pg = basename($_SERVER[\'PHP_SELF\']);
$_ALW = [\'activate.php\', \'login.php\', \'logout.php\'];

if (!in_array($pg, $_ALW)) {
    if (empty($lic)) { header("Location: activate.php"); exit; }
    if (!defined(\'LICENSE_KEY\')) define(\'LICENSE_KEY\', $lic);
    if ((time() - ($_SESSION[\'lic_last_check\'] ?? 0)) > _INT || ($_SESSION[\'lic_status\'] ?? \'\') !== \'success\') {
        _vls($conn);
    }
}

function _vls($c) {
    $h = $_SERVER[\'HTTP_HOST\'] ?? \'localhost\';
    $d = (in_array($h, [\'localhost\', \'127.0.0.1\', \'::1\'])) ? \'localhost\' : $h;
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => _API, CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => http_build_query([\'action\' => \'validate\', \'license_key\' => LICENSE_KEY, \'domain\' => $d]),
        CURLOPT_RETURNTRANSFER => 1, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => 0
    ]);
    $res = curl_exec($ch); $hc = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
    if ($hc == 200 && $res) {
        $r = json_decode($res, 1); $s = strtolower($r[\'status\'] ?? \'\');
        if ($s === \'success\' || $s === \'active\') {
            $_SESSION[\'lic_status\'] = \'success\'; $_SESSION[\'lic_last_check\'] = time(); $_SESSION[\'lic_last_success\'] = time();
            return 1;
        }
    }
    if (isset($_SESSION[\'lic_last_success\']) && (time() - $_SESSION[\'lic_last_success\']) < 0) return 1;
    if (basename($_SERVER[\'PHP_SELF\']) !== \'process.php\') _sle(\'INVALID\');
    return 0;
}

function _sle($c) {
    unset($_SESSION[\'lic_status\'], $_SESSION[\'lic_last_check\']);
    $msg = "Akses Diblokir. Lisensi Suspended.";
    $wa  = "https://wa.me/62818110242";
    die("<html><head><title>Blocked</title><style>body{background:#030712;color:#fff;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center}.box{background:rgba(15,23,42,.6);padding:40px;border-radius:30px;border:1px solid rgba(239,68,68,.2);max-width:400px}h1{color:#ef4444}a{display:inline-block;margin-top:20px;padding:12px 25px;background:#ef4444;color:#fff;text-decoration:none;border-radius:10px}</style></head><body><div class=\'box\'><h1>Akses Diblokir</h1><p>$msg</p><small>Code: $c</small><br><a href=\'$wa\'>Hubungi Dukungan</a></div></body></html>");
}

function getTVData($c, $id) {
    $id = (int)$id;
    $s = $c->prepare("SELECT t.*, trx.jenis_paket, trx.start_time, trx.target_selesai, trx.remaining_seconds, trx.rate_per_jam, m.nama_member FROM tvs t LEFT JOIN transactions trx ON t.current_trx_id = trx.id LEFT JOIN members m ON trx.member_id = m.id WHERE t.id = ?");
    $s->bind_param("i", $id); $s->execute();
    $r = $s->get_result()->fetch_assoc(); $s->close();
    if ($r) $r[\'trx_data\'] = $r[\'current_trx_id\'] ? $r : null;
    return $r;
}

function getADBList() {
    global $conn; $p = get_setting($conn, \'adb_path\');
    if (empty($p) || !file_exists($p)) return [];
    $o = @shell_exec("\"$p\" devices 2>&1"); $d = [];
    if ($o) { foreach(explode("\n", $o) as $l) { if (preg_match(\'/^([^\s]+)\s+device$/\', trim($l), $m)) $d[$m[1]] = \'device\'; } }
    return $d;
}

function checkADBStatus($ip, $l = null) {
    if (empty($ip)) return \'offline\';
    $l = $l ?? getADBList();
    $s = (strpos($ip, ":5555") === false) ? trim($ip) . ":5555" : trim($ip);
    return isset($l[$s]) ? \'online\' : \'offline\';
}

function controlTV($ip, $a, $e = null) {
    global $conn;
    $p = get_setting($conn, \'adb_path\');
    if (empty($p) || !file_exists($p)) return 0;

    $adb = $p;
    $s   = (strpos($ip, \':\') === false) ? trim($ip) . ":5555" : trim($ip);

    if ($a !== \'connect\') {
        $connect_cmd = "cmd /c \"\"$adb\" connect $s > NUL 2>&1\"";
        pclose(popen($connect_cmd, "r"));
        sleep(1);
    }

    $cmd = "";

    switch ($a) {

        case \'connect\':
            $cmd = "cmd /c \"\"$adb\" connect $s\"";
            break;

        case \'power\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 26\"";
            break;

        case \'home\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 3\"";
            break;

        case \'vol_up\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 24\"";
            break;

        case \'vol_down\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 25\"";
            break;

        case \'wake\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 224\"";
            break;

        case \'sleep\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell input keyevent 223\"";
            break;

        case \'stop\':
            $cmd = "cmd /c \"\"$adb\" -s $s shell am force-stop com.example.escobar_tv_client\"";
            pclose(popen($cmd, "r"));
            $log_line = date(\'Y-m-d H:i:s\') . " | Action: stop | IP: $s | CMD: $cmd\n";
            @file_put_contents(__DIR__ . "/adb_debug.log", $log_line, FILE_APPEND);
            return 1;

        case \'start_overlay\':
            $args = "";
            if (is_array($e)) {
                foreach ($e as $k => $v) {
                    if (is_numeric($v)) {
                        $args .= " --ei " . $k . " " . (int)$v;
                    } else {
                        $safe  = preg_replace(\'/[^a-zA-Z0-9\\.\\-\\_]/\', \'_\', (string)$v);
                        $args .= " --es " . $k . " " . $safe;
                    }
                }
            }
            $component = "com.example.escobar_tv_client/.OverlayService";
            $shell_cmd = "am start-foreground-service -n $component$args";
            $cmd = "cmd /c \"\"$adb\" -s $s shell $shell_cmd\"";
            break;

        case \'pause_overlay\':
            $component = "com.example.escobar_tv_client/.OverlayService";
            $shell_cmd = "am start-foreground-service -n $component --es action PAUSE";
            $cmd = "cmd /c \"\"$adb\" -s $s shell $shell_cmd\"";
            break;

        case \'resume_overlay\':
            $component = "com.example.escobar_tv_client/.OverlayService";
            $shell_cmd = "am start-foreground-service -n $component --es action RESUME";
            $cmd = "cmd /c \"\"$adb\" -s $s shell $shell_cmd\"";
            break;
    }

    if ($cmd) {
        $log_line = date(\'Y-m-d H:i:s\') . " | Action: $a | IP: $s | CMD: $cmd\n";
        @file_put_contents(__DIR__ . "/adb_debug.log", $log_line, FILE_APPEND);
        pclose(popen($cmd, "r"));
        return 1;
    }
    return 0;
}

function checkLogin() {
    if (!isset($_SESSION[\'user_id\'])) {
        header("Location: login.php");
        exit;
    }
}

function onlyAdmin() { if (($_SESSION[\'role\']??\'\')=== \'admin\' ? false : true) { header("Location: index.php?status=restricted"); exit; } }
function has_access($c, $p) { return ($_SESSION[\'role\']??\'\')=== \'admin\' || get_setting($c, $p) === \'1\'; }

function write_log($c, $a, $d) {
    if (session_status() === PHP_SESSION_NONE) { @session_start(); }
    if ($uid = ($_SESSION[\'user_id\'] ?? 0)) {
        $un = $_SESSION[\'username\'] ?? \'Sys\';
        $s  = $c->prepare("INSERT INTO activity_logs (user_id, username, action, details, created_at) VALUES (?, ?, ?, ?, NOW())");
        $s->bind_param("isss", $uid, $un, $a, $d);
        $s->execute();
        $s->close();
    }
}
';

echo "<style>body{font-family:monospace;background:#111;color:#0f0;padding:20px}.err{color:#f44}.ok{color:#0f0}</style>";
echo "<h2>🔧 Install config.php Baru</h2>";

$target = __DIR__ . "/config.php";

// Backup dulu
$backup = __DIR__ . "/config.php.bak." . date('YmdHis');
if (copy($target, $backup)) {
    echo "<span class='ok'>✅ Backup dibuat: $backup</span><br>";
} else {
    echo "<span class='err'>⚠ Gagal backup — lanjut tetap</span><br>";
}

// Tulis config baru
$result = file_put_contents($target, $new_config);

if ($result !== false) {
    echo "<span class='ok'>✅ config.php berhasil diupdate! ($result bytes ditulis)</span><br><br>";
    echo "Terakhir diubah: <b>" . date('Y-m-d H:i:s', filemtime($target)) . "</b><br><br>";

    // Verifikasi
    $isi = file_get_contents($target);
    $checks = [
        'Ada pause_overlay'  => strpos($isi, "'pause_overlay'") !== false,
        'Ada adb_debug.log'  => strpos($isi, 'adb_debug.log') !== false,
        'Ada sleep(1)'       => strpos($isi, 'sleep(1)') !== false,
        'Ada resume_overlay' => strpos($isi, "'resume_overlay'") !== false,
    ];
    foreach ($checks as $label => $ok) {
        echo ($ok ? "<span class='ok'>✅" : "<span class='err'>❌") . " $label</span><br>";
    }

    echo "<br><b style='color:#ff0'>⚠ HAPUS file install_config.php sekarang!</b><br>";
    echo "<a href='index.php' style='color:#0f0'>→ Kembali ke aplikasi</a>";
} else {
    echo "<span class='err'>❌ GAGAL menulis config.php!</span><br>";
    echo "Coba: klik kanan folder escobarweb → Properties → Security → beri Full Control ke user IUSR / Everyone<br>";
}
?>