<?php

require_once("Rest.inc.php");
require_once("db.php");

class functions extends REST {
    
    private $mysqli = NULL;
    private $db = NULL;
    
    public function __construct($db) {
        parent::__construct();
        $this->db = $db;
        $this->mysqli = $db->mysqli;
    }

    public function checkConnection() {
    	if (mysqli_ping($this->mysqli)) {
    		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
    			$respon = array('status' => 'ok', 'database' => 'connected');
    			$this->response($this->json($respon), 200);
    		} else {
    			$respon = array('status' => 'error', 'database' => 'API is disabled');
    			$this->response($this->json($respon), 200);
    		}
    	} else {
    		$respon = array('status' => 'failed', 'database' => 'not connected');
    		$this->response($this->json($respon), 404);
    	}
    }

    public function getRecentRadio() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {

			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {

					if ($this->get_request_method() != "GET") $this->response('',406);
						$limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
						$page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;
									
						$offset = ($page * $limit) - $limit;
						$count_total = $this->get_count_result("SELECT COUNT(DISTINCT id) FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND c.category_status = 1 AND n.radio_status = 1");
						$query = "SELECT n.id AS 'radio_id', n.radio_name, n.radio_image, n.radio_url, n.radio_description, n.type AS 'radio_type', n.view_count, c.category_name FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND c.category_status = 1 AND n.radio_status = 1 ORDER BY n.id DESC LIMIT $limit OFFSET $offset";

						$categories = $this->get_list_result($query);
						$count = count($categories);
						$respon = array(
										'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'posts' => $categories
						);
						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
					$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
					$this->response($this->json($respon), 404);
			}

		} else {
			$this->responseInvalidParam();
		}
    }
    
    public function getCategoryIndex() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {    	

					if($this->get_request_method() != "GET") $this->response('',406);
						//$count_total = $this->get_count_result("SELECT COUNT(DISTINCT cid) FROM tbl_category WHERE category_status = 1");
						$query = "SELECT DISTINCT c.cid, c.category_name, c.category_image, COUNT(DISTINCT r.id) AS radio_count
									FROM tbl_category c LEFT JOIN tbl_radio r ON c.cid = r.category_id WHERE c.category_status = 1 AND r.radio_status = 1 GROUP BY c.cid ORDER BY c.cid DESC";

						$categories = $this->get_list_result($query);
						$count = count($categories);
						$respon = array(
							'status' => 'ok', 'count' => $count, 'categories' => $categories
						);
						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
					$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
					$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}
    }

    public function getCategoryDetail() {

    	$id = $_GET['id'];

		if($this->get_request_method() != "GET") $this->response('',406);
		$limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
		$page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;

		$offset = ($page * $limit) - $limit;
		$count_total = $this->get_count_result("SELECT COUNT(DISTINCT id) FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND c.category_status = 1 AND n.radio_status = 1 AND n.category_id = '$id'");

		$query_category = "SELECT DISTINCT cid, category_name, category_image FROM tbl_category WHERE cid = '$id' AND category_status = 1 ORDER BY cid DESC";

		$query_post = "SELECT DISTINCT n.id AS 'radio_id', 
						n.radio_name, 
						n.radio_image,
						n.radio_url,
						n.radio_description,
						n.type AS 'radio_type',
						n.view_count,
						n.category_id,	
						c.category_name

						FROM tbl_radio n 

						LEFT JOIN tbl_category c ON n.category_id = c.cid 

						WHERE c.cid = '$id' 
						AND c.category_status = 1
						AND n.radio_status = 1

						GROUP BY n.id 
						ORDER BY n.id DESC 
								 
						LIMIT $limit OFFSET $offset";

		$category = $this->get_category_result($query_category);
		$post = $this->get_list_result($query_post);
		$count = count($post);
		$respon = array(
			'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'category' => $category, 'posts' => $post
		);
		$this->response($this->json($respon), 200);

    }

    public function getSearchResults() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {

					$search = $_GET['search'];

					if($this->get_request_method() != "GET") $this->response('',406);
					$limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
					$page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;

					$offset = ($page * $limit) - $limit;
					$count_total = $this->get_count_result("SELECT COUNT(DISTINCT n.id) FROM tbl_radio n, tbl_category c WHERE n.category_id = c.cid AND c.category_status = 1 AND n.radio_status = 1 AND (n.radio_name LIKE N'%$search%' OR c.category_name LIKE N'%$search%')");

					$query = "SELECT DISTINCT n.id AS 'radio_id', 
												n.radio_name, 
												n.radio_image,
												n.radio_url,
												n.radio_description,
												n.type AS 'radio_type',
												n.view_count,
												c.category_name

											  FROM tbl_radio n 

											  LEFT JOIN tbl_category c ON n.category_id = c.cid 

											  WHERE n.category_id = c.cid 
											  AND c.category_status = 1
											  AND n.radio_status = 1
											  AND (n.radio_name LIKE N'%$search%' OR c.category_name LIKE N'%$search%') 

											  GROUP BY n.id 
											  ORDER BY n.id DESC

										LIMIT $limit OFFSET $offset";

					$post = $this->get_list_result($query);
					$count = count($post);
					$respon = array(
						'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'posts' => $post
					);
					$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}
    }

    public function getSearchResultsRTL() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {

					$search = $_GET['search'];

					if($this->get_request_method() != "GET") $this->response('',406);
					$limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
					$page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;

					$offset = ($page * $limit) - $limit;
					$count_total = $this->get_count_result("SELECT COUNT(DISTINCT n.id) FROM tbl_radio n, tbl_category c WHERE n.category_id = c.cid AND c.category_status = 1 AND n.radio_status = 1 AND (n.radio_name LIKE N'%$search%' OR c.category_name LIKE N'%$search%')");

					$query = "SELECT DISTINCT n.id AS 'radio_id', 
												n.radio_name, 
												n.radio_image,
												n.radio_url,
												n.radio_description,
												n.type AS 'radio_type',
												n.view_count,
												c.category_name

											  FROM tbl_radio n 

											  LEFT JOIN tbl_category c ON n.category_id = c.cid 

											  WHERE n.category_id = c.cid 
											  AND c.category_status = 1
											  AND n.radio_status = 1
											  AND (n.radio_name LIKE N'%$search%' OR c.category_name LIKE N'%$search%') 

											  GROUP BY n.id 
											  ORDER BY n.id DESC

										LIMIT $limit OFFSET $offset";

					$post = $this->get_list_result($query);
					$count = count($post);
					$respon = array(
						'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'posts' => $post
					);
					$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}
    }

	public function getPrivacyPolicy() {
		include "../includes/config.php";
		$sql = "SELECT * FROM tbl_settings WHERE id = 1";
		$result = mysqli_query($connect, $sql);
		header( 'Content-Type: application/json; charset=utf-8' );
		print json_encode(mysqli_fetch_assoc($result));
	}


    public function getHome() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		$limit = 20;

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {

					if ($this->get_request_method() != "GET") $this->response('',406);

						$sql_featured = "SELECT n.id AS 'radio_id', n.radio_name, n.radio_image, n.radio_url, n.radio_description, n.type AS 'radio_type', n.view_count, c.category_name FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND n.featured = 1 AND n.radio_status = 1 AND c.category_status = 1 ORDER BY n.last_update DESC LIMIT $limit";

						$sql_categories = "SELECT DISTINCT c.cid, c.category_name, c.category_image, COUNT(DISTINCT r.id) as radio_count FROM tbl_category c LEFT JOIN tbl_radio r ON c.cid = r.category_id WHERE c.featured = 1 AND c.category_status = 1 GROUP BY c.cid ORDER BY c.last_update DESC LIMIT $limit";

						$sql_recent = "SELECT n.id AS 'radio_id', n.radio_name, n.radio_image, n.radio_url, n.radio_description, n.type AS 'radio_type', n.view_count, c.category_name FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND n.radio_status = 1 AND c.category_status = 1 ORDER BY n.id DESC LIMIT $limit";

						$sql_views = "SELECT n.id AS 'radio_id', n.radio_name, n.radio_image, n.radio_url, n.radio_description, n.type AS 'radio_type', n.view_count, c.category_name FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND n.radio_status = 1 AND c.category_status = 1 ORDER BY n.view_count DESC LIMIT $limit";

						$sql_random = "SELECT n.id AS 'radio_id', n.radio_name, n.radio_image, n.radio_url, n.radio_description, n.type AS 'radio_type', n.view_count, c.category_name FROM tbl_category c, tbl_radio n WHERE c.cid = n.category_id AND n.radio_status = 1 AND c.category_status = 1 ORDER BY RAND() LIMIT $limit";

						$featured = $this->get_list_result($sql_featured);
						$categories = $this->get_list_result($sql_categories);
						$recent = $this->get_list_result($sql_recent);
						$views = $this->get_list_result($sql_views);
						$random = $this->get_list_result($sql_random);
						$respon = array(
							'status' => 'ok', 'featured' => $featured, 'categories' => $categories, 'recent' => $recent, 'views' => $views, 'random' => $random
						);
						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}

    }

	public function getSettings() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {    	

					if($this->get_request_method() != "GET") $this->response('',406);

						$query = "SELECT a.*, s.package_name, s.fcm_notification_topic, s.onesignal_app_id, s.more_apps_url, s.privacy_policy FROM tbl_ads a, tbl_settings s LIMIT 1";

						$settings = $this->get_one($query);
						$respon = array(
							'status' => 'ok', 'settings' => $settings
						);
						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}

    }

	public function getNewSettings() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];
				$package_name = $_GET['package_name'];

				if ($access_key_received == $api_key) {    	

					if($this->get_request_method() != "GET") $this->response('',406);

						$sqlSettings = "SELECT a.*, s.package_name, s.fcm_notification_topic, s.onesignal_app_id, s.more_apps_url, s.privacy_policy FROM tbl_ads a, tbl_settings s LIMIT 1";
						$sqlApp = "SELECT package_name, status, redirect_url FROM tbl_app_config WHERE package_name = '$package_name' LIMIT 1 ";

						$settings = $this->get_one($sqlSettings);

						$appCount = count($this->get_list_result($sqlApp));
						$app = $this->get_one($sqlApp);
						$AppArray = array( 'package_name' => '', 'status' => '', 'redirect_url' => '');

						if ($appCount > 0) {
							$respon = array('status' => 'ok', 'app' => $app, 'settings' => $settings);
						} else {
							$respon = array('status' => 'ok', 'app' => $AppArray, 'settings' => $settings);
						}

						//$respon = array('status' => 'ok', 'settings' => $settings);

						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}

    }

    public function getUserToken() {

    	$response = array();

    	$username = $_POST['username'];
    	$password = $_POST['password'];
    	$password_hash = hash('sha256',$username.$password);
    	$email = $_POST['email'];
    	$full_name = $_POST['full_name'];
    	$user_role = '100';
    	$table_name = $_POST['table_name'];

    	include "../includes/config.php";

    	$sql = "SELECT * FROM $table_name WHERE username = '$username'";
    	$check = mysqli_fetch_array(mysqli_query($connect, $sql));

    	if (isset($check)) {
    		$response["value"] = 0;
    		$response["message"] = "Whoops! data already exist!";
    		header( 'Content-Type: application/json; charset=utf-8' );
    		echo json_encode($response);
    	} else {
    		$insert = "INSERT INTO $table_name (username, password, email, full_name, user_role) VALUES('$username','$password_hash', '$email', '$full_name', '$user_role')";
    		if (mysqli_query($connect, $insert)) {
    			$response["value"] = 1;
    			$response["message"] = "Success";
    			header( 'Content-Type: application/json; charset=utf-8' );
    			echo json_encode($response);
    		} else {
    			$response["value"] = 2;
    			$response["message"] = "Whoops! Failed!";
    			header( 'Content-Type: application/json; charset=utf-8' );
    			echo json_encode($response);
    		}
    	}
    	mysqli_close($connect);

    }


    public function getSocial() {

    	include "../includes/config.php";
		$setting_qry    = "SELECT * FROM tbl_settings WHERE id = '1'";
		$setting_result = mysqli_query($connect, $setting_qry);
		$settings_row   = mysqli_fetch_assoc($setting_result);
		$api_key    = $settings_row['api_key'];

		if ($this->validateResourceAccess($this->retrieveCurrentToken())) {
			if (isset($_GET['api_key'])) {

				$access_key_received = $_GET['api_key'];

				if ($access_key_received == $api_key) {    	

					if($this->get_request_method() != "GET") $this->response('',406);

						$query = "SELECT * FROM tbl_social WHERE status = 1 ORDER BY id DESC";

						$social = $this->get_list_result($query);
						$respon = array(
							'status' => 'ok', 'social' => $social
						);
						$this->response($this->json($respon), 200);

				} else {
					$respon = array( 'status' => 'failed', 'message' => 'Oops, API Key is Incorrect!');
					$this->response($this->json($respon), 404);
				}
			} else {
				$respon = array( 'status' => 'failed', 'message' => 'Forbidden, API Key is Required!');
				$this->response($this->json($respon), 404);
			}
		} else {
			$this->responseInvalidParam();
		}

    }

	public function updateView() {

		include "../includes/config.php";

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {

			$response = array();

			$id = $_POST['id'];

			$sql = "UPDATE tbl_radio SET view_count = view_count + 1 WHERE id = '$id'";

			if(mysqli_query($connect, $sql)) {
				$response["value"] = 1;
				$response["message"] = "success update views";

				header( 'Content-Type: application/json; charset=utf-8' );
				echo json_encode($response);
			} else {
				$response["value"] = 0;
				$response["message"] = "failed update vieww!";

				header( 'Content-Type: application/json; charset=utf-8' );
				echo json_encode($response);
			}

			mysqli_close($connect);

		}

	}    


    public function get_list_result($query) {
		$result = array();
		$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
		if($r->num_rows > 0) {
			while($row = $r->fetch_assoc()) {
				$result[] = $row;
			}
		}
		return $result;
	}

    public function get_count_result($query) {
		$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
		if($r->num_rows > 0) {
			$result = $r->fetch_row();
			return $result[0];
		}
		return 0;
	}

	private function get_category_result($query) {
		$result = array();
		$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
		if($r->num_rows > 0) {
			while($row = $r->fetch_assoc()) {
				$result = $row;
			}
		}
		return $result;
	}

	private function get_one($query) {
		$result = array();
		$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
		if($r->num_rows > 0) $result = $r->fetch_assoc();
		return $result;
	}
    
}

?>