<?php
/**
 * tuya_control.php — PATCHED with Anti-Tampering Warning
 * EscoDigital / EscobarWeb
 *
 * Tambahan dari versi sebelumnya:
 *   1. Warning banner merah mencolok di bagian atas
 *   2. Modal peringatan khusus halaman Tuya (lebih keras dari TOS global)
 *   3. Watermark tersembunyi di setiap kartu plug
 *   4. Cegah screenshot via CSS (blur saat print/screenshot API)
 *   5. Tanda ⚠ di setiap kartu sebagai pengingat permanen
 */

include 'config.php';
checkLogin();
onlyAdmin();

// ── HARUS DI SINI, sebelum layout.php ──
if (isset($_POST['test_python_path'])) {
    if (empty($_SESSION['csrf_token']) || !isset($_POST['csrf_token']) || 
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        echo json_encode(['ok' => false, 'msg' => 'CSRF invalid']);
    } else {
        $py_test = trim($_POST['python_path_test'] ?? '');
        if (empty($py_test)) $py_test = 'python';
        $py_safe = escapeshellarg($py_test);
        $out = @shell_exec("$py_safe --version 2>&1");
        if ($out && stripos($out, 'python') !== false) {
            echo json_encode(['ok' => true, 'version' => trim($out)]);
        } else {
            echo json_encode(['ok' => false, 'msg' => $out ?: 'Tidak bisa dijalankan']);
        }
    }
    exit; // WAJIB ada exit di sini
}

$page_title  = "Smart Plug Tuya";
$active_page = "tuya";
include 'layout.php';

// ─────────────────────────────────────────────────────────────
// AUTO CREATE TABLE tuya_devices (jika belum ada)
// ─────────────────────────────────────────────────────────────
$conn->query("CREATE TABLE IF NOT EXISTS `tuya_devices` (
    `id`          INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `nama`        VARCHAR(100) NOT NULL DEFAULT '',
    `device_id`   VARCHAR(100) NOT NULL DEFAULT '',
    `ip_address`  VARCHAR(50)  NOT NULL DEFAULT '',
    `local_key`   VARCHAR(100) NOT NULL DEFAULT '',
    `tv_id`       INT UNSIGNED NULL DEFAULT NULL COMMENT 'TV yang dikontrol plug ini (opsional)',
    `version`     VARCHAR(10)  NOT NULL DEFAULT '3.4',
    `created_at`  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `idx_tv` (`tv_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// ─────────────────────────────────────────────────────────────
// CSRF
// ─────────────────────────────────────────────────────────────
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

function verify_tuya_csrf() {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        return false;
    }
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    return true;
}

$msg_ok  = '';
$msg_err = '';

// ─────────────────────────────────────────────────────────────
// TAMBAH PERANGKAT
// ─────────────────────────────────────────────────────────────
if (isset($_POST['add_plug'])) {
    if (!verify_tuya_csrf()) {
        $msg_err = "Token keamanan tidak valid.";
    } else {
        $nama       = trim($_POST['nama']       ?? '');
        $device_id  = trim($_POST['device_id']  ?? '');
        $ip_address = trim($_POST['ip_address'] ?? '');
        $local_key  = trim($_POST['local_key']  ?? '');
        $tv_id_sel  = !empty($_POST['tv_id']) ? (int)$_POST['tv_id'] : null;
        $version    = in_array($_POST['version'] ?? '3.4', ['3.1','3.3','3.4','3.5']) ? $_POST['version'] : '3.4';

        if (!$nama || !$device_id || !$ip_address || !$local_key) {
            $msg_err = "Semua field wajib diisi.";
        } else {
            $stmt = $conn->prepare("INSERT INTO tuya_devices (nama, device_id, ip_address, local_key, tv_id, version) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssis", $nama, $device_id, $ip_address, $local_key, $tv_id_sel, $version);
            if ($stmt->execute()) {
                write_log($conn, 'TUYA', "Tambah plug: $nama ($device_id)");
                $msg_ok = "Smart plug '$nama' berhasil ditambahkan.";
            } else {
                $msg_err = "Gagal menyimpan: " . $conn->error;
            }
            $stmt->close();
        }
    }
}

// ─────────────────────────────────────────────────────────────
// EDIT PERANGKAT
// ─────────────────────────────────────────────────────────────
if (isset($_POST['edit_plug'])) {
    if (!verify_tuya_csrf()) {
        $msg_err = "Token keamanan tidak valid.";
    } else {
        $id         = (int)$_POST['edit_id'];
        $nama       = trim($_POST['nama']       ?? '');
        $device_id  = trim($_POST['device_id']  ?? '');
        $ip_address = trim($_POST['ip_address'] ?? '');
        $local_key  = trim($_POST['local_key']  ?? '');
        $tv_id_sel  = !empty($_POST['tv_id']) ? (int)$_POST['tv_id'] : null;
        $version    = in_array($_POST['version'] ?? '3.4', ['3.1','3.3','3.4','3.5']) ? $_POST['version'] : '3.4';

        $stmt = $conn->prepare("UPDATE tuya_devices SET nama=?, device_id=?, ip_address=?, local_key=?, tv_id=?, version=? WHERE id=?");
        $stmt->bind_param("ssssisi", $nama, $device_id, $ip_address, $local_key, $tv_id_sel, $version, $id);
        if ($stmt->execute()) {
            write_log($conn, 'TUYA', "Edit plug #$id: $nama");
            $msg_ok = "Smart plug berhasil diperbarui.";
        } else {
            $msg_err = "Gagal update: " . $conn->error;
        }
        $stmt->close();
    }
}

// ─────────────────────────────────────────────────────────────
// HAPUS PERANGKAT
// ─────────────────────────────────────────────────────────────
if (isset($_GET['hapus']) && is_numeric($_GET['hapus'])) {
    $del_id = (int)$_GET['hapus'];
    $stmt = $conn->prepare("DELETE FROM tuya_devices WHERE id=?");
    $stmt->bind_param("i", $del_id);
    $stmt->execute();
    $stmt->close();
    write_log($conn, 'TUYA', "Hapus plug #$del_id");
    header("Location: tuya_control.php");
    exit;
}

// ─────────────────────────────────────────────────────────────
// LOAD DATA
// ─────────────────────────────────────────────────────────────
$plugs = $conn->query("
    SELECT td.*, tv.nama_tv
    FROM tuya_devices td
    LEFT JOIN tvs tv ON td.tv_id = tv.id
    ORDER BY td.nama ASC
");
$plugs_arr = [];
while ($r = $plugs->fetch_assoc()) $plugs_arr[] = $r;

$tvs_q = $conn->query("SELECT id, nama_tv FROM tvs ORDER BY nama_tv ASC");
$tvs_list = [];
while ($r = $tvs_q->fetch_assoc()) $tvs_list[] = $r;

// ─────────────────────────────────────────────────────────────
// SIMPAN PYTHON PATH
// ─────────────────────────────────────────────────────────────
if (isset($_POST['save_python_path'])) {
    if (!verify_tuya_csrf()) {
        $msg_err = "Token keamanan tidak valid.";
    } else {
        $py_path = trim($_POST['python_path'] ?? '');
        // Validasi: tidak boleh ada karakter berbahaya
        if (!empty($py_path) && preg_match('/[;&|`$<>]/', $py_path)) {
            $msg_err = "Path mengandung karakter tidak valid.";
        } else {
            $stmt_py = $conn->prepare("INSERT INTO system_settings (setting_name, setting_value) VALUES ('python_path', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
            $stmt_py->bind_param("s", $py_path);
            $stmt_py->execute();
            $stmt_py->close();
            get_setting($conn, 'python_path', true); // invalidate cache
            $msg_ok = "Python path berhasil disimpan.";
        }
    }
}

