<?php ob_start(); header("Content-Type: application/json");
if(file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'includes/config.php')){
require(__DIR__ . DIRECTORY_SEPARATOR . 'includes/config.php');	
	
if(!isset($_GET['key'])){
	echo $z->json(array(
		'result' => 'error',
		'reason' => 'dailyLimitExceededUnreg',
		'message' => 'Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.'
	)); exit;
}

@list($key, $tm) = explode("@@", $z->decode($_GET['key']));
$__key = $z->getSetting('apikey');
$okey = $z->getSetting('api_key');

if($okey!=$_GET['key'] || $__key != $key){
	echo $z->json(array(
		'result' => 'error',
		'reason' => 'invalidKey',
		'message' => 'API Key you provided is either invalid or is expired.'
	)); exit;
}
	
switch($_GET['action']):
	case "genres":		
		$list = $z->select("SELECT * FROM genres WHERE status=? ORDER BY title ASC", array("yes"), "s");
		if($list->result=="ok" && $list->count > 0){
			for($n = 0; $n < count($list->fetch); $n++):
				$data[] = array(
					'ID' => $hash->encode($list->fetch[$n]->ID),
					'label' => $list->fetch[$n]->title,
					'slug' => $list->fetch[$n]->slug,
					'trackCount' => number_format($list->fetch[$n]->tracks)
				);
			endfor;
			echo $z->json(array(
				'result' => 'ok',
				'list' => $data
			)); exit;
		}else{
			echo $z->json(array(
				'result' => 'error',
				'message' => 'Empty Result.'
			)); exit;
		}
	break;
	case "featured":		
		$limit = (int) isset($_GET['perpage']) ? $_GET['perpage'] : 30;
		$list = $z->select("SELECT * FROM tracks WHERE status=? ORDER BY views DESC LIMIT ?", array("yes",$limit), "ss");
		if($list->result=="ok" && $list->count > 0){
			for($n = 0; $n < count($list->fetch); $n++):
				$data[] = $z->apiTrackItem($list->fetch[$n]);
			endfor;
			echo $z->json(array(
				'result' => 'ok',
				'total' => $limit,
				'tracks' => $data
			)); exit;
		}else{
			echo $z->json(array(
				'result' => 'error',
				'message' => 'Empty Result.'
			)); exit;
		}
	break;
	case "newreleases":
		$limit = (int) isset($_GET['perpage']) ? $_GET['perpage'] : 30;
		$start = 0; $ostart = 1;
		if(isset($_GET['nextPageToken'])){
			$ostart = (int) $hash->decode($_GET['nextPageToken'])[0];
			$start = $limit * $ostart - $limit;	
		}
		$total = $z->select("SELECT COUNT(ID) as total FROM tracks WHERE status=?", array("yes"), "s")->row->total;
		$totalPages = ceil($total / $limit);
		$list = $z->select("SELECT * FROM tracks WHERE status=? ORDER BY ID DESC LIMIT ?,?", array("yes",$start,$limit), "sss");
		if($list->result=="ok" && $list->count > 0){
			for($n = 0; $n < count($list->fetch); $n++):
				$data[] = $z->apiTrackItem($list->fetch[$n]);
			endfor;
			$_ARRAY = array();
			$_ARRAY['result'] = 'ok';
			$_ARRAY['total'] = $total;
			if($ostart > 1){
				$_ARRAY['prevToken'] = $hash->encode($ostart-1);			
			}
			if($ostart < $totalPages){
				$_ARRAY['nextToken'] = $hash->encode($ostart+1);			
			}
			$_ARRAY['tracks'] = $data;			
			echo $z->json($_ARRAY); exit;
		}else{
			echo $z->json(array(
				'result' => 'error',
				'message' => 'Empty Result.'
			)); exit;
		}
	break;
	case "search":
		$limit = (int) isset($_GET['perpage']) ? $_GET['perpage'] : 30;
		$start = 0; $ostart = 1;
		if(isset($_GET['nextPageToken'])){
			$ostart = (int) $hash->decode($_GET['nextPageToken'])[0];
			$start = $limit * $ostart - $limit;	
		}
		
		if(isset($_GET['q']) && !empty($_GET['q'])){
			$keyword = str_replace(" ", "+", urldecode($_GET['q']));
			$q = "SELECT * FROM tracks WHERE status=? AND (";						
			$okeyword = $keyword = $z->clean(str_replace("+"," ", $_GET['q']));
			$x = array_reverse(explode(" ", $keyword));	
			$keywords_set = array();
			foreach($x as $word):
				array_push($keywords_set, $word);		
			endforeach;
			$combinations = $z->getCombinations($keywords_set);
			$c = 0;
			foreach($combinations as $newWord):
				if(!empty($newWord)){	
					if(substr($newWord, -1)==' '){ $newWord = substr($newWord, 0, -1); }
					if($c>0){	$q .= " OR "; }
					$newWord = $z->realescape($newWord);
					$q .= " title LIKE '%$newWord%' ";
					$c++;
				}		
			endforeach;			
			$q .= " ) ";
			$total = $z->select($q, array("yes"), "s")->count;	
			$q .= " ORDER BY ";
			foreach($combinations as $newWord):
				if(!empty($newWord)){	
					if(substr($newWord, -1)==' '){ $newWord = substr($newWord, 0, -1); }
					$newWord = $z->realescape($newWord);
					$q .= "CASE WHEN instr(title, '$newWord') = 0 THEN 1 ELSE 0 END,";
				}
			endforeach;			
			$q .= "instr(title, '$keyword') DESC";			
			$q .= " LIMIT ?, ?";	
			$list = $z->select($q, array("yes",$start,$limit), "sii");
			$totalPages = ceil($total / $limit);
			if($list->result=="ok" && $list->count > 0){
				for($n = 0; $n < count($list->fetch); $n++):
					$data[] = $z->apiTrackItem($list->fetch[$n]);
				endfor;
				$_ARRAY = array();
				$_ARRAY['result'] = 'ok';
				$_ARRAY['query'] = $_GET['q'];
				$_ARRAY['total'] = $total;
				if($ostart > 1){
					$_ARRAY['prevToken'] = $hash->encode($ostart-1);			
				}
				if($ostart < $totalPages){
					$_ARRAY['nextToken'] = $hash->encode($ostart+1);			
				}
				$_ARRAY['tracks'] = $data;			
				echo $z->json($_ARRAY); exit;
			}else{
				echo $z->json(array(
					'result' => 'error',
					'message' => 'Empty Result.'
				)); exit;
			}
		}else{
			echo $z->json(array(
				'result' => 'error',
				'message' => 'Empty Query String.'
			)); exit;
		}
		
	break;
endswitch;
}
ob_flush(); ?>