<?php
$type=$_GET['type'];

if ($type == "update_config") {

    echo "updating....";
}

if ($type == "RTC_time") {
    $time = shell_exec("date '+%d/%m/%Y %H:%M:%S'");
    echo $time;
}

if ($type == "git_pull") {
    $command = 'sudo git pull';
    $output = shell_exec($command);
    echo $output;
}

if ($type == "sshTunnel") {
    $ssh_port=$_GET['ssh_port'];
    $command = 'sudo ssh -i /var/www/.ssh/id_rsa -f -N -R "'.$ssh_port.':localhost:22" -p 50221 -o StrictHostKeyChecking=no "airlab_server1@aircarto.fr"';
    $output = shell_exec($command);
    echo $output;
}

if ($type == "reboot") {
    $command = 'sudo reboot';
    $output = shell_exec($command);
}

if ($type == "npm") {
    $port=$_GET['port'];

    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/npm.py ' . $port;
    $output = shell_exec($command);
    echo $output;
}

if ($type == "noise") {
    $command = '/var/www/nebuleair_pro_4g/sound_meter/sound_meter';
    $output = shell_exec($command);
    echo $output;
}

if ($type == "BME280") {
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/BME280/read.py';
    $output = shell_exec($command);
    echo $output;
}

# SARA R4 COMMANDS
if ($type == "sara") {
    $port=$_GET['port'];
    $sara_command=$_GET['command'];
    $sara_command = escapeshellcmd($sara_command);
    $timeout=$_GET['timeout'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara.py ' . $port . ' ' . $sara_command . ' ' . $timeout;
    $output = shell_exec($command);
    echo $output;
}

# SARA R4 COMMANDS (MQTT)
if ($type == "sara_getMQTT_config") {
    $port=$_GET['port'];
    $timeout=$_GET['timeout'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/MQTT/get_config.py ' . $port .  ' ' . $timeout;
    $output = shell_exec($command);
    echo $output;
}

# SARA R4 COMMANDS (MQTT)
if ($type == "sara_getMQTT_login_logout") {
    $port=$_GET['port'];
    $timeout=$_GET['timeout'];
    $login_logout=$_GET['login_logout'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/MQTT/login_logout.py ' . $port .  ' ' . $login_logout .  ' ' . $timeout;
    $output = shell_exec($command);
    echo $output;
}

# SARA R4 COMMANDS (MQTT -> publish)
if ($type == "sara_MQTT_publish") {
    $port=$_GET['port'];
    $timeout=$_GET['timeout'];
    $message=$_GET['message'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/MQTT/publish.py ' . $port .  ' ' . $message .  ' ' . $timeout;
    $output = shell_exec($command);
    echo $output;
}

#Connect to network

if ($type == "sara_connectNetwork") {
    $port=$_GET['port'];
    $timeout=$_GET['timeout'];
    $networkID=$_GET['networkID'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_connectNetwork.py ' . $port . ' ' . $networkID . ' ' . $timeout;
    $output = shell_exec($command);
    echo $output;
}

#SET THE URL for messaging
if ($type == "sara_setURL") {
    $port=$_GET['port'];
    $url=$_GET['url'];
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_setURL.py ' . $port . ' ' . $url;
    $output = shell_exec($command);
    echo $output;
}

#TO WRITE MESSAGE TO MEMORY
if ($type == "sara_writeMessage") {
    $port=$_GET['port'];
    $message=$_GET['message'];
    $message = escapeshellcmd($message);
    $type2=$_GET['type2'];

    if ($type2 === "write") {
        $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_writeMessage.py ' . $port . ' ' . $message;
        $output = shell_exec($command);
    }
    if ($type2 === "read") {
        $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_readMessage.py ' . $port . ' ' . $message;
        $output = shell_exec($command);
    }
    if ($type2 === "erase") {
        $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_eraseMessage.py ' . $port . ' ' . $message;
        $output = shell_exec($command);
    }
    
    echo $output;
}

#Send the typed message to server (for ntfy notification)
if ($type == "sara_sendMessage") {
    $port=$_GET['port'];
    $endpoint=$_GET['endpoint'];
    $endpoint = escapeshellcmd($endpoint);
    $command = '/usr/bin/python3 /var/www/nebuleair_pro_4g/SARA/sara_sendMessage.py ' . $port . ' ' . $endpoint;
    $output = shell_exec($command);
    echo $output;
}

if ($type == "internet") {
    //eth0
    $command = 'nmcli -g GENERAL.STATE device show eth0';
    $eth0_connStatus = shell_exec($command);
    $eth0_connStatus = str_replace("\n", "", $eth0_connStatus);
    $command = 'nmcli -g IP4.ADDRESS device show eth0';
    $eth0_IPAddr = shell_exec($command);
    $eth0_IPAddr = str_replace("\n", "", $eth0_IPAddr);

    //wlan0
    $command = 'nmcli -g GENERAL.STATE device show wlan0';
    $wlan0_connStatus = shell_exec($command);
    $wlan0_connStatus = str_replace("\n", "", $wlan0_connStatus);
    $command = 'nmcli -g IP4.ADDRESS device show wlan0';
    $wlan0_IPAddr = shell_exec($command);
    $wlan0_IPAddr = str_replace("\n", "", $wlan0_IPAddr);

    $data= array(
        "ethernet" => array(
            "connection" => $eth0_connStatus,
            "IP" => $eth0_IPAddr
        ),
        "wifi" => array(
            "connection" => $wlan0_connStatus,
            "IP" => $wlan0_IPAddr
        )
        );
    $json_data = json_encode($data);

    echo $json_data;
}

# IMPORTANT
# c'est ici que la connexion vers le WIFI du client s'effectue.
if ($type == "wifi_connect") {
    $SSID=$_GET['SSID'];
    $PASS=$_GET['pass'];

    echo "will try to connect to </br>";
    echo "SSID: " . $SSID;
    echo "</br>";
    echo "Password: " . $PASS;
    echo "</br>";
    echo "</br>";

    echo "You will be disconnected. If connection is successfull you can find the device on your local network.";
    
    $script_path = __DIR__ . '/connexion.sh';
    $log_file = __DIR__ . '/logs/app.log';
    shell_exec("$script_path $SSID $PASS >> $log_file 2>&1 &");

    #$output = shell_exec('sudo nmcli connection down Hotspot');
    #$output2 = shell_exec('sudo nmcli device wifi connect "AirLab" password "123plouf"');

}


if ($type == "wifi_scan") {

    // Set the path to your CSV file
    $csvFile = '/var/www/nebuleair_pro_4g/wifi_list.csv';
    
    // Initialize an array to hold the JSON data
    $jsonData = [];
    
    // Open the CSV file for reading
    if (($handle = fopen($csvFile, 'r')) !== false) {
        // Get the headers from the first row
        $headers = fgetcsv($handle);
        
        // Loop through the rest of the rows
        while (($row = fgetcsv($handle)) !== false) {
            // Combine headers with row data to create an associative array
            $jsonData[] = array_combine($headers, $row);
        }
        
        // Close the file handle
        fclose($handle);
    }
    
    // Set the content type to JSON
    header('Content-Type: application/json');
    
    // Convert the array to JSON format and output it
    echo json_encode($jsonData, JSON_PRETTY_PRINT);
    

}

if ($type == "wifi_scan_old") {

    $output = shell_exec('nmcli device wifi list ifname wlan0');
    // Split the output into lines
    $lines = explode("\n", trim($output));
    
    // Initialize an array to hold the results
    $wifiNetworks = [];
    
    // Loop through each line and extract the relevant information
    foreach ($lines as $index => $line) {
        // Skip the header line
        if ($index === 0) {
            continue;
        }
    
        // Split the line by whitespace and filter empty values
        $columns = preg_split('/\s+/', $line);
        
        // If the line has enough columns, store the relevant data
        if (count($columns) >= 5) {
            $wifiNetworks[] = [
                'SSID' => $columns[2], // Network name
                'BARS' => $columns[8],
                'SIGNAL' => $columns[7], // Signal strength
                
            ];
        }
    }
    $json_data = json_encode($wifiNetworks);

    echo $json_data;

}