<?php
include_once 'serverMessenger.php';
// Start the session
session_start();

function getYoutubeJSON($KEY, $CONTINUATION) {
    $DEV_KEY = 'AIzaSyCXZDOxqMGj6Vtcty1tvlqQYJ5x2xoCYqM';
    $KEYWORD = preg_replace("/[\s]/", "+", $KEY);
    $url     = "https://www.googleapis.com/youtube/v3/search?q=". $KEYWORD .
               "&part=snippet&maxResults=50&type=video&key=". $DEV_KEY;

    if ($CONTINUATION != "null")
        $url .= "&pageToken=". $CONTINUATION;

    error_log($url, 4);

    $server_output = getYTList($url);
    echo $server_output;


}

function getYTList($api_url = '') {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $arr_result = json_decode($response);
    if (isset($arr_result->items)) {
        return $response;
    } elseif (isset($arr_result->error)) {
        $message = "Server: [Error] --> Something went wrong...";
        serverMessage("error", $message);
    }
}

// Determin action
if (isset($_POST['query'], $_POST['stub'], $_POST['continuation'])) {
    getYoutubeJSON($_POST['stub'], $_POST['continuation']);
} else {
    $message = "Server: [Error] --> Illegal Access Method!";
    serverMessage("error", $message);
}
?>
