<?php
require 'functions.php';
require 'download.php';

/**
 * Class YouTube
 */
class YouTube {
	
	public $query;
	public $count;
	public $order;
	public $pageToken;
	# Key
	public $cc_key;
	# Data
	static $filer;

    /**
     * @param $query
     * @param $count
     * @param $order
     * @param $pageToken
     * @param $key
     */
	public function __construct($query, $count, $order, $pageToken) {
		$this->query = $query;
		$this->count = $count;
		# Orders type
		$this->order = $order;
        $allowOrder = array('relevance', 'date', 'viewCount', 'rating');
        if(!in_array($this->order, $allowOrder)) exit('Wrong type of order');
		$this->pageToken = $pageToken;
		# Key
		$this->cc_key = 'AIzaSyCI0UWRNu-SPyBsRwvArhbghb36PNtor28';
		
		# Make url
		$url = 'https://www.googleapis.com/youtube/v3/search?part=id&type=video&q='.$this->query.'&maxResults='.intval($this->count).'&order='.$this->order.($this->pageToken ? '&pageToken='.$this->pageToken : '').'&key='.$this->cc_key;
		
		# Get data
		self::$filer = json_decode(file_get_contents($url),true);
	}

    /**
     * @return array
     */
	function search() {
		/**
		* 	@param VideoId
		* 	@type array
		*	@desc this array will contain the IDs returned from the first call
		*/
		$VideoId = array();
		/**
		*	@param data
		*	@type array
		*	@desc this array will be used to store details of each video
		*/
		$data = array();
		/**
		*	@param IDurl
		*	@type string
		*	@desc this variable will contain a string of the IDs got from the endpoint
		*/
		$IDurl='';
			
		//Store IDs to VideoId
		foreach (self::$filer['items'] as $entry){
			if (isset($entry['id']['videoId'])){
				$VideoId [] = $entry['id']['videoId'];
			}
		}
		//Create the IDs string
		foreach ($VideoId as $key => $value) {
			$IDurl .= $value.',';
		}
		//Trim IDurl (',')
		$IDurl = rtrim($IDurl,',');

		//create the second Youtube endpoint URL
		$video_url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics%2CcontentDetails&id='.$IDurl.'&key='.$this->cc_key;
		$video_filer = json_decode(file_get_contents($video_url),true);
		
		//Store each video details to data
		foreach ($video_filer['items'] as $video){
			if (isset($video['id'])){
				$date = new DateTime($video['snippet']['publishedAt']);
				$time = covtime($video['contentDetails']['duration']);
				//convert the date
				$video_date = date_format($date , 'd/m/y');
				//create the video list details
				$data[] = array(
					"id" => $video['id'],
					"thumbnail" => $video['snippet']['thumbnails']['medium']['url'],
					"title" => htmlspecialchars($video['snippet']['title'], ENT_QUOTES, 'UTF-8'),
					"title_short" => short_text_out(htmlspecialchars($video['snippet']['title'], ENT_QUOTES, 'UTF-8'), 4),
					"description" => htmlspecialchars($video['snippet']['description'], ENT_QUOTES, 'UTF-8'),
					"description_short" => short_text_out(htmlspecialchars($video['snippet']['description'], ENT_QUOTES, 'UTF-8'), 16),
					"duration" => $video['contentDetails']['duration'],
					"username" => $video['snippet']['channelTitle'],
					"profile" => "https://www.youtube.com/channel/".$video['snippet']['channelId'],
					"views" => (isset($video['statistics']['viewCount']))?$video['statistics']['viewCount']:'',
					"likeCount" => (isset($video['statistics']['likeCount']))?$video['statistics']['likeCount']:'',
					"dislikeCount" => (isset($video['statistics']['dislikeCount']))?$video['statistics']['dislikeCount']:'',
					"date" => $video_date,
					"time" => $time,
					"more" =>  'https://www.youtube.com/watch?v='.$video['id'],
					"embed_url" => 'http://www.youtube.com/embed/'.$video['id'].'?autoplay=1'
				);
			}
		}
			
		return $data;
	}

    /**
     * @return array
     */
	function info() {
		
		$info = array(
			"count" => self::$filer['pageInfo']['totalResults'],
			"res" => self::$filer['pageInfo']['resultsPerPage'],
			"next" => (isset(self::$filer['nextPageToken']) ? self::$filer['nextPageToken'] : NULL),
			"prev" => (isset(self::$filer['prevPageToken']) ? self::$filer['prevPageToken'] : NULL),
		);
		
		return $info;
	}
}