<?php
/****************************
 * File :  Api.php
 * Author : Cygnusa
 * @2018
 *
 *	Main Api Class
 *
****************************/

require_once("appconfig.php");
require_once("Rest.inc.php");
require_once("global.php");
require_once("projectfunctions.php");

class API extends REST {
	
	public $data = "";		
	public $db = NULL;
	
	//CONFIG
	public $site_settings = NULL;	
	private $role_administrator =1;
	private $role_admin =2;
	private $role_user =3;
	
	public $api_url = NULL;
	public $function_name = NULL;
	public $params=NULL;
	public $funcparams=NULL;
	public $lang=NULL;
	public $device_type=NULL;	
	public $current_user_data =NULL;
	public $current_user_id=NULL;
    
	public $current_user_role=NULL;
	public $current_access_token=NULL;
    
    public $current_smpin=NULL;
    public $current_emp_code=NULL;    
	public $current_page=0;
	public $manager_error=NULL; 
    
    public $dse_roles=array("8,9,10,11,12,13"); 
	 
	public function __construct(){
		parent::__construct();
	}
	
	/* /////////////////////////////// DEVICE VALIDATION ////////////////////////////// */
	private function validateDevice($device_type){
		 
		 if(defined('DEVICE_TYPE'))
		 { 
			$device_arr=explode("|",DEVICE_TYPE); if(!(is_array($device_arr)&& in_array($device_type,$device_arr))) $this->response(array('response'=>'failed', 'message' => 'PAGE NOT FOUND'), 404);
		}else {
			$this->response(array('response'=>'failed', 'message' => 'PAGE NOT FOUND'), 404);
		}	
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// LANGUAGE VALIDATION ////////////////////////////// */
	private function validateLanguage($lang){
		/* 
		$query_lang=$this->getQueryValue("SELECT language_id FROM ".TABLE_MASTER_LANGUAGE."  WHERE  language_code='".$lang."' LIMIT 1");
		if(count($query_lang)<0)$this->response(array('response'=>'failed', 'message' => 'INVALID LANGUAGE'), 404);
         * 
         */
        if(strtolower($lang)!='en_us')$this->response(array('response'=>'failed', 'message' => 'INVALID LANGUAGE'), 404);
		return true;
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// DATABASE CONNECTION ////////////////////////////// */		
	private function dbConnect(){
		try{
			$this->db = new PDO("mysql:host=".HOST.";dbname=".DBNAME.";charset=utf8",DBUSER,DBPASSWORD,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
			$this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);			
		}catch(PDOException $e){
			
			$this->response(array('response'=>'failed', 'message' => 'DB NOT CONNECTED'), 503);
			exit(1);
		}		
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/*
	* Public method for access api.
	* This method dynamically call the method based on the query string
	*
	*/
		
	/* /////////////////////////////// PROCESS ////////////////////////////// */
	public function processApi(){
		$api_request=explode("_api/",urldecode($_SERVER['REQUEST_URI']));
		$this->api_url=$api_request[1];
		//CHECK URL API EXITS
		if(!isset($api_request[1]) || ($api_request[1]==NULL || $api_request[1]=='' || strpos($api_request[1], '/') === false)){
			$this->response(array('response'=>'failed','message' => 'PAGE NOT FOUND'),404);
		}else{
			//CHECK URL SPLIT	
			$request_function=explode("/",$api_request[1]);
			if(!count($request_function)>3) $this->response(array('response'=>'failed','message'=>'PAGE NOT FOUND'),404);
			
			//CHECK DEVICE 
			$this->device_type=trim(strtolower($request_function[0]));
			$this->validateDevice($this->device_type);
			
			//CONNNECT TO DB			
			$this->dbConnect();	
			
			//CHECK LANGUAGE
			$this->lang=trim($request_function[1]);
			$this->validateLanguage($this->lang);
			
			
			$function=strtolower(trim(str_replace("/","", $request_function[2])));
			$func_namearr=explode("?",$function);	
			$this->function_name=$func_namearr[0];
			//FOR SINGLE CONTROLLER WITH FILTER CALL
			$this->funcparams=array_slice($func_namearr,1);
			$this->params=($request_function[2]==NULL || $request_function[2]=='')?NULL:array_slice($request_function,3);
			 
		}
		$this->call_controller();	
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
		
	/* /////////////////////////////// CALL CONTROLLER ////////////////////////////// */
	private function call_controller()
	{	
		if(file_exists(APPLICATION_PATH.CONTROLLER_PATH.DIRECTORY_SEPARATOR.strtolower($this->function_name).".php"))
		{				
					
			$qry_params=explode ("?",$this->params[0]);	
			try{
				spl_autoload_register('my_autoloader');
				$classname=$this->function_name;
				 
				$obj = new $classname($this);
	
			}catch(Exception $e){
				$this->response(array('response'=>'failed','message'=>$e->getMessage()),500);
			}	
			 
		}else{
			// If the method not exist with in this class, response would be "Page not found".
			$this->response(array('response'=>'failed','message'=>'PAGE NOT FOUND'),404);
		}
		
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* MYSQL MAIN FUNCTION */
	/* /////////////////////////////// EXCECUTE QUERY ////////////////////////////// */
	public function executeQuery($str) {
        try
        {
            $result = $this->db->query($str);		
            return $result;
        }
        catch (PDOException $e) {
           $this->response(array('response'=>'failed','message'=>"PHP CODE ERROR ".$e->getMessage()),500);
        }        
        catch(Exception $e){
			$this->response(array('response'=>'failed','message'=>"PHP CODE ERROR ".$e->getMessage()),500);
		}
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// QUERY VALUE ////////////////////////////// */
	public function getQueryValue($str) {
        try
        {
            $result = $this->executeQuery($str);
            $result_value = $result->fetchAll(PDO::FETCH_OBJ);	
            return $result_value;
        }
        catch (PDOException $e) {
           $this->response(array('response'=>'failed','message'=>"MYSQL ERROR ".$e->getMessage()),500);
        }        
        catch(Exception $e){
			$this->response(array('response'=>'failed','message'=>"PHP CODE ERROR ".$e->getMessage()),500);
		}
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// SELECT QUERY ////////////////////////////// */
	public function selectQuery($table_name, $field_name, $condition, $limitations='')
	{
		try{	
			if($field_name == "") $field_name = "*";		
			$select_query_str = "SELECT $field_name FROM $table_name";
			if($condition!="") $select_query_str .= " where $condition";
			if($limitations!="")  $select_query_str .= " limit $limitations";
			
			
			$query_obj=$this->executeQuery($select_query_str);
			$num_rows  = $query_obj->rowCount($query_obj);
			$result_value=array();
			if($num_rows>0)
			{
				$result_value = $query_obj->fetchAll(PDO::FETCH_OBJ);
			}	   
			return array('nr' => $num_rows,'result'=>$result_value);
		
		}catch (PDOException $e) {
           $this->response(array('response'=>'failed','message'=>"MYSQL ERROR ".$e->getMessage()),500);
        }        
        catch(Exception $e){
			$this->response(array('response'=>'failed','message'=>"PHP CODE ERROR ".$e->getMessage()),500);
		}
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// QUERY COUNT ////////////////////////////// */
	public function getQueryCount($str) {
        try
        {
            $result = $this->executeQuery($str);
            $result_value = $result->rowCount();
            return $result_value;
        }
        catch (PDOException $e) {
           $this->response(array('response'=>'failed','message'=>"MYSQL ERROR ".$e->getMessage()),500);
        }        
        catch(Exception $e){
			$this->response(array('response'=>'failed','message'=>"PHP CODE ERROR ".$e->getMessage()),500);
		}
	}
	
	/* ///////////////////////////////////////////////////////////////////////////////////// */
	
	/* /////////////////////////////// LAST INSERT ID ////////////////////////////// */
	public function lastInsertId(){
		return $this->db->lastInsertId();
	}
	/* ///////////////////////////////////////////////////////////////////////////////////// */
 
}
	
// Initiiate Library
$api = new API;
$api->processApi();

?>