<?php
/**
 * tuya_api.php — PATCHED
 * Perubahan:
 *   1. Tambah action 'tv_plug_status' → cek status semua plug milik 1 TV
 *   2. Tambah action 'tv_plug_toggle' → toggle semua plug milik 1 TV (ON/OFF)
 *   3. billing_start / billing_stop sekarang SINKRON (tidak async)
 *      agar caller bisa tahu apakah plug berhasil dikontrol
 */

ob_start();
error_reporting(0);
@ini_set('display_errors', '0');

include 'config.php';
checkLogin();

header('Content-Type: application/json');

function tuya_json_exit(array $data): void {
    if (ob_get_length()) ob_clean();
    echo json_encode($data);
    exit;
}

function get_plug(mysqli $conn, int $id): ?array {
    $s = $conn->prepare("SELECT * FROM tuya_devices WHERE id = ? LIMIT 1");
    $s->bind_param("i", $id);
    $s->execute();
    $r = $s->get_result()->fetch_assoc();
    $s->close();
    return $r ?: null;
}

function get_python_cmd(mysqli $conn): string {
    $s = $conn->prepare("SELECT setting_value FROM system_settings WHERE setting_name = 'python_path' LIMIT 1");
    if ($s) {
        $s->execute();
        $r = $s->get_result()->fetch_assoc();
        $s->close();
        $saved = trim($r['setting_value'] ?? '');
        if (!empty($saved)) return $saved;
    }
    return (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'python' : 'python3';
}

function run_tuya(array $plug, string $action): array {
    global $conn;
    $python = get_python_cmd($conn);
    $script = __DIR__ . DIRECTORY_SEPARATOR . 'tuya_bridge.py';

    if (!file_exists($script)) {
        return ['ok' => false, 'msg' => "tuya_bridge.py tidak ditemukan."];
    }

    $device_id = escapeshellarg($plug['device_id']);
    $ip        = escapeshellarg($plug['ip_address']);
    $key       = escapeshellarg($plug['local_key']);
    $version   = escapeshellarg($plug['version']);
    $act       = escapeshellarg($action);

    $cmd    = "$python " . escapeshellarg($script) . " $device_id $ip $key $version $act 2>&1";
    $output = @shell_exec($cmd);

    if ($output === null || $output === false) {
        return ['ok' => false, 'msg' => "Tidak bisa menjalankan Python."];
    }

    $decoded = @json_decode(trim($output), true);
    if (!is_array($decoded)) {
        return ['ok' => false, 'msg' => "Output tidak valid: " . substr($output, 0, 200)];
    }

    return $decoded;
}

/**
 * Ambil semua plug milik satu TV
 */
function get_plugs_by_tv(mysqli $conn, int $tv_id): array {
    // Cek tabel dulu
    $chk = $conn->query("SHOW TABLES LIKE 'tuya_devices'");
    if (!$chk || $chk->num_rows === 0) return [];

    $s = $conn->prepare("SELECT * FROM tuya_devices WHERE tv_id = ?");
    $s->bind_param("i", $tv_id);
    $s->execute();
    $res = $s->get_result();
    $plugs = [];
    while ($r = $res->fetch_assoc()) $plugs[] = $r;
    $s->close();
    return $plugs;
}

$action = $_REQUEST['action'] ?? '';
$id     = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
$tv_id  = isset($_REQUEST['tv_id']) ? (int)$_REQUEST['tv_id'] : 0;

switch ($action) {

    // ─────────────────────────────────────
    // CEK STATUS SATU PLUG
    // ─────────────────────────────────────
    case 'status': {
        if (!$id) tuya_json_exit(['status'=>'error','msg'=>'id kosong']);
        $plug = get_plug($conn, $id);
        if (!$plug) tuya_json_exit(['status'=>'error','msg'=>'Plug tidak ditemukan']);
        $res = run_tuya($plug, 'status');
        if (!($res['ok'] ?? false)) {
            tuya_json_exit(['status'=>'error','msg'=>$res['msg'] ?? 'Gagal']);
        }
        tuya_json_exit(['status'=>'ok','is_on'=>(bool)($res['is_on']??false),'power'=>$res['power']??null]);
    }

    // ─────────────────────────────────────
    // TOGGLE SATU PLUG (manual dari tuya_control.php)
    // ─────────────────────────────────────
    case 'toggle': {
        if (!$id) tuya_json_exit(['status'=>'error','msg'=>'id kosong']);
        $plug  = get_plug($conn, $id);
        if (!$plug) tuya_json_exit(['status'=>'error','msg'=>'Plug tidak ditemukan']);
        $state = (($_POST['state'] ?? '0') === '1') ? 'on' : 'off';
        $res   = run_tuya($plug, $state);
        if (!($res['ok'] ?? false)) {
            tuya_json_exit(['status'=>'error','msg'=>$res['msg'] ?? 'Gagal toggle']);
        }
        write_log($conn, 'TUYA', "Manual toggle plug '{$plug['nama']}' -> " . strtoupper($state));
        tuya_json_exit(['status'=>'ok','is_on'=>($state==='on'),'power'=>$res['power']??null]);
    }

    // ─────────────────────────────────────
    // [BARU] CEK STATUS SEMUA PLUG MILIK 1 TV
    // Dipanggil dari index.php untuk refresh badge
    // ─────────────────────────────────────
    case 'tv_plug_status': {
        if (!$tv_id) tuya_json_exit(['status'=>'error','msg'=>'tv_id kosong']);
        $plugs = get_plugs_by_tv($conn, $tv_id);
        if (empty($plugs)) tuya_json_exit(['status'=>'ok','is_on'=>false,'plug_count'=>0,'msg'=>'Tidak ada plug']);

        // Ambil status plug pertama saja (representatif)
        $res = run_tuya($plugs[0], 'status');
        if (!($res['ok'] ?? false)) {
            tuya_json_exit(['status'=>'error','msg'=>$res['msg']??'Gagal cek status','is_on'=>false]);
        }
        tuya_json_exit([
            'status'     => 'ok',
            'is_on'      => (bool)($res['is_on'] ?? false),
            'power'      => $res['power'] ?? null,
            'plug_count' => count($plugs),
        ]);
    }

    // ─────────────────────────────────────
    // [BARU] TOGGLE SEMUA PLUG MILIK 1 TV
    // Dipanggil dari index.php (tombol ON/OFF langsung)
    // ─────────────────────────────────────
    case 'tv_plug_toggle': {
        if (!$tv_id) tuya_json_exit(['status'=>'error','msg'=>'tv_id kosong']);
        $plugs = get_plugs_by_tv($conn, $tv_id);
        if (empty($plugs)) tuya_json_exit(['status'=>'ok','msg'=>'Tidak ada plug terdaftar','plug_count'=>0]);

        $want_on = (($_POST['state'] ?? $_GET['state'] ?? '0') === '1');
        $state   = $want_on ? 'on' : 'off';

        $ok_count  = 0;
        $err_count = 0;
        $last_power = null;

        foreach ($plugs as $plug) {
            $res = run_tuya($plug, $state);
            if ($res['ok'] ?? false) {
                $ok_count++;
                $last_power = $res['power'] ?? null;
                write_log($conn, 'TUYA', "TV#{$tv_id} toggle plug '{$plug['nama']}' -> " . strtoupper($state));
            } else {
                $err_count++;
            }
        }

        tuya_json_exit([
            'status'    => $ok_count > 0 ? 'ok' : 'error',
            'is_on'     => $want_on,
            'ok_count'  => $ok_count,
            'err_count' => $err_count,
            'power'     => $last_power,
            'msg'       => $err_count > 0 ? "{$err_count} plug gagal" : null,
        ]);
    }

    // ─────────────────────────────────────
    // BILLING START — sinkron, return hasil
    // ─────────────────────────────────────
    case 'billing_start': {
        if (!$tv_id) tuya_json_exit(['status'=>'ok','msg'=>'no tv_id']);
        $plugs = get_plugs_by_tv($conn, $tv_id);
        $turned_on = 0;
        foreach ($plugs as $plug) {
            $res = run_tuya($plug, 'on');
            if ($res['ok'] ?? false) {
                $turned_on++;
                write_log($conn, 'TUYA', "Auto ON '{$plug['nama']}' — billing start TV #{$tv_id}");
            }
        }
        tuya_json_exit(['status'=>'ok','turned_on'=>$turned_on,'total'=>count($plugs)]);
    }

    // ─────────────────────────────────────
    // BILLING STOP — sinkron, return hasil
    // ─────────────────────────────────────
    case 'billing_stop': {
        if (!$tv_id) tuya_json_exit(['status'=>'ok','msg'=>'no tv_id']);
        $plugs = get_plugs_by_tv($conn, $tv_id);
        $turned_off = 0;
        foreach ($plugs as $plug) {
            $res = run_tuya($plug, 'off');
            if ($res['ok'] ?? false) {
                $turned_off++;
                write_log($conn, 'TUYA', "Auto OFF '{$plug['nama']}' — billing stop TV #{$tv_id}");
            }
        }
        tuya_json_exit(['status'=>'ok','turned_off'=>$turned_off,'total'=>count($plugs)]);
    }

    case 'tv_on':
    case 'tv_off': {
        if ($tv_id) {
            $plugs = get_plugs_by_tv($conn, $tv_id);
            $state = ($action === 'tv_on') ? 'on' : 'off';
            foreach ($plugs as $plug) run_tuya($plug, $state);
        }
        tuya_json_exit(['status'=>'ok']);
    }

    default:
        tuya_json_exit(['status'=>'error','msg'=>'Action tidak dikenal']);
}