<?php
/**
 * tuya_debug.php — Diagnostic Tool
 * Taruh file ini di folder escobarweb, akses dari browser.
 * HAPUS file ini setelah selesai debug!
 */

// Keamanan sederhana — akses hanya dari localhost
$allowed = ['127.0.0.1', '::1', 'localhost'];
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', $allowed)) {
    die("Akses ditolak. Hanya dari localhost.");
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tuya Debug — Escobar</title>
<style>
    body { font-family: Consolas, monospace; background: #0f172a; color: #e2e8f0; padding: 24px; }
    h2 { color: #06b6d4; border-bottom: 1px solid #334155; padding-bottom: 8px; }
    .box { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 16px; margin-bottom: 16px; }
    .ok  { color: #22c55e; font-weight: bold; }
    .err { color: #ef4444; font-weight: bold; }
    .warn{ color: #f59e0b; font-weight: bold; }
    .info{ color: #94a3b8; }
    pre  { background: #0f172a; border: 1px solid #334155; padding: 12px; border-radius: 6px;
           overflow-x: auto; font-size: 13px; white-space: pre-wrap; word-break: break-all; }
    label { color: #94a3b8; font-size: 12px; display: block; margin-bottom: 4px; }
    input, select { background: #0f172a; border: 1px solid #334155; color: #fff;
                    padding: 8px 12px; border-radius: 6px; width: 100%; margin-bottom: 12px; font-family: Consolas, monospace; }
    button { background: #06b6d4; color: #000; border: none; padding: 10px 22px;
             border-radius: 6px; font-weight: bold; cursor: pointer; font-size: 14px; }
    .section { margin-bottom: 28px; }
    table { width: 100%; border-collapse: collapse; }
    td { padding: 6px 10px; border-bottom: 1px solid #334155; font-size: 13px; }
    td:first-child { color: #94a3b8; width: 240px; }
</style>
</head>
<body>

<h2>🔧 Tuya Debug Tool — Escobar Billing</h2>
<p class="info" style="margin-bottom:20px">Diagnostic tool untuk troubleshoot koneksi Smart Plug Tuya dari sisi PHP/server.</p>

<!-- ════════════════════════════════════════
     BAGIAN 1: INFO ENVIRONMENT PHP
════════════════════════════════════════ -->
<div class="section">
<h2>1. Environment PHP & Server</h2>
<div class="box">
<table>
<tr><td>PHP Version</td><td><?= PHP_VERSION ?></td></tr>
<tr><td>OS</td><td><?= PHP_OS ?> (<?= PHP_OS_FAMILY ?>)</td></tr>
<tr><td>PHP_OS WIN detection</td><td>
    <?php $is_win = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; ?>
    <?php if ($is_win): ?>
        <span class="ok">✔ Terdeteksi Windows → akan pakai command "python"</span>
    <?php else: ?>
        <span class="warn">⚠ Bukan Windows → akan pakai command "python3"</span>
    <?php endif; ?>
</td></tr>
<tr><td>DOCUMENT_ROOT</td><td><?= $_SERVER['DOCUMENT_ROOT'] ?? '-' ?></td></tr>
<tr><td>__DIR__ (lokasi file ini)</td><td><?= __DIR__ ?></td></tr>
<tr><td>tuya_bridge.py ada?</td><td>
    <?php $script = __DIR__ . DIRECTORY_SEPARATOR . 'tuya_bridge.py'; ?>
    <?php if (file_exists($script)): ?>
        <span class="ok">✔ Ada di: <?= $script ?></span>
    <?php else: ?>
        <span class="err">✘ TIDAK ADA di: <?= $script ?></span>
    <?php endif; ?>
</td></tr>
<tr><td>shell_exec() aktif?</td><td>
    <?php $disabled = explode(',', ini_get('disable_functions') ?? ''); ?>
    <?php if (in_array('shell_exec', array_map('trim', $disabled))): ?>
        <span class="err">✘ DINONAKTIFKAN di php.ini — ini penyebab utama!</span>
    <?php else: ?>
        <span class="ok">✔ Aktif</span>
    <?php endif; ?>
</td></tr>
<tr><td>exec() aktif?</td><td>
    <?php if (in_array('exec', array_map('trim', $disabled))): ?>
        <span class="err">✘ DINONAKTIFKAN di php.ini</span>
    <?php else: ?>
        <span class="ok">✔ Aktif</span>
    <?php endif; ?>
</td></tr>
<tr><td>disable_functions (raw)</td><td style="font-size:11px"><?= ini_get('disable_functions') ?: '(kosong)' ?></td></tr>
</table>
</div>
</div>

<!-- ════════════════════════════════════════
     BAGIAN 2: CEK PYTHON DARI PHP
════════════════════════════════════════ -->
<div class="section">
<h2>2. Cek Python dari PHP (shell_exec)</h2>
<div class="box">
<?php
$python_candidates = ['python', 'python3', 'py'];

foreach ($python_candidates as $py) {
    // Test versi
    $output = @shell_exec("$py --version 2>&1");
    if ($output === null || $output === false || trim($output) === '') {
        echo "<p>Command <code>$py --version</code>: <span class='err'>✘ Tidak bisa dijalankan / tidak ditemukan</span></p>";
    } else {
        $ver = trim($output);
        echo "<p>Command <code>$py --version</code>: <span class='ok'>✔ " . htmlspecialchars($ver) . "</span></p>";
    }
}

echo "<hr style='border-color:#334155;margin:12px 0'>";

// PATH yang dilihat PHP
$php_path = @shell_exec("echo %PATH% 2>&1");
if ($php_path) {
    echo "<p><strong>PATH yang terlihat oleh PHP:</strong></p>";
    echo "<pre>" . htmlspecialchars(trim($php_path)) . "</pre>";
} else {
    // Coba cara lain
    $php_path2 = @shell_exec("set PATH 2>&1");
    echo "<p><strong>PATH (via set):</strong></p>";
    echo "<pre>" . htmlspecialchars(trim($php_path2 ?? 'tidak bisa dibaca')) . "</pre>";
}

// Python path absolut
$py_where = @shell_exec("where python 2>&1");
echo "<p><strong>Lokasi python (where python):</strong></p>";
echo "<pre>" . htmlspecialchars(trim($py_where ?? 'tidak bisa dijalankan')) . "</pre>";
?>
</div>
</div>

<!-- ════════════════════════════════════════
     BAGIAN 3: CEK TINYTUYA
════════════════════════════════════════ -->
<div class="section">
<h2>3. Cek tinytuya terinstall</h2>
<div class="box">
<?php
$py_cmd = $is_win ? 'python' : 'python3';

// Coba import tinytuya
$check_import = @shell_exec("$py_cmd -c \"import tinytuya; print('OK:' + tinytuya.__version__)\" 2>&1");
if ($check_import && strpos($check_import, 'OK:') === 0) {
    $ver = trim(str_replace('OK:', '', $check_import));
    echo "<p><span class='ok'>✔ tinytuya terinstall, versi: $ver</span></p>";
} else {
    echo "<p><span class='err'>✘ tinytuya TIDAK terinstall atau tidak bisa diakses</span></p>";
    echo "<pre>" . htmlspecialchars($check_import ?? 'null output') . "</pre>";
    echo "<p class='warn'>⚠ Solusi: Buka CMD sebagai Administrator, jalankan:<br>";
    echo "<code>python -m pip install tinytuya</code></p>";
}

// Cek pip list tinytuya
$pip_check = @shell_exec("$py_cmd -m pip show tinytuya 2>&1");
echo "<p><strong>pip show tinytuya:</strong></p>";
echo "<pre>" . htmlspecialchars($pip_check ?? 'null') . "</pre>";
?>
</div>
</div>

<!-- ════════════════════════════════════════
     BAGIAN 4: TEST LANGSUNG KE PLUG
════════════════════════════════════════ -->
<div class="section">
<h2>4. Test Koneksi ke Smart Plug</h2>
<div class="box">
<form method="POST">
    <label>Device ID</label>
    <input type="text" name="t_device_id" value="<?= htmlspecialchars($_POST['t_device_id'] ?? '') ?>" placeholder="bf123abc...">

    <label>IP Address</label>
    <input type="text" name="t_ip" value="<?= htmlspecialchars($_POST['t_ip'] ?? '') ?>" placeholder="192.168.1.x">

    <label>Local Key</label>
    <input type="text" name="t_key" value="<?= htmlspecialchars($_POST['t_key'] ?? '') ?>" placeholder="abc123xyz...">

    <label>Versi Protocol</label>
    <select name="t_version">
        <option value="3.1" <?= ($_POST['t_version']??'3.4')==='3.1'?'selected':'' ?>>3.1</option>
        <option value="3.3" <?= ($_POST['t_version']??'3.4')==='3.3'?'selected':'' ?>>3.3</option>
        <option value="3.4" <?= ($_POST['t_version']??'3.4')==='3.4'?'selected':'' ?>>3.4 (default)</option>
        <option value="3.5" <?= ($_POST['t_version']??'3.4')==='3.5'?'selected':'' ?>>3.5</option>
    </select>

    <label>Action</label>
    <select name="t_action">
        <option value="status" <?= ($_POST['t_action']??'status')==='status'?'selected':'' ?>>status (cek ON/OFF)</option>
        <option value="on"     <?= ($_POST['t_action']??'')==='on'?'selected':'' ?>>on (nyalakan)</option>
        <option value="off"    <?= ($_POST['t_action']??'')==='off'?'selected':'' ?>>off (matikan)</option>
    </select>

    <button type="submit">▶ Jalankan Test</button>
</form>

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['t_device_id'])): ?>
<?php
    $t_device  = escapeshellarg(trim($_POST['t_device_id']));
    $t_ip      = escapeshellarg(trim($_POST['t_ip']));
    $t_key     = escapeshellarg(trim($_POST['t_key']));
    $t_version = escapeshellarg(in_array($_POST['t_version'], ['3.1','3.3','3.4','3.5']) ? $_POST['t_version'] : '3.4');
    $t_action  = escapeshellarg(in_array($_POST['t_action'], ['status','on','off']) ? $_POST['t_action'] : 'status');
    $py_cmd2   = $is_win ? 'python' : 'python3';

    // Coba dengan python path absolut kalau normal gagal
    $py_where_raw = @shell_exec("where python 2>&1");
    $py_abs = '';
    if ($py_where_raw) {
        $lines = explode("\n", trim($py_where_raw));
        foreach ($lines as $l) {
            $l = trim($l);
            if (str_ends_with(strtolower($l), '.exe') && file_exists($l)) {
                $py_abs = $l;
                break;
            }
        }
    }

    $script = __DIR__ . DIRECTORY_SEPARATOR . 'tuya_bridge.py';
    $cmd = "$py_cmd2 " . escapeshellarg($script) . " $t_device $t_ip $t_key $t_version $t_action 2>&1";
    echo "<hr style='border-color:#334155;margin:16px 0'>";
    echo "<p><strong>Command yang dijalankan:</strong></p>";
    echo "<pre>" . htmlspecialchars(str_replace(escapeshellarg(trim($_POST['t_key'])), '***KEY***', $cmd)) . "</pre>";

    $start = microtime(true);
    $output = @shell_exec($cmd);
    $elapsed = round((microtime(true) - $start) * 1000);

    echo "<p><strong>Output ({$elapsed}ms):</strong></p>";
    echo "<pre>" . htmlspecialchars($output ?? 'null — shell_exec return NULL') . "</pre>";

    // Parse JSON
    if ($output) {
        $json = @json_decode(trim($output), true);
        if ($json) {
            if ($json['ok'] ?? false) {
                echo "<p class='ok'>✔ BERHASIL TERHUBUNG!</p>";
                echo "<p>Status: " . ($json['is_on'] ? "<span class='ok'>NYALA (ON)</span>" : "<span class='info'>MATI (OFF)</span>") . "</p>";
                if (isset($json['power'])) echo "<p>Power: " . $json['power'] . " W</p>";
            } else {
                echo "<p class='err'>✘ Gagal: " . htmlspecialchars($json['msg'] ?? 'unknown') . "</p>";
            }
            if (!empty($json['raw_dps'])) {
                echo "<p><strong>Raw DPS (semua data dari plug):</strong></p>";
                echo "<pre>" . htmlspecialchars(json_encode($json['raw_dps'], JSON_PRETTY_PRINT)) . "</pre>";
            }
        }
    }

    // Coba dengan path absolut kalau gagal
    if ((!$output || $output === null) && $py_abs) {
        echo "<hr style='border-color:#334155;margin:16px 0'>";
        echo "<p class='warn'>⚠ Mencoba dengan path absolut Python: <code>" . htmlspecialchars($py_abs) . "</code></p>";
        $cmd_abs = escapeshellarg($py_abs) . " " . escapeshellarg($script) . " $t_device $t_ip $t_key $t_version $t_action 2>&1";
        $output2 = @shell_exec($cmd_abs);
        echo "<pre>" . htmlspecialchars($output2 ?? 'null juga') . "</pre>";

        if ($output2 && str_contains($output2, '"ok"')) {
            echo "<p class='ok'>✔ Berhasil dengan path absolut!</p>";
            echo "<p class='warn'>⚠ <strong>Solusi:</strong> Edit <code>tuya_api.php</code> dan <code>process.php</code>,<br>";
            echo "ganti baris <code>\$python = ...</code> menjadi:</p>";
            echo "<pre>\$python = " . htmlspecialchars("'" . $py_abs . "'") . ";</pre>";
        }
    }
?>
<?php endif; ?>
</div>
</div>

<!-- ════════════════════════════════════════
     BAGIAN 5: SOLUSI OTOMATIS
════════════════════════════════════════ -->
<div class="section">
<h2>5. Ringkasan & Solusi</h2>
<div class="box">
<?php
echo "<table>";
// shell_exec
$se_disabled = in_array('shell_exec', array_map('trim', $disabled));
echo "<tr><td>shell_exec aktif</td><td>" . ($se_disabled ? "<span class='err'>✘ Nonaktif — edit php.ini</span>" : "<span class='ok'>✔</span>") . "</td></tr>";

// python bisa dijalankan
$py_ok = false;
$py_ver_output = @shell_exec("python --version 2>&1");
$py_ok = ($py_ver_output && strpos($py_ver_output, 'Python') === 0);
echo "<tr><td>python bisa dijalankan dari PHP</td><td>" . ($py_ok ? "<span class='ok'>✔ $py_ver_output</span>" : "<span class='err'>✘ Tidak bisa — PATH belum ada di environment PHP</span>") . "</td></tr>";

// tuya_bridge.py
echo "<tr><td>tuya_bridge.py ada</td><td>" . (file_exists($script) ? "<span class='ok'>✔</span>" : "<span class='err'>✘</span>") . "</td></tr>";

// tinytuya
$tt_ok = $check_import && strpos($check_import, 'OK:') === 0;
echo "<tr><td>tinytuya terinstall</td><td>" . ($tt_ok ? "<span class='ok'>✔</span>" : "<span class='err'>✘ Jalankan: python -m pip install tinytuya</span>") . "</td></tr>";
echo "</table>";

if (!$py_ok) {
    echo "<hr style='border-color:#334155;margin:12px 0'>";
    echo "<p class='warn'>⚠ <strong>Penyebab utama 'Tidak Terhubung':</strong> PHP tidak bisa menemukan <code>python</code> di PATH.</p>";
    echo "<p>Solusi pilihan (pilih salah satu):</p>";
    echo "<p><strong>Opsi A — Pakai path absolut Python:</strong><br>";
    $py_abs2 = trim(@shell_exec("where python 2>&1") ?? '');
    $py_abs2 = explode("\n", $py_abs2)[0];
    echo "Ganti baris <code>\$python = ...</code> di <code>tuya_api.php</code> dan <code>process.php</code> menjadi:<br>";
    echo "<pre>\$python = '" . htmlspecialchars(trim($py_abs2) ?: 'C:\\Python312\\python.exe') . "';</pre>";
    echo "<strong>Opsi B — Restart XAMPP setelah Python di-install</strong> (PATH baru tidak terbaca sampai Apache restart)<br>";
    echo "<strong>Opsi C — Tambah Python ke PATH system</strong> (bukan user PATH), lalu restart XAMPP.";
}
?>
</div>
</div>

<p class="info" style="margin-top:20px">⚠ <strong>Hapus file tuya_debug.php setelah selesai!</strong> File ini mengekspos informasi sistem.</p>
</body>
</html>