<?php

function getWifiInterfaceName() {
    $raw = shell_exec('netsh interface show interface');

    $lines = explode("\n", $raw);
    foreach ($lines as $line) {

        // cari interface "Dedicated" (biasanya WiFi)
        if (stripos($line, "Dedicated") !== false) {

            // ambil nama paling kanan
            $parts = preg_split('/\s{2,}/', trim($line));

            if (isset($parts[3])) {
                $name = trim($parts[3]);

                // filter kemungkinan WiFi
                if (
                    stripos($name, "wi-fi") !== false ||
                    stripos($name, "wireless") !== false ||
                    stripos($name, "wlan") !== false
                ) {
                    return $name;
                }
            }
        }
    }

    return null;
}

// ==============================================
//  API MODE (AJAX)
// ==============================================
if (isset($_GET['action'])) {

    // --- STATUS WIFI ---
    if ($_GET['action'] == "status") {

        //$raw1 = shell_exec('netsh interface show interface "Wi-Fi"');
		$wifiName = getWifiInterfaceName();
		$raw1 = shell_exec('netsh interface show interface "' . $wifiName . '"');
        $enabled = (strpos($raw1, "Enabled") !== false);

        $raw2 = shell_exec('netsh wlan show interfaces');

        if (strpos($raw2, "State") !== false) {
            preg_match('/State\s*:\s*(.*)/i', $raw2, $state_match);
            $state = trim($state_match[1]);

            if ($state === "connected") {
                preg_match('/SSID\s*:\s*(.*)/i', $raw2, $ssid_match);
                $ssid = trim($ssid_match[1]);
            } else {
                $ssid = "Tidak terhubung";
            }
        } else {
            $state = "disconnected";
            $ssid = "Tidak terhubung";
        }

        echo json_encode(array(
			"enabled" => $enabled,
			"state"   => $state,
			"ssid"    => $ssid
		));
        exit;
    }

    // --- TOGGLE WIFI ---
    if ($_GET['action'] == "toggle") {

        $wifi = isset($_POST['wifi']) ? $_POST['wifi'] : "";
		
		$wifiName = getWifiInterfaceName();
        if ($wifi == "on") {
			if ($wifiName) {
				shell_exec('netsh interface set interface name="' . $wifiName . '" admin=enabled');
			}
            //shell_exec('netsh interface set interface name="Wi-Fi" admin=enabled');
        } else {
			if ($wifiName) {
				shell_exec('netsh interface set interface name="' . $wifiName . '" admin=disabled');
			}
            //shell_exec('netsh interface set interface name="Wi-Fi" admin=disabled');
        }

        echo "OK";
        exit;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update BRIVISION / SukuBunga + WiFi Control</title>

<link href="css/tombol.css" rel="stylesheet" type="text/css">

<style>
body {
    font-family: Arial;
    text-align: center;
    background: #fff;
    padding: 20px;
}

.btn {
    padding: 12px 25px;
    margin: 5px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    color: #fff;
    font-size: 36px;
}

.enable { background: #3D63AC; }
.disable { background: orange; }

.menu-box {
    margin-bottom: 20px;
}

.status {
    margin-top: 10px;
    font-size: 34px;
}
</style>
</head>

<body>

<h2 style="color:#093977;" class="status">Silahkan Pilih Yang Ingin Anda Update</h2>

<!-- ================= MENU ================= -->
<div class="menu-box">

    <a href="pilih.php?kat=updatevideo">
        <button class="btn enable" style="width:50%;height:100px;">Update BRIVISION</button>
    </a>

    <br>

    <a href="pilih.php?kat=updatesimpanan">
        <button class="btn enable" style="width:50%; height:100px;">Update Suku Bunga</button>
    </a>

    <br>

    <a href="pilih.php?kat=">
        <button class="btn disable" style="width:50%;">Kembali</button>
    </a>
</div>

<hr>

<!-- ================= WIFI CONTROL (SCRIPT 2) ================= -->

<h3 class="status">WiFi Control Panel</h3>

<label class="status">
    <input type="checkbox" id="wifiToggle"> Wi-Fi
</label>

<div class="status">
    <div id="wifiStatus">Status: --</div>
    <div id="ssidStatus">SSID: --</div>
</div>

<!-- tombol tambahan dari script 1
<br><br>
<button onclick="sendCommand('enable')" class="btn enable">Enable Wi-Fi</button>
<button onclick="sendCommand('disable')" class="btn disable">Disable Wi-Fi</button>

<br>
<div id="output">...</div>
-->
<script>

// ================= AJAX SCRIPT 1 (ENABLE/DISABLE simple) =================
function sendCommand(action) {
    document.getElementById("output").innerHTML = "Processing...";

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "action.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onload = function () {
        document.getElementById("output").innerHTML = this.responseText;
    };

    xhr.send("action=" + action);
}

// ================= WIFI STATUS (SCRIPT 2) =================
function updateStatus() {
    fetch('?action=status')
        .then(r => r.json())
        .then(d => {
            document.getElementById('wifiToggle').checked = d.enabled;

            let connectionState = (d.state === "connected")
                ? "Connected"
                : "Disconnected";

            document.getElementById('wifiStatus').innerHTML =
                "Status: " + (d.enabled ? "Enabled" : "Disabled") +
                " / " + connectionState;

            document.getElementById('ssidStatus').innerHTML =
                "SSID: " + d.ssid;
        });
}

updateStatus();
setInterval(updateStatus, 2000);

// ================= TOGGLE WIFI =================
document.getElementById('wifiToggle').addEventListener('change', function () {
    let status = this.checked ? "on" : "off";

    fetch("?action=toggle", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: "wifi=" + status
    });
});

</script>

</body>
</html>