<?php
	include_once('includes/db_connect.php');
	include_once('includes/global_functions.php');
    $radioid = $_GET['radioid'];
    $radiomac = $_GET['radiomac'];
        
    if($radioid == "" && $radiomac == ""){
        print(json_encode([error => "Not a valid radioid"]));
        die();
    }else{
        if($radiomac != ""){
            $radiomac = str_replace(':', '', $radiomac);
            $radioid = substr($radiomac, 6 , 11);
        }
        
        $array = array();
        $delete = "DELETE FROM `CommandQue` WHERE idCommand IN (";
       	if($stmt = $mysqli -> prepare("SELECT idCommand, command, value FROM CommandQue LEFT JOIN users ON CommandQue.uid = users.uid WHERE users.radiotoken = ? LIMIT 5")){
        	$stmt -> bind_param("s", $radioid);
        	$stmt -> execute();
        	$stmt -> bind_result($idcommand, $command, $value);
        	while($result = $stmt -> fetch()){
        	    $delete = $delete.$idcommand.",";
        	    if($command == "startstream"){
            		$streamsplit = parse_url($value);
            		$streamip = gethostbyname($streamsplit["host"]);
            		$streamurl = $streamsplit["path"];
            		$streamport = $streamsplit["port"];
            		if($streamport == ""){
            		    $streamport = 80;
            		}
            		  array_push($array, array(   command => $command, 
	                                value => array(streamip => $streamip, streamurl => $streamurl, streamport => $streamport), 
	                               )
	                       );
        	    }else{
	                	    array_push($array, array(   command => $command, 
	                                value => $value, 
	                               ) 
	               );
        	    }
        	 };
        	$stmt -> close();
        }
        $delete = rtrim($delete, ",");
        $delete = $delete.");";
       	if($stmt = $mysqli -> prepare($delete)){
        	$stmt -> execute();
           	$stmt -> close();
        }
        print(json_encode($array, JSON_UNESCAPED_SLASHES));
    }
    
    