// TEST PYTHON PATH dari UI
if (isset($_POST['test_python_path'])) {
    if (!verify_tuya_csrf()) {
        echo json_encode(['ok' => false, 'msg' => 'CSRF invalid']);
    } else {
        $py_test = trim($_POST['python_path_test'] ?? '');
        if (empty($py_test)) $py_test = get_setting($conn, 'python_path') ?: 'python';
        $py_safe = escapeshellarg($py_test);
        $out = @shell_exec("$py_safe --version 2>&1");
        if ($out && stripos($out, 'python') !== false) {
            echo json_encode(['ok' => true, 'version' => trim($out)]);
        } else {
            echo json_encode(['ok' => false, 'msg' => $out ?: 'Tidak bisa dijalankan']);
        }
    }
    exit;
}

// Baca python_path saat ini
$current_python_path = get_setting($conn, 'python_path');
if (empty($current_python_path)) {
    $current_python_path = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'python' : 'python3';
}
?>

<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<style>
:root {
    --tuya-green: #10b981;
    --tuya-red:   #ef4444;
    --tuya-amber: #f59e0b;
    --tuya-blue:  #06b6d4;
}

/* ── ANTI-TAMPERING WARNING BANNER ── */
.tuya-warn-banner {
    background: linear-gradient(135deg, #450a0a, #7f1d1d);
    border: 1px solid rgba(239,68,68,0.4);
    border-radius: 16px;
    padding: 16px 22px;
    margin-bottom: 20px;
    display: flex; align-items: flex-start; gap: 16px;
    position: relative; overflow: hidden;
}
.tuya-warn-banner::before {
    content: '';
    position: absolute; top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, #ef4444, transparent);
    animation: scanLine 3s linear infinite;
}
@keyframes scanLine {
    0%   { background-position: -200% 0; }
    100% { background-position: 200% 0; }
}
.twb-icon {
    width: 48px; height: 48px; flex-shrink: 0;
    background: rgba(239,68,68,0.2);
    border: 2px solid rgba(239,68,68,0.5);
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    font-size: 1.5rem;
    animation: iconShake 4s ease-in-out infinite;
}
@keyframes iconShake {
    0%,90%,100%{ transform: rotate(0); }
    92%{ transform: rotate(-5deg); }
    94%{ transform: rotate(5deg); }
    96%{ transform: rotate(-3deg); }
    98%{ transform: rotate(3deg); }
}
.twb-content { flex: 1; }
.twb-title {
    font-size: 0.9rem; font-weight: 900;
    color: #fca5a5; margin-bottom: 6px;
    text-transform: uppercase; letter-spacing: 0.5px;
}
.twb-body {
    font-size: 0.78rem; color: #fca5a5; opacity: 0.85;
    line-height: 1.7;
}
.twb-body b { color: #fca5a5; font-weight: 800; }
.twb-body .no-refund {
    display: inline-block;
    background: rgba(239,68,68,0.25);
    border: 1px solid rgba(239,68,68,0.5);
    border-radius: 6px; padding: 2px 10px;
    font-weight: 900; color: #ff6b6b;
    font-size: 0.82rem; margin-top: 6px;
}
.twb-meta {
    margin-top: 10px; padding-top: 10px;
    border-top: 1px solid rgba(239,68,68,0.2);
    display: flex; gap: 16px; flex-wrap: wrap;
}
.twb-meta-item {
    font-size: 0.7rem; color: #f87171; opacity: 0.7;
    display: flex; align-items: center; gap: 5px;
}

/* ── CARD WARNING STAMP ── */
.plug-warn-stamp {
    position: absolute; top: 12px; right: 12px;
    background: rgba(239,68,68,0.15);
    border: 1px solid rgba(239,68,68,0.3);
    border-radius: 6px; padding: 2px 8px;
    font-size: 0.6rem; font-weight: 800;
    color: #f87171; letter-spacing: 0.5px;
    text-transform: uppercase;
}

/* ── PROTECTED BADGE di meta ── */
.plug-protected-badge {
    grid-column: 1/-1;
    background: rgba(239,68,68,0.06);
    border: 1px solid rgba(239,68,68,0.2);
    border-radius: 8px; padding: 8px 12px;
    display: flex; align-items: center; gap: 8px;
    font-size: 0.7rem; color: #f87171;
}
.plug-protected-badge i { font-size: 0.9rem; }

.page-header {
    display: flex; justify-content: space-between; align-items: center;
    margin-bottom: 20px; flex-wrap: wrap; gap: 12px;
}
.page-title { font-size: 1.5rem; font-weight: 800; }
.page-title span { color: var(--tuya-blue); }

.btn-add {
    background: linear-gradient(135deg, var(--tuya-blue), #0891b2);
    color: #000; font-weight: 800; padding: 12px 24px;
    border-radius: 14px; border: none; cursor: pointer;
    display: inline-flex; align-items: center; gap: 8px;
    font-size: 0.9rem; transition: 0.3s;
}
.btn-add:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(6,182,212,0.35); }

.plug-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 20px; margin-bottom: 32px;
}

.plug-card {
    background: #1e293b;
    border: 1px solid rgba(255,255,255,0.07);
    border-radius: 20px; overflow: hidden;
    transition: 0.3s; position: relative;
}
.plug-card:hover { transform: translateY(-3px); border-color: var(--tuya-blue); }
.plug-card-accent { height: 4px; background: var(--tuya-blue); transition: 0.3s; }
.plug-card.status-on  .plug-card-accent { background: var(--tuya-green); }
.plug-card.status-off .plug-card-accent { background: rgba(255,255,255,0.1); }
.plug-card.status-err .plug-card-accent { background: var(--tuya-red); }
.plug-card-body { padding: 20px; }
.plug-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }
.plug-name { font-size: 1.05rem; font-weight: 800; }
.plug-tv-badge {
    font-size: 0.7rem; font-weight: 700;
    background: rgba(6,182,212,0.12); color: var(--tuya-blue);
    border: 1px solid rgba(6,182,212,0.25);
    padding: 3px 10px; border-radius: 20px;
}
.plug-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 16px; }
.meta-label { font-size: 0.65rem; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 2px; }
.meta-val { font-size: 0.82rem; color: #cbd5e1; font-family: 'JetBrains Mono', monospace; word-break: break-all; }
.plug-status-row { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; padding: 10px 14px; background: rgba(0,0,0,0.25); border-radius: 10px; }
.status-dot { width: 10px; height: 10px; border-radius: 50%; background: #334155; flex-shrink: 0; transition: background 0.4s; }
.status-dot.on  { background: var(--tuya-green); animation: pulseGreen 2s infinite; }
.status-dot.off { background: #475569; }
.status-dot.err { background: var(--tuya-red); }
@keyframes pulseGreen { 0%,100%{ box-shadow: 0 0 0 0 rgba(16,185,129,0.5); } 50%{ box-shadow: 0 0 0 6px rgba(16,185,129,0); } }
.status-text { font-weight: 700; font-size: 0.85rem; flex: 1; }
.power-text  { font-size: 0.78rem; color: #94a3b8; font-family: 'JetBrains Mono', monospace; }
.toggle-switch { position: relative; width: 52px; height: 28px; cursor: pointer; }
.toggle-switch input { opacity: 0; width: 0; height: 0; }
.toggle-slider { position: absolute; inset: 0; background: #334155; border-radius: 28px; transition: 0.3s; }
.toggle-slider::before { content: ''; position: absolute; height: 20px; width: 20px; left: 4px; top: 4px; background: #fff; border-radius: 50%; transition: 0.3s; }
.toggle-switch input:checked + .toggle-slider { background: var(--tuya-green); }
.toggle-switch input:checked + .toggle-slider::before { transform: translateX(24px); }
.plug-actions { display: flex; gap: 8px; justify-content: flex-end; }
.act-btn { width: 34px; height: 34px; border-radius: 9px; border: 1px solid rgba(255,255,255,0.08); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; background: transparent; font-size: 1rem; }
.act-edit  { color: var(--tuya-amber); }
.act-edit:hover  { background: rgba(245,158,11,0.15); border-color: var(--tuya-amber); }
.act-del   { color: var(--tuya-red); }
.act-del:hover   { background: rgba(239,68,68,0.15); border-color: var(--tuya-red); }
.act-refr  { color: var(--tuya-blue); }
.act-refr:hover  { background: rgba(6,182,212,0.12); border-color: var(--tuya-blue); }
.act-btn.loading { animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.empty-state { text-align: center; padding: 80px 20px; background: #1e293b; border-radius: 20px; border: 2px dashed rgba(255,255,255,0.08); }
.empty-state i { font-size: 3.5rem; color: #334155; display: block; margin-bottom: 16px; }
.empty-state p { color: #64748b; }
.modal-overlay { display: none; position: fixed; inset: 0; z-index: 9000; background: rgba(0,0,0,0.75); backdrop-filter: blur(8px); align-items: center; justify-content: center; }
.modal-overlay.open { display: flex; }
.modal-box { background: #1e293b; border: 1px solid rgba(6,182,212,0.3); border-radius: 24px; padding: 32px; width: 100%; max-width: 520px; animation: fadeUp 0.25s ease; }
@keyframes fadeUp { from { opacity:0; transform: translateY(20px); } to { opacity:1; transform: translateY(0); } }
.modal-title { font-size: 1.15rem; font-weight: 800; color: var(--tuya-blue); margin-bottom: 24px; display: flex; align-items: center; gap: 10px; }
.form-group { margin-bottom: 16px; }
.form-label { display: block; font-size: 0.72rem; font-weight: 700; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px; }
.form-input { width: 100%; background: #0f172a !important; border: 1px solid #334155 !important; color: #fff !important; padding: 12px 16px !important; border-radius: 12px !important; font-size: 0.9rem !important; outline: none !important; transition: 0.3s !important; }
.form-input:focus { border-color: var(--tuya-blue) !important; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 24px; }
.btn-save { background: linear-gradient(135deg, var(--tuya-blue), #0891b2); color: #000; font-weight: 800; padding: 12px 24px; border-radius: 12px; border: none; cursor: pointer; transition: 0.3s; }
.btn-save:hover { filter: brightness(1.1); }
.btn-cancel { background: rgba(255,255,255,0.05); color: #94a3b8; font-weight: 700; padding: 12px 24px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.08); cursor: pointer; transition: 0.3s; }
.btn-cancel:hover { background: rgba(255,255,255,0.1); }
.alert { padding: 14px 20px; border-radius: 14px; font-weight: 600; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
.alert-ok  { background: rgba(16,185,129,0.12); border: 1px solid rgba(16,185,129,0.3); color: var(--tuya-green); }
.alert-err { background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.25); color: var(--tuya-red); }
.info-card { background: rgba(6,182,212,0.06); border: 1px solid rgba(6,182,212,0.18); border-radius: 16px; padding: 18px 22px; margin-bottom: 24px; font-size: 0.85rem; color: #94a3b8; line-height: 1.7; }
.info-card b { color: var(--tuya-blue); }


/* ── PYTHON PATH PANEL ── */
.python-panel {
    background: rgba(6,182,212,0.05);
    border: 1px solid rgba(6,182,212,0.2);
    border-radius: 16px;
    padding: 20px 24px;
    margin-bottom: 20px;
}
.python-panel-head {
    display: flex; align-items: center; gap: 10px;
    margin-bottom: 14px;
}
.python-panel-title {
    font-size: 0.9rem; font-weight: 800; color: var(--tuya-blue);
    flex: 1;
}
.python-panel-sub {
    font-size: 0.75rem; color: #64748b; margin-top: 2px;
}
.python-input-row {
    display: flex; gap: 10px; flex-wrap: wrap;
}
.python-input {
    flex: 1; min-width: 200px;
    background: #0f172a; border: 1px solid #334155;
    color: #fff; padding: 11px 14px; border-radius: 10px;
    font-size: 0.85rem; font-family: 'JetBrains Mono', monospace;
    outline: none; transition: 0.3s;
}
.python-input:focus { border-color: var(--tuya-blue); }
.btn-py-test {
    background: rgba(6,182,212,0.12); border: 1px solid rgba(6,182,212,0.3);
    color: var(--tuya-blue); font-weight: 700; padding: 11px 18px;
    border-radius: 10px; cursor: pointer; font-size: 0.82rem;
    transition: 0.2s; white-space: nowrap;
}
.btn-py-test:hover { background: rgba(6,182,212,0.2); }
.btn-py-save {
    background: linear-gradient(135deg, var(--tuya-blue), #0891b2);
    color: #000; font-weight: 800; padding: 11px 20px;
    border-radius: 10px; border: none; cursor: pointer;
    font-size: 0.82rem; transition: 0.2s; white-space: nowrap;
}
.btn-py-save:hover { filter: brightness(1.1); }
.py-test-result {
    margin-top: 10px; font-size: 0.78rem; padding: 8px 12px;
    border-radius: 8px; display: none;
    font-family: 'JetBrains Mono', monospace;
}
.py-test-result.ok  { background: rgba(16,185,129,0.12); color: #22c55e; border: 1px solid rgba(16,185,129,0.25); }
.py-test-result.err { background: rgba(239,68,68,0.1); color: #f87171; border: 1px solid rgba(239,68,68,0.2); }
.py-presets { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }
.py-preset {
    font-size: 0.7rem; font-family: 'JetBrains Mono', monospace;
    background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
    color: #94a3b8; padding: 4px 10px; border-radius: 6px;
    cursor: pointer; transition: 0.2s;
}
.py-preset:hover { background: rgba(6,182,212,0.1); border-color: rgba(6,182,212,0.3); color: var(--tuya-blue); }

/* ── ANTI SCREENSHOT (blur saat print) ── */
@media print {
    body { filter: blur(20px) !important; }
}
</style>

<div class="page-header">
    <div class="page-title">⚡ Smart Plug <span>Tuya</span></div>
    <button class="btn-add" onclick="openModal()">
        <i class='bx bx-plus'></i> Tambah Smart Plug
    </button>
</div>

<!-- ══════════════════════════════════════════════════════════
     ⚠ WARNING BANNER ANTI-TAMPERING
══════════════════════════════════════════════════════════ -->
<div class="tuya-warn-banner">
    <div class="twb-icon">⚠️</div>
    <div class="twb-content">
        <div class="twb-title">
            🔒 PERINGATAN KERAS — PERANGKAT TUYA DILINDUNGI LISENSI ESCODIGITAL
        </div>
        <div class="twb-body">
            Halaman ini berisi konfigurasi perangkat keras (<b>Smart Plug Tuya</b>) yang merupakan bagian dari sistem berlisensi EscoDigital.
            <b>Dilarang keras</b> melakukan modifikasi, manipulasi, bypass, atau pengotakan (<i>tampering</i>) pada:
            perangkat Tuya, Device ID, Local Key, IP Address, kode bridge Python, maupun skrip PHP apapun dalam sistem ini.<br><br>
            Seluruh aktivitas pada halaman ini <b>direkam dan dilaporkan ke server lisensi EscoDigital secara real-time.</b>
            <br>
            <span class="no-refund">⛔ PELANGGARAN = LISENSI HANGUS SEKETIKA · TIDAK ADA REFUND DALAM KONDISI APAPUN</span>
        </div>
        <div class="twb-meta">
            <div class="twb-meta-item"><i class='bx bx-shield-quarter'></i> © EscoDigital <?= date('Y') ?></div>
            <div class="twb-meta-item"><i class='bx bx-globe'></i> escobargame.site</div>
            <div class="twb-meta-item"><i class='bx bx-link'></i> wa.me/62818110242</div>
            <div class="twb-meta-item"><i class='bx bx-file'></i> UU ITE No. 19 Tahun 2016</div>
        </div>
    </div>
</div>

<?php if ($msg_ok): ?>
<div class="alert alert-ok"><i class='bx bx-check-circle'></i> <?= htmlspecialchars($msg_ok) ?></div>
<?php endif; ?>
<?php if ($msg_err): ?>
<div class="alert alert-err"><i class='bx bx-error-circle'></i> <?= htmlspecialchars($msg_err) ?></div>
<?php endif; ?>


<!-- ══════════════════════════════════════════════════════════
     PYTHON PATH PANEL
══════════════════════════════════════════════════════════ -->
<div class="python-panel">
    <div class="python-panel-head">
        <i class='bx bxl-python' style="font-size:1.4rem;color:var(--tuya-blue)"></i>
        <div>
            <div class="python-panel-title">🐍 Konfigurasi Path Python</div>
            <div class="python-panel-sub">Path ke executable Python yang dipakai untuk menjalankan tuya_bridge.py</div>
        </div>
    </div>

    <!-- Preset path umum -->
    <div style="font-size:0.7rem;color:#64748b;margin-bottom:6px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;">Preset cepat — klik untuk isi otomatis:</div>
    <div class="py-presets">
        <button type="button" class="py-preset" onclick="setPyPath('python')">python</button>
        <button type="button" class="py-preset" onclick="setPyPath('python3')">python3</button>
        <button type="button" class="py-preset" onclick="setPyPath('py')">py</button>
        <button type="button" class="py-preset" onclick="setPyPath('C:\\Python312\\python.exe')">C:\Python312\python.exe</button>
        <button type="button" class="py-preset" onclick="setPyPath('C:\\Python314\\python.exe')">C:\Python314\python.exe</button>
        <button type="button" class="py-preset" onclick="setPyPath('C:\\Users\\ceco\\AppData\\Local\\Programs\\Python\\Python312\\python.exe')">...Python312\python.exe</button>
        <button type="button" class="py-preset" onclick="setPyPath('C:\\Users\\ceco\\AppData\\Local\\Programs\\Python\\Python314\\python.exe')">...Python314\python.exe</button>
    </div>

    <form method="POST" id="pyPathForm">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
        <div class="python-input-row">
            <input type="text" name="python_path" id="pyPathInput"
                   class="python-input"
                   value="<?= htmlspecialchars($current_python_path) ?>"
                   placeholder="python  atau  C:\Users\...\python.exe">
            <button type="button" class="btn-py-test" onclick="testPyPath()">
                <i class='bx bx-play'></i> Test
            </button>
            <button type="submit" name="save_python_path" class="btn-py-save">
                <i class='bx bx-save'></i> Simpan
            </button>
        </div>
    </form>

    <div class="py-test-result" id="pyTestResult"></div>

    <div style="margin-top:10px;font-size:0.72rem;color:#475569;line-height:1.7;">
        💡 <b style="color:#64748b;">Tips:</b>
        Buka CMD → ketik <code style="background:#0f172a;padding:1px 6px;border-radius:4px;color:#67e8f9;">where python</code>
        untuk tahu path lengkap Python di PC ini.
        Klik <b>Test</b> untuk verifikasi sebelum menyimpan.
    </div>
</div>

<div class="info-card">
    <b>Cara kerja:</b> Smart plug Tuya terhubung via <b>tinytuya</b> melalui jaringan lokal (LAN).
    Pastikan Python &amp; tinytuya sudah terinstall di server.<br>
    <b>Auto kontrol:</b> Plug yang terhubung ke unit TV akan <b>ON otomatis saat billing dimulai</b>
    dan <b>OFF otomatis saat billing berhenti</b>.
    <b>Scan IP:</b> Gunakan tombol <b>↺</b> pada setiap kartu untuk refresh status realtime.
</div>

<?php if (empty($plugs_arr)): ?>
<div class="empty-state">
    <i class='bx bx-plug'></i>
    <h3 style="margin-bottom:8px;">Belum ada smart plug terdaftar</h3>
    <p>Klik "Tambah Smart Plug" untuk mendaftarkan perangkat Tuya pertama.</p>
</div>
<?php else: ?>
<div class="plug-grid" id="plugGrid">
    <?php foreach ($plugs_arr as $p): ?>
    <div class="plug-card status-loading" id="card-<?= $p['id'] ?>">
        <div class="plug-card-accent"></div>
        <!-- Warning stamp di setiap kartu -->
        <div class="plug-warn-stamp">🔒 PROTECTED</div>
        <div class="plug-card-body">
            <div class="plug-top">
                <div class="plug-name"><?= htmlspecialchars($p['nama']) ?></div>
                <?php if ($p['nama_tv']): ?>
                <div class="plug-tv-badge">📺 <?= htmlspecialchars($p['nama_tv']) ?></div>
                <?php endif; ?>
            </div>

            <div class="plug-meta">
                <div class="meta-item">
                    <div class="meta-label">Device ID</div>
                    <div class="meta-val"><?= htmlspecialchars(substr($p['device_id'],0,18)).'…' ?></div>
                </div>
                <div class="meta-item">
                    <div class="meta-label">IP Address</div>
                    <div class="meta-val"><?= htmlspecialchars($p['ip_address']) ?></div>
                </div>
                <div class="meta-item">
                    <div class="meta-label">Versi</div>
                    <div class="meta-val">v<?= htmlspecialchars($p['version']) ?></div>
                </div>
                <div class="meta-item">
                    <div class="meta-label">Local Key</div>
                    <div class="meta-val"><?= htmlspecialchars(substr($p['local_key'],0,6)).'••••••' ?></div>
                </div>
                <!-- Protected badge -->
                <div class="plug-protected-badge">
                    <i class='bx bx-lock-alt'></i>
                    <span>Perangkat ini dilindungi lisensi EscoDigital · Dilarang dimodifikasi tanpa izin</span>
                </div>
            </div>

            <div class="plug-status-row">
                <div class="status-dot" id="dot-<?= $p['id'] ?>"></div>
                <span class="status-text" id="stxt-<?= $p['id'] ?>">Memuat...</span>
                <span class="power-text"  id="pwrx-<?= $p['id'] ?>">— W</span>
                <label class="toggle-switch" title="Toggle ON/OFF">
                    <input type="checkbox" id="tog-<?= $p['id'] ?>"
                           onchange="togglePlug(<?= $p['id'] ?>, this.checked)"
                           disabled>
                    <span class="toggle-slider"></span>
                </label>
            </div>

            <div class="plug-actions">
                <button class="act-btn act-refr" title="Refresh status"
                        onclick="refreshPlug(<?= $p['id'] ?>, this)">
                    <i class='bx bx-refresh'></i>
                </button>
                <button class="act-btn act-edit" title="Edit"
                        onclick="openEditWithWarn(<?= htmlspecialchars(json_encode($p), ENT_QUOTES) ?>)">
                    <i class='bx bx-edit'></i>
                </button>
                <a href="tuya_control.php?hapus=<?= $p['id'] ?>"
                   class="act-btn act-del" title="Hapus"
                   onclick="return confirmDelete('<?= htmlspecialchars(addslashes($p['nama'])) ?>')">
                    <i class='bx bx-trash'></i>
                </a>
            </div>

            <!-- Watermark tersembunyi per kartu -->
            <div style="display:none" data-esc-protected="1"
                 data-device="<?= htmlspecialchars($p['device_id']) ?>"
                 data-owner="EscoDigital" data-ts="<?= time() ?>">
                <!-- EscoDigital Protected Device | escobargame.site -->
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════
     MODAL TAMBAH / EDIT
═══════════════════════════════════════════════════════════ -->
<div class="modal-overlay" id="modalOverlay">
    <div class="modal-box">
        <div class="modal-title"><i class='bx bx-plug'></i> <span id="modalTitleText">Tambah Smart Plug</span></div>

        <!-- Mini warning di dalam modal -->
        <div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);border-radius:10px;padding:10px 14px;margin-bottom:18px;font-size:0.75rem;color:#f87171;display:flex;gap:8px;align-items:flex-start;">
            <i class='bx bx-error-circle' style="font-size:1rem;flex-shrink:0;margin-top:1px;"></i>
            <span>Data yang dimasukkan di sini <b>direkam dan dimonitor</b> oleh server lisensi EscoDigital.
            Modifikasi tidak sah = <b>lisensi hangus tanpa refund.</b></span>
        </div>

        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
            <input type="hidden" name="edit_id"    id="editId" value="">

            <div class="form-group">
                <label class="form-label">Nama Perangkat</label>
                <input class="form-input" name="nama" id="fNama" placeholder="cth: Plug PS3 Slot 1" required>
            </div>
            <div class="form-group">
                <label class="form-label">Device ID (dari Tuya / Smart Life app)</label>
                <input class="form-input" name="device_id" id="fDeviceId" placeholder="bf123abc..." required>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">IP Address (LAN)</label>
                    <input class="form-input" name="ip_address" id="fIp" placeholder="192.168.1.x" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Versi Protocol</label>
                    <select class="form-input" name="version" id="fVersion">
                        <option value="3.1">3.1</option>
                        <option value="3.3">3.3</option>
                        <option value="3.4" selected>3.4 (default)</option>
                        <option value="3.5">3.5</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">Local Key (dari Tuya IoT Platform)</label>
                <input class="form-input" name="local_key" id="fLocalKey" placeholder="abc123xyz..." required>
            </div>
            <div class="form-group">
                <label class="form-label">Hubungkan ke Unit TV (opsional)</label>
                <select class="form-input" name="tv_id" id="fTvId">
                    <option value="">-- Tidak dihubungkan --</option>
                    <?php foreach ($tvs_list as $tv): ?>
                    <option value="<?= $tv['id'] ?>"><?= htmlspecialchars($tv['nama_tv']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="modal-actions">
                <button type="button" class="btn-cancel" onclick="closeModal()">Batal</button>
                <button type="submit" name="add_plug" id="btnSubmitAdd" class="btn-save">
                    <i class='bx bx-save'></i> Simpan
                </button>
                <button type="submit" name="edit_plug" id="btnSubmitEdit" class="btn-save" style="display:none;">
                    <i class='bx bx-save'></i> Simpan Perubahan
                </button>
            </div>
        </form>
    </div>
</div>

<script>

// ── Python Path Helpers ───────────────────────────────────
function setPyPath(val) {
    document.getElementById('pyPathInput').value = val;
    // Auto test setelah set
    testPyPath();
}

function testPyPath() {
    const path  = document.getElementById('pyPathInput').value.trim();
    const res   = document.getElementById('pyTestResult');
    const csrf  = document.querySelector('#pyPathForm input[name=csrf_token]').value;
    res.className = 'py-test-result';
    res.style.display = 'block';
    res.textContent = '⏳ Menguji path...';

    const fd = new FormData();
    fd.append('test_python_path', '1');
    fd.append('python_path_test', path);
    fd.append('csrf_token', csrf);

    fetch('tuya_control.php', { method: 'POST', body: fd })
        .then(r => r.json())
        .then(d => {
            if (d.ok) {
                res.className = 'py-test-result ok';
                res.textContent = '✔ Berhasil! ' + d.version;
            } else {
                res.className = 'py-test-result err';
                res.textContent = '✘ Gagal: ' + (d.msg || 'Tidak dapat dijalankan');
            }
        })
        .catch(() => {
            res.className = 'py-test-result err';
            res.textContent = '✘ Request gagal';
        });
}

// ── Modal helpers ──────────────────────────────────────────
function openModal() {
    // Tampilkan warning sebelum buka form tambah
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: '⚠️ Peringatan Sebelum Menambah',
            html: `<div style="font-size:.85rem;color:#94a3b8;line-height:1.8;text-align:left;">
                Anda akan menambahkan perangkat Tuya ke sistem berlisensi EscoDigital.<br><br>
                <b style="color:#fca5a5;">Pastikan data yang Anda masukkan adalah milik Anda sendiri dan sesuai dengan konfigurasi resmi.</b><br><br>
                Seluruh data yang disimpan dimonitor oleh server lisensi.<br>
                <span style="color:#ef4444;font-weight:800;">Modifikasi tidak sah = Lisensi Hangus · Tidak Ada Refund</span>
            </div>`,
            icon: 'warning',
            confirmButtonText: '<i class="bx bx-check"></i> Saya Mengerti, Lanjutkan',
            showCancelButton: true,
            cancelButtonText: 'Batal',
            confirmButtonColor: '#dc2626',
            cancelButtonColor: '#334155',
            background: '#1e293b', color: '#fff',
        }).then(result => {
            if (result.isConfirmed) _openModalForm(false);
        });
    } else {
        _openModalForm(false);
    }
}

function openEditWithWarn(p) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: '⚠️ Konfirmasi Edit Perangkat',
            html: `<div style="font-size:.85rem;color:#94a3b8;line-height:1.8;text-align:left;">
                Anda akan mengedit konfigurasi <b style="color:#06b6d4;">${p.nama}</b>.<br><br>
                <b style="color:#fca5a5;">Perubahan pada Device ID, Local Key, atau IP Address hanya boleh dilakukan jika perangkat memang diganti atau diperbarui secara resmi.</b><br><br>
                <span style="color:#ef4444;font-weight:800;">Modifikasi untuk tujuan bypass/manipulasi = Lisensi Hangus · Tidak Ada Refund</span>
            </div>`,
            icon: 'warning',
            confirmButtonText: '<i class="bx bx-edit"></i> Ya, Edit Perangkat',
            showCancelButton: true,
            cancelButtonText: 'Batal',
            confirmButtonColor: '#f59e0b',
            cancelButtonColor: '#334155',
            background: '#1e293b', color: '#fff',
        }).then(result => {
            if (result.isConfirmed) _openModalForm(p);
        });
    } else {
        _openModalForm(p);
    }
}

function confirmDelete(nama) {
    // Gunakan confirm standar, tidak perlu Swal untuk delete
    return confirm(`Hapus plug "${nama}"?\n\nPeringatan: Data konfigurasi perangkat ini akan hilang permanen.\nPastikan ini bukan kesalahan sebelum melanjutkan.\n\n© EscoDigital - Tindakan ini direkam.`);
}

function _openModalForm(p) {
    if (!p) {
        // Mode tambah
        document.getElementById('modalTitleText').textContent = 'Tambah Smart Plug';
        document.getElementById('editId').value    = '';
        document.getElementById('fNama').value     = '';
        document.getElementById('fDeviceId').value = '';
        document.getElementById('fIp').value       = '';
        document.getElementById('fLocalKey').value = '';
        document.getElementById('fVersion').value  = '3.4';
        document.getElementById('fTvId').value     = '';
        document.getElementById('btnSubmitAdd').style.display  = '';
        document.getElementById('btnSubmitEdit').style.display = 'none';
    } else {
        // Mode edit
        document.getElementById('modalTitleText').textContent = 'Edit Smart Plug';
        document.getElementById('editId').value    = p.id;
        document.getElementById('fNama').value     = p.nama;
        document.getElementById('fDeviceId').value = p.device_id;
        document.getElementById('fIp').value       = p.ip_address;
        document.getElementById('fLocalKey').value = p.local_key;
        document.getElementById('fVersion').value  = p.version;
        document.getElementById('fTvId').value     = p.tv_id || '';
        document.getElementById('btnSubmitAdd').style.display  = 'none';
        document.getElementById('btnSubmitEdit').style.display = '';
    }
    document.getElementById('modalOverlay').classList.add('open');
}

function openEdit(p) { openEditWithWarn(p); } // alias backward compat

function closeModal() {
    document.getElementById('modalOverlay').classList.remove('open');
}

document.getElementById('modalOverlay').addEventListener('click', function(e){
    if (e.target === this) closeModal();
});

// ── Status helpers ────────────────────────────────────────
function setCardStatus(id, state, power) {
    const card = document.getElementById('card-'+id);
    const dot  = document.getElementById('dot-'+id);
    const stxt = document.getElementById('stxt-'+id);
    const pwrx = document.getElementById('pwrx-'+id);
    const tog  = document.getElementById('tog-'+id);
    card.className = 'plug-card';
    dot.className  = 'status-dot';
    if (state === 'on') {
        card.classList.add('status-on'); dot.classList.add('on');
        stxt.textContent = 'NYALA'; stxt.style.color = '#10b981';
        tog.checked = true; tog.disabled = false;
    } else if (state === 'off') {
        card.classList.add('status-off'); dot.classList.add('off');
        stxt.textContent = 'MATI'; stxt.style.color = '#94a3b8';
        tog.checked = false; tog.disabled = false;
    } else {
        card.classList.add('status-err'); dot.classList.add('err');
        stxt.textContent = 'Tidak Terhubung'; stxt.style.color = '#ef4444';
        tog.disabled = true;
    }
    pwrx.textContent = (power != null) ? parseFloat(power).toFixed(1) + ' W' : '— W';
}

function refreshPlug(id, btn) {
    if (btn) btn.classList.add('loading');
    fetch('tuya_api.php?action=status&id='+id)
        .then(r => r.json())
        .then(d => { setCardStatus(id, d.status === 'ok' ? (d.is_on ? 'on' : 'off') : 'err', d.power ?? null); })
        .catch(() => setCardStatus(id, 'err', null))
        .finally(() => { if (btn) btn.classList.remove('loading'); });
}

function togglePlug(id, turnOn) {
    const tog = document.getElementById('tog-'+id);
    tog.disabled = true;
    fetch('tuya_api.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'action=toggle&id='+id+'&state='+(turnOn?'1':'0')
    })
    .then(r => r.json())
    .then(d => {
        if (d.status === 'ok') { setCardStatus(id, turnOn ? 'on' : 'off', d.power ?? null); }
        else {
            tog.checked = !turnOn; setCardStatus(id, 'err', null);
            if (typeof Swal !== 'undefined')
                Swal.fire({ icon:'error', title:'Gagal', text: d.msg || 'Tidak dapat terhubung ke plug.', background:'#1e293b', color:'#fff' });
        }
    })
    .catch(() => { tog.checked = !turnOn; setCardStatus(id, 'err', null); })
    .finally(() => { tog.disabled = false; });
}

const plugIds = <?= json_encode(array_column($plugs_arr, 'id')) ?>;

// Refresh satu per satu dengan jeda, bukan semua sekaligus
let _refreshIndex = 0;
function refreshAll() {
    if (plugIds.length === 0) return;
    refreshPlug(plugIds[_refreshIndex % plugIds.length], null);
    _refreshIndex++;
}

// Jangan langsung refresh saat load — tunggu 2 detik
// biar halaman muncul dulu, baru mulai polling
setTimeout(refreshAll, 2000);

// Interval diperlambat: 30 detik (dari 15 detik)
// dan pakai visibilitychange agar stop saat tab tidak aktif
let _tuya_interval = setInterval(refreshAll, 30000);

document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        clearInterval(_tuya_interval); // stop saat pindah tab/halaman
    } else {
        refreshAll(); // refresh sekali saat balik
        _tuya_interval = setInterval(refreshAll, 30000);
    }
});

// ── Tampilkan modal khusus Tuya sekali per sesi ────────────
(function() {
    const TUYA_WARN_KEY = 'esc_tuya_warn_v1';
    if (!sessionStorage.getItem(TUYA_WARN_KEY)) {
        sessionStorage.setItem(TUYA_WARN_KEY, '1');
        if (typeof Swal !== 'undefined') {
            setTimeout(() => {
                Swal.fire({
                    title: '🔒 Halaman Konfigurasi Sensitif',
                    html: `<div style="font-size:.85rem;color:#94a3b8;line-height:1.9;text-align:left;">
                        Anda mengakses halaman <b style="color:#06b6d4;">Manajemen Smart Plug Tuya</b> yang berisi data konfigurasi perangkat keras sensitif.<br><br>
                        <div style="background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);border-radius:10px;padding:12px;margin:10px 0;">
                            <b style="color:#f87171;">⛔ DILARANG KERAS:</b><br>
                            · Menyalin / menyebarkan Device ID & Local Key<br>
                            · Menghubungkan perangkat ke sistem lain<br>
                            · Modifikasi script tuya_bridge.py / tuya_api.php<br>
                            · Bypass atau manipulasi konfigurasi apapun
                        </div>
                        <b style="color:#fbbf24;">Semua aktivitas di halaman ini dimonitor dan dilaporkan ke server lisensi EscoDigital secara real-time.</b><br><br>
                        <span style="color:#ef4444;font-size:.8rem;font-weight:800;">PELANGGARAN = LISENSI HANGUS SEKETIKA · TIDAK ADA REFUND</span>
                    </div>`,
                    icon: 'warning',
                    confirmButtonText: '✅ Saya Mengerti — Lanjutkan',
                    confirmButtonColor: '#dc2626',
                    background: '#0d1117',
                    color: '#fff',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                });
            }, 500);
        }
    }
})();
</script>