<?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);
        }
        $currentStream = null;
        if($stmt = $mysqli -> prepare("SELECT username FROM Twitch LEFT JOIN users ON Twitch.uid = users.uid WHERE users.radiotoken = ?")){
            $stmt -> bind_param("s", $radioid);
         	$stmt -> execute();
         	$stmt -> bind_result($TwitchUsername);
        	$stmt -> fetch();
         	$stmt -> close();
         	
         	$ch = curl_init(); 
            curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/kraken/users/".$TwitchUsername."/follows/channels"); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
            $jsonreturn = json_decode(curl_exec($ch), true);
            for($x = 0; $x < count($jsonreturn["follows"]); $x++)
            {
                $channel = $jsonreturn["follows"][$x]["channel"]["display_name"];
                curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/kraken/streams/".$channel); 
                $stream = json_decode(curl_exec($ch), true);
                if($stream["stream"] != null)
                {
                    $currentStream = array();
                    $status = $stream["stream"]["channel"]["status"];
                    $game = $stream["stream"]["game"];
                    $datetime = $stream["stream"]["created_at"];
                    $date = strtotime($datetime);
                    array_push($currentStream, array(   Name => $channel,
                                                        Title => $status,
                                                        Game => $game,
                                                        Date => $date));
                }
            }
       	}
        print(json_encode($currentStream, JSON_UNESCAPED_SLASHES));
    }
    
    