<?php
	function set_upload_service($path){
	    $config = array();
	    $config['upload_path'] = $path;
	    $config['allowed_types'] = '*';
	    $config['overwrite'] = FALSE;
	    return $config;
	}

	function remove_html(&$item, $key){
	    $item = strip_tags($item);
	}

	function set_log($class,$method,$postdata,$auth){
		$CI = & get_instance();
		$url = $class.'/'.$method;
		$data = array('url'=>$url,
					  'parameter'=>$postdata,
					  'auth'=>$auth,
					  'time'=>date('Y-m-d h:i:s'));

		$CI->db->insert('service_log',$data);
		return $CI->db->insert_id();
	}

	function getSettings(){
		$CI = & get_instance();
		$settings = $CI->db->get('setting');
		return (!empty($settings))?$settings->row_array():'';
	}

	function pr($val){
		echo (is_array($val))?'<pre>':'';
		print_r($val);
		echo (is_array($val))?'</pre>':'';
		exit;
	}

	function pre($val){
		echo (is_array($val))?'<pre>':'';
		print_r($val);
		echo (is_array($val))?'</pre>':'';
		echo '<br>';
	}

	function encode_param($param = ''){
		if(empty($param)){
			return;
		}
		$encode = base64_encode('{*}'.$param.'{*}');
		$encode = base64_encode('a%a'.$encode.'a%a');
		$encode = base64_encode('b'.$encode.'b');
		$encode = base64_encode('Ta7K'.$encode.'eyRq');
		return urlencode($encode);
	}

	function decode_param($param = ''){
		if(empty($param)){
			return;
		}
		$decode = urldecode(trim($param));
		$decode = trim(base64_decode(urldecode($decode)),'Ta7K');
		$decode = trim($decode,'eyRq');
		$decode = trim(base64_decode(urldecode($decode)),'b');
		$decode = trim(base64_decode(urldecode($decode)),'a%a');
		$decode = trim(base64_decode(urldecode($decode)),'{*}');
		return $decode;
	}

	function getLocationLatLng($location = ''){
	  	$settings = getSettings();

		if(empty($location) || empty($settings) || !isset($settings['google_api_key']) || 
		   empty($gKey = $settings['google_api_key'])){
			return 0;
		}
		$thisObj = & get_instance();
		$locData = file_get_contents("https://maps.google.com/maps/api/geocode/json?address=".
									 urlencode($location)."&sensor=false&key=".$gKey);
		if(empty($locData))
			return 0;
	    $loc_data = json_decode($locData);
	    if(empty($loc_data) || !isset($loc_data->status) || $loc_data->status != 'OK')
			return 0;

		$locArr['lat'] = $loc_data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
		$locArr['lng'] = $loc_data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

	    if(empty($locArr['lat']) || empty($locArr['lng']))
			return 0;
		return $locArr;
	}

	function generate_unique() {
		$unique = md5(uniqid(time().mt_rand(), true));
		return $unique;
	}

	function genQRcode($qr_id='',$url='',$custmLogo=''){
		if(empty($qr_id)){
			return '';
		}
		include 'qr_code/autoload.php';

		$qr_id 			= urlencode($qr_id);
		$logo 			= (!empty($custmLogo))?$custmLogo:'assets/images/qr-cod-icon.png';
		$savePath 		= (!empty($url))?$url:"assets/uploads/qrcode/bookCode_".time().".png";

		$QR = imagecreatefrompng('https://chart.googleapis.com/chart?cht=qr&chld=H|1&chs=500x500&chl='.$qr_id);

		$logo 			= imagecreatefromstring(file_get_contents($logo));
		$qrWidth 		= imagesx($QR)/3;
		$qrHeight 		= imagesy($QR)/3;

		$logoWidth 	    = imagesx($logo);
		$logoHeight 	= imagesy($logo);

		$scale 			= $logoWidth/$qrWidth;
		$imgWidth 	    = $qrWidth;
		$imgHeight      = $logoHeight/$scale;

		imagecopyresampled($QR,$logo,$imgWidth,$qrHeight,0,0,$imgWidth,$imgHeight,$logoWidth,$logoHeight);
		imagepng($QR, $savePath);

		return $savePath;
	}

	// function BayanPayPayment(){
	// 	include 'BayanPayPaymentLibrary.php';
	// }

	function getCurrency($userId=''){
		$CI = & get_instance();
		$join = (!empty($userId))?"INNER JOIN customer AS CUST (CUST.country_id=CON.country_id AND 
		                                                        CUST.customer_id=$userId)":'';

		$countryData = $CI->db->query("SELECT * FROM country AS CON $join WHERE CON.status='1'");
		if(empty($countryData)){
			return 0;
		}
		return (empty($userId))?$countryData->result_array():$countryData->row_array();
	}
	
	function getNotifTemplate(){
		$CI = & get_instance();
		$settings = $CI->db->get('notification_templates');
		return (!empty($settings))?$settings->row_array():'';
	}

	function roleManagement(){
		$CI = & get_instance();
		$menus = array();
	    $userType = $CI->session->userdata['user_type'];
		switch($userType){
			/* ADD => 1  EDIT => 2  DELETE => 3  CHANGE_STATUS => 4 */
		    case 1: 
		        $menus = array('Dashboard'=>array(1,2,3,4),'Tag'=>array(1,2,3,4),'Host'=>array(1,2,3,4),
		        			   'CMS'=>array(1,2,3,4),'Event'=>array(1,2,3,4),'Organizer'=>array(1,2,3,4),
		        			   'Checker'=>array(1,2,3,4),'Category'=>array(1,2,3,4),
		        			   'Venue'=>array(1,2,3,4),'Staff'=>array(1,2,3,4),'City'=>array(1,2,3,4),
		        			   'Customer'=>array(1,2,3,4),'Booking'=>array(1,2,3,4),
		        			   'Commission'=>array(1,2,3,4),'Notification'=>array(1,2,3,4),
		        			   'Settings'=>array(1,2,3,4),'Promocode'=>array(1,2,3,4),
		        			   'Country'=>array(1,2,3,4));
		        break;
		    case 2: 
		        $menus = array('Dashboard'=>array(1,2,3,4),'Tag'=>array(),'Host'=>array(1),
		        			   'City'=>array(),'Category'=>array(),'Venue'=>array(1,2,3,4),
		        			   'Event'=>array(1,2,3,4),'Checker'=>array(1,2,3,4),'Customer'=>array(),
		        			   'Booking'=>array(1,2,3,4),'Promocode'=>array(1,2,3,4));
		        break;
		    case 4: 
		        $menus = array('Dashboard'=>array(1,2,3,4),'Tag'=>array(1,2,3,4),'Host'=>array(1,2,3,4),
		        			   'City'=>array(1,2,3,4),'Category'=>array(1,2,3,4),'Venue'=>array(1,2,3,4),
		        			   'Event'=>array(1,2,3,4),'Checker'=>array(1,2,3,4),
		        			   'Organizer'=>array(1,2,3,4),'Customer'=>array(1,2,3,4),
		        			   'Booking'=>array(1,2,3,4),'Notification'=>array(1,2,3,4));
		        break;
		}
		return $menus;
	}

	function langTranslator($id='',$module='',$lngCode=''){
		$thisObj = & get_instance();
		if (empty($id) && empty($module)){
			return false;
		}
		$cond = '';
		$langArr = array();
		$orderBy = " ORDER BY CASE WHEN language_code LIKE 'EN' THEN 0 ELSE 1 END, language_code ASC ";

		if(!empty($lngCode)){
			$cond = "(language_code='$lngCode' OR language_code='EN') AND ";
		}

		switch($module) {
			case 'EVT':
				$cond   .= "event_id='$id'";
				$sql     = "SELECT * FROM translator_event WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$evtName = $evtDesc = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['event_name_'.$lang] = $langArr['event_description_'.$lang] = '';
					}
				} else {
					$langArr['event_name'] = $langArr['event_description'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$evtName = ($code=='en')?$data['event_name']:'';
					$evtDesc = ($code=='en')?$data['event_description']:'';

					$name    = (!empty($data['event_name']))?$data['event_name']:$evtName;
					$desc    = (!empty($data['event_description']))?$data['event_description']:$evtDesc;
					$langArr['event_name'.$code] = $name;
					$langArr['event_description'.$code] = $desc;
				}
				break;
			case 'VEN':
				$cond   .= "venue_id='$id'";
				$sql     = "SELECT * FROM translator_venue WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$venName = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['venue_name_'.$lang] = '';
					}
				} else {
					$langArr['venue_name'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$venName = ($code=='en')?$data['venue_name']:'';

					$name    = (!empty($data['venue_name']))?$data['venue_name']:$venName;
					$langArr['venue_name'.$code] = $name;
				}
				break;
			case 'CAT':
				$cond   .= "category_id='$id'";
				$sql     = "SELECT * FROM translator_category WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$catName = $catImage = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['category_name_'.$lang] = $langArr['category_image_'.$lang] = '';
					}
				} else {
					$langArr['category_name'] = $langArr['category_image'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$catName = ($code=='en')?$data['category_name']:'';
					$catImage= ($code=='en')?$data['category_image']:'';

					$name    = (!empty($data['category_name']))?$data['category_name']:$catName;
					$image   = (!empty($data['category_image']))?$data['category_image']:$catImage;
					$langArr['category_name'.$code] = $name;
					$langArr['category_image'.$code] = $image;
				}
				break;
			case 'LOC':
				$cond   .= "locality_id='$id'";
				$sql     = "SELECT * FROM translator_locality WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$locName = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['locality_name_'.$lang] = '';
					}
				} else {
					$langArr['locality_name'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$locName = ($code=='en')?$data['locality_name']:'';

					$name    = (!empty($data['locality_name']))?$data['locality_name']:$locName;
					$langArr['locality_name'.$code] = $name;
				}
				break;
			case 'REG':
				$cond   .= "region_id='$id'";
				$sql     = "SELECT * FROM translator_region WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$regName = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['region_name_'.$lang] = '';
					}
				} else {
					$langArr['region_name'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$regName = ($code=='en')?$data['region_name']:'';

					$name    = (!empty($data['region_name']))?$data['region_name']:$regName;
					$langArr['region_name'.$code] = $name;
				}
				break;
			case 'TAG':
				$cond   .= "tag_id='$id'";
				$sql     = "SELECT * FROM translator_tag WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$regName = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['tag_'.$lang] = '';
					}
				} else {
					$langArr['tag'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$regName = ($code=='en')?$data['tag']:'';

					$name    = (!empty($data['tag']))?$data['tag']:$regName;
					$langArr['tag'.$code] = $name;
				}
				break;
			case 'PROMO':
				$cond   .= "promocode_id='$id'";
				$sql     = "SELECT * FROM translator_promocode WHERE $cond $orderBy";
				$resp    = $thisObj->db->query($sql)->result_array();
				$promoDesc = $promoTc = '';
				if(empty($lngCode)){
					$languages = getLanguages();
					foreach ($languages AS $lang) {
						$langArr['promocode_tc_'.$lang] = $langArr['promocode_desc_'.$lang] = '';
					}
				} else {
					$langArr['promocode_tc'] = $langArr['promocode_desc'] = '';
				}
				foreach ($resp AS $data) {
					$code    = (empty($lngCode))?'_'.$data['language_code']:'';
					$promoDesc = $promoTc = '';
					if($code=='en'){
						$promoTc = $data['promocode_tc'];
						$promoDesc = $data['promocode_desc'];
					}

					$tc      = (!empty($data['promocode_tc']))?$data['promocode_tc']:$promoTc;
					$desc    = (!empty($data['promocode_desc']))?$data['promocode_desc']:$promoDesc;
					$langArr['promocode_tc'.$code] = $tc;
					$langArr['promocode_desc'.$code] = $desc;
				}
				break;
		}
		return $langArr;
	}

	function getLanguages(){
		$thisObj = & get_instance();
		$sql = "SELECT language_code FROM country WHERE status='1' GROUP BY language_code
				ORDER BY CASE WHEN language_code LIKE 'EN' THEN 0 ELSE 1 END, language_code ASC";
		$langData = $thisObj->db->query($sql);

		if(empty($langData) || empty($langData = $langData->result_array())){
			return array('EN');
		}
		$langArr = array();
		foreach ($langData AS $lang) {
			$langArr[] = $lang['language_code'];
		}
		return $langArr;
	}
?>