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

function parseWifiList($input) {
    $lines = explode("\n", trim($input));
    $networks = [];
    
    // Skip the header line
    for ($i = 1; $i < count($lines); $i++) {
        $line = trim($lines[$i]);
        if (empty($line)) continue;
        
        // Use regex to parse each line
        if (preg_match('/^\s*(\*?)\s*([0-9A-F:]{17})\s+([^\s].{0,32}?)\s+Infra\s+(\d+)\s+(\d+)\s+Mbit\/s\s+(\d+)\s+((?:\*{1,4})|(?:▂(?:▄)?(?:▆)?(?:█)?_*))\s+(.*)$/', $line, $matches)) {

            $ssid = trim($matches[3]);
            // Don't skip hidden networks (--) anymore
            if ($ssid === "--") continue;
            
            $strength = intval($matches[6]); // Signal strength as number
            $security = trim($matches[8]); // Security information
            
            // Calculate the channel type (2.4GHz or 5GHz)
            $channel = intval($matches[4]);
            $frequency = ($channel > 14) ? "5 GHz" : "2.4 GHz";
            
            $networks[] = [
                "ssid" => $ssid,
                "bssid" => $matches[2],
                "strength" => $strength,
                "secured" => !empty($security) && $security !== "--",
                "security" => $security,
                "channel" => $channel,
                "frequency" => $frequency,
                "rate" => $matches[5] . " Mbit/s",
                "bars" => strlen($matches[7]) // Number of bars (*) in the signal indicator
            ];
        }
    }
    
    // Sort networks by signal strength (highest first)
    usort($networks, function($a, $b) {
        return $b['strength'] - $a['strength'];
    });
    
    return $networks;
}


if(!(isset($apppath))){$apppath = "/home/relayup/";}
$readname = $apppath . 'dev/wifi_scan_wlan0.lst';

if (file_exists($readname)) { } else {$readname = $apppath . 'dev/wifi_scan_wlan1.lst';}
$savedcontent = file_get_contents($readname);

$networksA = parseWifiList($savedcontent);

if(!(isset($apppath))){$apppath = "/home/relayup/";}
$readname = $apppath . 'dev/wifi_scan_wlan1.lst';

if (file_exists($readname)) { } else {$readname = $apppath . 'dev/wifi_scan_wlan1.lst';}
$savedcontent = file_get_contents($readname);

$networksB = parseWifiList($savedcontent);
?>