<?php 

class Organizer_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
 	}

  	public function getOrganizerEventList($data){
  		try {
 			$organizer_id = $data['organiser_id'];
			$count = $this->db->query("SELECT EVT.event_id FROM events AS EVT
				INNER JOIN translator_event AS TSEVT ON (EVT.event_id = TSEVT.event_id) 
 				INNER JOIN translator_venue AS TSVNE ON (EVT.venue_id = TSVNE.venue_id) 
 				INNER JOIN translator_category AS TSCAT ON (EVT.category_id = TSCAT.category_id)
 				INNER JOIN venue AS VNE ON (EVT.venue_id = VNE.id) 
				INNER JOIN translator_region AS TSREG ON (VNE.region_id = TSREG.region_id) 
				WHERE EVT.provider_id = '$organizer_id'AND TSEVT.language_code='EN' AND 
				      TSVNE.language_code='EN' AND TSCAT.language_code='EN' AND TSREG.language_code='EN' AND 
				      EVT.status IN ('0','1','3')")->num_rows();
			if($count > 0) {
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
						  'current_page'=>$page,'per_page'=>$perPage);
				$evtData = $this->db->query("SELECT TSEVT.event_id,TSEVT.event_name,TSVNE.venue_name AS venue,TSCAT.category_name AS category,TSREG.region_name AS region,EVT.status 
 				FROM events AS EVT 
 				INNER JOIN translator_event AS TSEVT ON (EVT.event_id = TSEVT.event_id) 
 				INNER JOIN translator_venue AS TSVNE ON (EVT.venue_id = TSVNE.venue_id) 
 				INNER JOIN translator_category AS TSCAT ON (EVT.category_id = TSCAT.category_id) 
 				INNER JOIN venue AS VNE ON (EVT.venue_id = VNE.id) 
 				INNER JOIN translator_region AS TSREG ON (VNE.region_id = TSREG.region_id) 
 				WHERE EVT.provider_id = $organizer_id AND TSEVT.language_code='EN' AND 
 					  TSVNE.language_code='EN' AND TSCAT.language_code='EN' AND TSREG.language_code='EN' AND 
 					  EVT.status IN ('0','1','3') 
		        ORDER BY EVT.event_id DESC
 				LIMIT $limit,$perPage");
	 			if(empty($evtData) || empty($evtData = $evtData->result_array())){
					$respArr['code'] = 980;
					$respArr['status'] = 0;
					$respArr['message'] = 'No Data Found';
					return $respArr; exit;
				}
				$resp = array('data'=>$evtData,'meta'=>$meta);
	 			$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
			}else{
	 			$res = array('status'=>0,'message'=>'No Data found','code'=>'ER06');
	 		}
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
  	}

  	public function event($data) {
 		try {
			$organizer_id = $data['organiser_id'];
			$this->db->query("SET SESSION group_concat_max_len = 20000");
 			$languages = getLanguages();
   			$sql = "SELECT EVT.has_payment,EVT.event_id,EVT.custom_seat_layout,
							EVT.seat_pricing,VNE.layout,VNE.layout_details,EVT.max_booking,
							VNE.location,VNE.location_lat AS lat,VNE.location_lng AS lng,VNE.id AS venue_id,
							GROUP_CONCAT(DISTINCT EVTG.tag_id) AS tag_ids,
							GROUP_CONCAT(DISTINCT CONCAT_WS('#',EVDT.id,EVDT.date,EVDT.time)) AS
							date_time,TSEVT.event_name,TSVNE.venue_name,TSREG.region_name
					FROM events AS EVT
					INNER JOIN event_date_time AS EVDT ON EVT.event_id = EVDT.event_id
					INNER JOIN translator_event AS TSEVT ON EVT.event_id = TSEVT.event_id
					INNER JOIN translator_venue AS TSVNE ON EVT.venue_id = TSVNE.venue_id
					INNER JOIN venue AS VNE ON VNE.id = EVT.venue_id
					INNER JOIN translator_region AS TSREG ON VNE.region_id = TSREG.region_id
					LEFT JOIN event_tags AS EVTG ON EVT.event_id=EVTG.event_id
					WHERE EVT.provider_id='$organizer_id' AND TSEVT.language_code='EN' AND 
						  TSVNE.language_code='EN' AND TSREG.language_code='EN' AND EVDT.status='1' AND 
						  EVT.event_id=".$data['event_id'];
			$result = $this->db->query($sql)->row();
			if(empty($result->event_id)){
				$res = array('status'=>0,'message'=>'No data Found','code'=>'ER06');
				return $res;
			}
			$resultData = array();
			$event_layout = $faretype ='';
			if($result->layout!=''){
				if($result->custom_seat_layout!=''){
					$event_layout = $pricelist = json_decode($result->custom_seat_layout, TRUE);
					$price = min(array_column($pricelist, 'price'));
					//$event_layout = json_decode($result->custom_seat_layout;
					$faretype = 2;
				} else {
					$event_layout  = $pricelist = json_decode($result->layout_details, TRUE);
					$price = min(array_column($pricelist, 'price'));
					//$event_layout = $result->layout_details;
					$faretype = 1;
				}
			} else {
				$event_layout = $pricelist = json_decode($result->seat_pricing, TRUE);
				$price = $pricelist['price'];
				//$event_layout = $result->seat_pricing;
				$priceArr = array();
				foreach ($languages as $lang) {
					if(!isset($event_layout['price_details_'.$lang])){
						continue;
					}
					$sql = "SELECT country_id AS lang_id,language_code AS lang,language FROM country WHERE status='1' AND language_code='$lang'";
					$langSql = $this->db->query($sql)->row_array();

					$desc=(!empty($event_layout['price_details_'.$lang]))?$event_layout['price_details_'.$lang]:'';
					$priceArr[] = array('lang'=>$lang,'desc'=>$desc,'language'=>$langSql['language'],'language_id'=>$langSql['lang_id']);
					unset($event_layout['price_details_'.$lang]);
				}
				$event_layout['about_price_division'] = $priceArr;
			}
			if($result->date_time != ''){
				$dates = explode(',', $result->date_time);
				$time_spec = array();
				$startDate = explode('#', $dates[0]);
				$endDate = explode('#', $dates[count($dates)-1]);
				foreach ($dates as $rss) {
					$timeArray = explode('#', $rss);
					if(strtotime($startDate[1]) == strtotime($timeArray[1])){
						$time_spec[] = $timeArray[2];
					}
				}
			}
			$tagArr  = array();
			$resData['scheduled_for'] = "";
			$resData['ticket_price'] = $price;
			if(isset($startDate) && !empty($startDate)){
				$resData['scheduled_for'] = ($startDate[1] == $endDate[1])?$startDate[1]:$startDate[1].' - '.$endDate[1];
			}
			$resData['show_timing'] = (isset($time_spec) && !empty($time_spec))?$time_spec:[];
			$resData['event_name'] =$result->event_name;
			$resData['event_name'] =$result->event_name;
			$resData['venue_region'] =$result->region_name;
			$resData['venue_name'] =$result->venue_name;
			$resData['location'] =$result->location;
			$resData['booking_limit'] = $result->max_booking;
			$resData['layout_type'] = (!empty($result->layout))?'1':'2';
			$resData['layout_pricing'] = $event_layout;
			if($resData['layout_type'] == '1'){
				$resData['layout_image'] = $result->layout;
				$resData['fare_type'] = $faretype;
			}
			if(!empty($result->tag_ids) && !empty($tag_ids = explode(',',$result->tag_ids))){
				foreach ($tag_ids AS $key => $id) {
					$tags = langTranslator($id,'TAG','EN');
					foreach ($tags AS $key => $id) {
						if(isset($tagArr[$key])){
							$tagArr[$key][] = $id;
						} else {
							$tagArr[$key] = array($id);
						}
					}
			 	} 
			} else {
				$tagArr = array('tag'=>array('0'=>'tag_EN'));
			}
			$resData = array_merge($resData,$tagArr);
			$res = array('status'=>1,'data'=>$resData);
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}

 	public function editOrganizerEventDetails($postData){
 		try{
 			ini_set("memory_limit","-1");
 			set_time_limit(0);
 			$languages = getLanguages();
 			$postData['seat_pricing'] = $postData['custom_seat_layout'] = '';
	        if(isset($postData['layout_type'],$postData['fare_type']) && $postData['layout_type'] == 1 && $postData['fare_type'] == 2 && isset($postData['layout'])){
	            $postData['custom_seat_layout'] = $postData['layout'];
	        } else if($postData['layout_type'] == 2) {
	            $postData['seat_pricing'] =  $postData['layout'];
	        }
	        $eventData = array('venue_id'=>(isset($postData['venue_id']) && !empty($postData['venue_id']))?$postData['venue_id']:'',
	                           'category_id'=>(isset($postData['category_id']) && !empty($postData['category_id']))?$postData['category_id']:'',
	                           'provider_id'=>(isset($postData['organiser_id']) && !empty($postData['organiser_id']))?$postData['organiser_id']:'',
	                           'max_booking'=>(isset($postData['maximum_seat_booking']) && !empty($postData['maximum_seat_booking']))?$postData['maximum_seat_booking']:'',
	                           'has_payment'=>(isset($postData['payment_mode']))?$postData['payment_mode']:'',
	                           'seat_pricing'=>(isset($postData['seat_pricing']) && !empty($postData['seat_pricing']))?json_encode($postData['seat_pricing']):'',
	                           'custom_seat_layout'=>(isset($postData['custom_seat_layout']) && !empty($postData['custom_seat_layout']))?json_encode($postData['custom_seat_layout']):'',
	                           'approve_booking'=>$postData['approve_booking'],
	                       	   'status'=>3);
	 		$evtName = (!empty($postData['event_name']))?$postData['event_name']:'';
	 		$evtDesc = (!empty($postData['event_desc']))?$postData['event_desc']:'';
	        $status = $this->db->update('events',$eventData,array('event_id'=>$postData['event_id']));
	 		if($status && ($evtName != '' && $evtDesc != '')){
		 		if(!empty($languages)){
		 			$insertArr = $languageArr = array();
		 			foreach ($languages AS $lang) {
	 					foreach ($evtName as $evkey => $evvalue) {
	 						if($lang == $evvalue->lang){
	 							$languageArr[$lang]['event_name'] = $evvalue->event_name;
	 						}
	 					}
	 					foreach ($evtDesc as $desckey => $descvalue) {
 							if($lang == $descvalue->lang){
	 							$languageArr[$lang]['event_desc'] = $descvalue->event_desc;
	 						}
 						}	
		 			}
		 			foreach ($languages AS $lang) {
		 				if(!isset($languageArr[$lang]) || (empty($languageArr[$lang]['event_name']) && 
		 				   empty($languageArr[$lang]['event_desc']))){
		 					continue;
		 				}
		 				$eName = (isset($languageArr[$lang]['event_name']) && !empty($languageArr[$lang]['event_name']))?$languageArr[$lang]['event_name']:'';
		 				$eDesc = (isset($languageArr[$lang]['event_desc']) && !empty($languageArr[$lang]['event_desc']))?$languageArr[$lang]['event_desc']:'';
		 				$insertArr[] = array('event_id'=>$postData['event_id'],'event_name'=>$eName,
		 									 'event_description'=>$eDesc,'language_code'=>$lang);
		 			}
		 			if(!empty($insertArr)){
		 				$this->db->delete('translator_event',array('event_id'=>$postData['event_id']));
		 				$this->db->insert_batch('translator_event',$insertArr);
		 			}
		 		}
	 		}
	        if(!empty($postData['event_id'])){
	            $insertEventDate = array();
	            if(isset($postData['show_type']) && !empty($postData['show_type'])){
		            $this->db->update('event_date_time',array('status'=>'0'),
							   array('status'=>'1','event_id'=>$postData['event_id']));
		            $showTiming = is_array($postData['show_timing'])?$postData['show_timing']:json_decode($postData['show_timing']);
	            	if($postData['show_type'] == 1){
		                $date = $postData['start_date'];
		                foreach ($showTiming AS $time) {
		                    $insertEventDate[] = array('event_id'=>$postData['event_id'],'date'=>$date,'time'=>$time);
		                }
		            } else {
		                $cdate = strtotime($postData['start_date']);
		                while ($cdate <= strtotime($postData['end_date'])) {
		                    $cdate = date('Y-m-d',$cdate);
		                    foreach ($showTiming AS $time) {
		                        $insertEventDate[] = array('event_id'=>$postData['event_id'],'date'=>$cdate,'time'=>$time);
		                    }
		                    $cdate = strtotime($cdate . ' +1 day');
		                }
		            }
		            $this->db->insert_batch('event_date_time',$insertEventDate);
	            }
	            $insertTag = array();
	            if(isset($postData['tag']) && !empty($postData['tag'])){
		            foreach ($postData['tag'] AS $tag) {
		                $insertTag[] = array('event_id'=>$postData['event_id'],'tag_id'=>$tag);
		            }
		            $this->db->delete('event_tags',array('event_id'=>$postData['event_id']));
		            $this->db->insert_batch('event_tags',$insertTag);
	            }
	        }
	        $res = array('status'=>1,'message'=>'Event Updated Successfully');
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
 		}
 		return $res;
 	}

 	public function changeOrganizerEventStatus($data,$status=''){
 		try{
 			$count = $this->db->get_where('events',array('event_id'=>$data['event_id']))->num_rows();
 			if($count < 1){
 				$res = array('status'=>0,'message'=>'Event Doesnot Exist','code'=>'ER05');
 				return $res;
 			}
 			if($this->db->update('events',array('status'=>$status),array('event_id'=>$data['event_id'],'provider_id'=>$data['organiser_id']))){
 				$evStatus = ($status == 0)?'Deactivated':'Activated';
 				$res = array('status'=>1,'message'=>($status == 2)?'Event Deleted Successfully':'Event '.$evStatus.' Successfully');
 			}
 		} catch(Exception $e){
 			$res = array('status'=>'0','message'=>'Ohh No!! Something Went South!!','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getVenueList($data){
 		try{
 			$cond = " VNE.status != '2'";
 			if(isset($data['status']) && !empty($data['status']) && 
 			   empty($status = implode(',', $data['status']))){
	 			$cond  = " VNE.status IN (".$status.")";
 			}
 			if(isset($data['organiser_id']) && !empty($data['organiser_id'])){
 				$cond .= (!empty($cond))?" AND":"";
 				$cond .= " VNE.provider_id='".$data['organiser_id']."' ";
 			}
		 	
 			$count = $this->db->query("SELECT * FROM venue AS VNE WHERE $cond ")->num_rows();
 			if($count > 0) {
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
						  'current_page'=>$page,'per_page'=>$perPage);


		 		$sql = "SELECT VNE.id AS venue_id,VNE.location AS venue_location,VNE.region_id,HST.host_category,HST.show_layout,VNE.status
		 				FROM venue AS VNE
		 				INNER JOIN host_categories AS HST ON (HST.host_cat_id=VNE.host_cat_id)
		 				WHERE $cond LIMIT $limit,$perPage";
		 		$venueData = $this->db->query($sql);
		 		if(empty($venueData) || empty($venueData = $venueData->result_array())){
		 			$res =array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
		 			return $res;
		 		}
	 			foreach ($venueData AS $key => $data) {
	 				$rtlData = langTranslator($data['venue_id'],'VEN','EN');
					$venueData[$key]['venue_name'] = $rtlData['venue_name'];
	 				$rtlData = langTranslator($data['region_id'],'REG','EN');
					$venueData[$key]['venue_region'] = $rtlData['region_name'];
					unset($venueData[$key]['region_id']);
	 			}
	 			$res = array('status'=>1,'message'=>'Successfully','data'=>array('data'=>$venueData,'meta'=>$meta));
	 		}else{
	 			$res = array('status'=>0,'message'=>'No Data found','code'=>'ER06');
	 		}
 		} catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getVenueDetails($data){
 		try{
 			$cond  = (!empty($view))?" VNE.status IN ($view) ":" VNE.status != '2' ";
	 		$cond .= (!empty($data['venue_id']))?" AND VNE.id='".$data['venue_id']."' ":"";
	 		$cond .= (!empty($data['organiser_id']))?" AND VNE.provider_id='".$data['organiser_id']."' ":"";

	 		$sql = "SELECT VNE.id AS venue_id,VNE.layout AS venue_images,VNE.layout_details AS seat_block,
	 				VNE.region_id AS venue_region_id,VNE.location AS venue_location,
	 				HST.host_cat_id AS host_category_id,HST.host_category,VNE.location_lat,VNE.location_lng
	 				FROM venue AS VNE
	 				INNER JOIN host_categories AS HST ON (HST.host_cat_id=VNE.host_cat_id)
	 				WHERE $cond";
	 		$venueData = $this->db->query($sql);
	 		if(empty($venueData) || empty($venueData = $venueData->row_array())){
	 			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
	 			return $res;
	 		}

	 		$sql = "SELECT TLOC.id,TLOC.locality_name AS locality_name
					FROM locality AS LOC 
					INNER JOIN translator_locality AS TLOC ON (TLOC.locality_id = LOC.id)
					WHERE TLOC.language_code='EN' AND LOC.region_id = '".$venueData['venue_region_id']."' AND 
						  LOC.status = '1'";
			$venueData['locality'] = $this->db->query($sql)->result_array();

	 		$sql = "SELECT TVEN.venue_name AS name,TVEN.language_code AS lang
					FROM venue AS VEN 
					INNER JOIN translator_venue AS TVEN ON (TVEN.venue_id = VEN.id)
					WHERE VEN.id = '".$venueData['venue_id']."'";
			$venueData['venue_names'] = $this->db->query($sql)->result_array();

			$venueData['layout_type'] = (!empty($venueData['venue_images']))?'1':'2';
			$rtlData = langTranslator($venueData['venue_id'],'VEN','EN');
			$venueData['venue_name'] = $rtlData['venue_name'];
			$rtlData = langTranslator($venueData['venue_region_id'],'REG','EN');
			$venueData['venue_region'] = $rtlData['region_name'];
	 		$res = array('status'=>1,'data'=>$venueData);
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getCustomerList($data){
 		try{
 			$provider_id = $data['organiser_id'];
 			$count = $this->db->query("SELECT BUK.customer_id FROM  booking AS BUK INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) WHERE EVT.provider_id ='$provider_id' GROUP BY BUK.customer_id")->num_rows();
 			if($count > 0) {
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
						  'current_page'=>$page,'per_page'=>$perPage);

	 			$sql = "SELECT BUK.customer_id,CUST.name AS customer_name,CUST.email,CUST.phone,CASE WHEN CUST.gender ='1' THEN 'male' WHEN CUST.gender='2' THEN 'female' ELSE 'others' END AS gender,CUST.profile_image AS image,CUST.city FROM booking AS BUK INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) INNER JOIN customer AS CUST ON (CUST.customer_id = BUK.customer_id) WHERE EVT.provider_id ='$provider_id' GROUP BY BUK.customer_id LIMIT $limit,$perPage";
	 			$custData = $this->db->query($sql)->result_array();
	 			$res = array('status'=>1,'data'=>array('data'=>$custData,'meta'=>$meta));
	 		}else{
	 			$res = array('status'=>0,'message'=>'No Data found','code'=>'ER06');
	 		}
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getBookingList($data){
 		try{
 			$provider_id = $data['organiser_id'];
 			$this->db->query("SET SESSION group_concat_max_len = 20000");
 			$count = $this->db->query("SELECT BUK.id FROM  booking AS BUK INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) INNER JOIN translator_event AS TSEVT ON (EVT.event_id = TSEVT.event_id)INNER JOIN translator_category AS TSCAT ON (EVT.category_id = TSCAT.category_id)  WHERE EVT.provider_id ='$provider_id' AND TSEVT.language_code='EN' AND TSCAT.language_code='EN' AND BUK.status !='4' GROUP BY BUK.id")->num_rows();
 			if($count > 0) {
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
						  'current_page'=>$page,'per_page'=>$perPage);

	 			$sql = "SELECT TSEVT.event_id,TSEVT.event_name,BUK.bookId,TSCAT.category_name,BUK.amount,BUK.status,CUST.name AS customer_name,EVDT.date AS scheduled_date,EVDT.time AS scheduled_time 
	 			FROM booking AS BUK 
	 			INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) 
	 			INNER JOIN translator_event AS TSEVT ON (EVT.event_id = TSEVT.event_id) 
	 			INNER JOIN translator_category AS TSCAT ON (EVT.category_id = TSCAT.category_id) 
	 			INNER JOIN customer AS CUST ON (CUST.customer_id = BUK.customer_id) 
	 			INNER JOIN event_date_time AS EVDT ON (BUK.event_date_id = EVDT.id) 
	 			WHERE EVT.provider_id ='$provider_id' AND TSEVT.language_code='EN' AND TSCAT.language_code='EN' AND BUK.status !='4'
	 			GROUP BY BUK.id ORDER BY BUK.id DESC
	 			LIMIT $limit,$perPage";
	 			$custData = $this->db->query($sql)->result_array();
	 			$res = array('status'=>1,'data'=>array('data'=>$custData,'meta'=>$meta));
	 		}else{
	 			$res = array('status'=>0,'message'=>'No Data found','code'=>'ER06');
	 		}
 		} catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getBookingDetails($data){
 		try{
 			$this->db->query("SET SESSION group_concat_max_len = 20000");
 			$sql = "SELECT BUK.ticket_details,CASE WHEN BUK.reserved_by='1' THEN 'Admin' WHEN BUK.reserved_by='2' THEN 'Provider' ELSE 'Customer' END AS reserved_by,TSEVT.event_name,TSEVT.event_description,BUK.bookId,TSCAT.category_name,CUST.name AS customer_name,CUST.email,CUST.phone AS customer_phone_no,PDR.name AS provider_name,PDR.email AS provider_email,PDR.phone AS provider_phone_no,VNE.location AS venue_address,TSVNE.venue_name,BUK.no_of_ticket,BUK.amount,BUK.status AS booking_status,EVDT.date AS scheduled_date,EVDT.time AS scheduled_time,BUK.qrcode 
 				FROM booking AS BUK  
 				INNER JOIN customer AS CUST ON (CUST.customer_id = BUK.customer_id)  
 				INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) 
 				INNER JOIN translator_event AS TSEVT ON (TSEVT.event_id = BUK.event_id) 
 				INNER JOIN translator_category AS TSCAT ON (TSCAT.category_id = EVT.category_id) 
 				LEFT JOIN provider AS PDR ON (PDR.provider_id = EVT.provider_id) 
 				INNER JOIN translator_venue AS TSVNE ON (TSVNE.venue_id = EVT.venue_id) 
 				INNER JOIN event_date_time AS EVDT ON (BUK.event_date_id = EVDT.id)
 				INNER JOIN venue AS VNE ON (VNE.id = EVT.venue_id) 
 				WHERE BUK.bookId='".$data['booking_id']."'";
 			$query = $this->db->query($sql);
 			if(empty($query) || empty($query= $query->row_array())){
 				$res= array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 				return $res; exit;
 			}
 			$query['ticket_details'] = (!empty($query['ticket_details']))?json_decode($query['ticket_details']):[];
			$res = array('status'=>1,'data'=>$query);
 		} catch (Exception $e){
 			$res= array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function organiserSignUp($data){
 		try{
 			$userNameChk = $this->db->query("SELECT * FROM users 
 									     	 WHERE user_type='2' AND status!='2' AND 
 									     		   username='".$data['username']."'");
	 		if(!empty($userNameChk) && $userNameChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Username Already Exist','code'=>'ER07');
	 			return $res;
	 		}
	 		$emailChk = $this->db->query("SELECT * FROM provider AS PRV 
	 									  INNER JOIN users AS USR ON (USR.id=PRV.provider_id)
									      WHERE USR.user_type='2' AND USR.status!='2' AND 
									      		PRV.email='".$data['email_id']."'");
	 		if(!empty($emailChk) && $emailChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Email Id Already Exist','code'=>'ER08');
	 			return $res;
	 		}	
 			$data['contact_no'] = preg_replace('/\D/', '', $data['contact_no']);
	 		$phoneChk = $this->db->query("SELECT * FROM provider AS PRV 
	 									  INNER JOIN users AS USR ON (USR.id=PRV.provider_id)
										  WHERE USR.user_type='2' AND USR.status!='2' AND 
										  	    PRV.phone='".$data['contact_no']."'");
	 		if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Phone Number Already Exist','code'=>'ER09');
	 			return $res;
	 		}			
			$this->db->insert('users',array('username'=>$data['username'],'display_name'=>$data['username'],
							  'password'=>md5($data['password']),'user_type'=>'2','status'=>'3'));
 			$last_id = $this->db->insert_id();
 			if($this->db->insert('provider',array('provider_id'=>$last_id,'name'=>$data['username'],
 												  'email'=>$data['email_id'],'phone'=>$data['contact_no']))){
 				$res = array('status'=>1,'message'=>'Registered Successfully');	
 			}
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function signIn($data){
 		try{
 			if($data['user_type'] == '2'){
 				$sql = $this->db->query("SELECT USR.* FROM users AS USR 
 										 INNER JOIN provider AS PDR ON (PDR.provider_id = USR.id) 
 										 WHERE USR.password='".md5($data['password'])."' AND 
 										       ( PDR.email='".$data['email_id']."' OR USR.username='".$data['email_id']."') AND 
 										       USR.user_type='".$data['user_type']."' AND 
 										       USR.status='1'");
 			}else{
 				$sql = $this->db->query("SELECT * FROM checker WHERE username='".$data['email_id']."' AND password='".md5($data['password'])."' AND status='1'");
 			}
 			if(empty($sql) || empty($custData = $sql->row_array())){
 				$res = array('status'=>0,'message'=>'User Does not Exist','code'=>'ER09');
 				return $res;
 			}
 			$this->db->update('provider',array('fcm_token'=>$data['fcm_token']),array('provider_id'=>$custData['id']));
 			$res = array('status'=>1,'message'=>'Logged In Successfully','data'=>$custData['id']);
 		} catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changePassword($data){
 		try{
 			if($data['new_password'] != $data['confirm_password']){
 				$res = array('status'=>0,'message'=>'New Password and Confirm Password Doesnot Match','code'=>'ER10');
 				return $res;
 			}
 			$sql = "SELECT * FROM provider AS PDR 
 					INNER JOIN users AS USR ON (USR.id=PDR.provider_id) 
 					WHERE phone LIKE '%".$data['phone_number']."' AND 
 						  USR.user_type='2' AND USR.status='1'";
 			$usrData = $this->db->query($sql);
 			if(empty($usrData) || empty($usrData = $usrData->row_array())){
 				$res = array('status'=>0,'message'=>'Provider Doesnot Exist','code'=>'ER08');
 				return $res;
 			}
 			$sql = "UPDATE users SET password='".md5($data['confirm_password'])."' 
 					WHERE id='".$usrData['provider_id']."' AND user_type='".$data['user_type']."'";
			$status = $this->db->query($sql);
 			if($status){
				$res = array('status'=>1,'message'=>'Password Updated Successfully');
 			}
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function checkerDeactivate($data,$status =''){
 		try{
 			if($this->db->update('checker',array('status'=>$status),array('id'=>$data['checker_id'],'provider_id'=>$data['organiser_id']))){
 				$res = array('status'=>1,'message'=>($status == 0)?'Checker Deactivated':'Checker Activated');
 			}
 		} catch (Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getTagList($data) {
 		try {
			$organizer_id = $data['organiser_id'];
			$status = implode(',', $data['status']);
			$count = $this->db->query("SELECT tag_id AS id,status FROM tags WHERE status IN (".$status.")")->num_rows();
			if($count > 0){
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
							  'current_page'=>$page,'per_page'=>$perPage);
		 		$tagData = $this->db->query("SELECT tag_id AS id,status FROM tags WHERE status IN (".$status.") LIMIT $limit,$perPage");
		 		if(empty($tagData) || empty($tagData = $tagData->result_array())){
		 			$res = array('status'=>0,'message'=>'No data Found','code'=>'ER09');
		 			return $res;
		 		}
	 			foreach ($tagData AS $key => $data) {
	 				$rtlData = langTranslator($data['id'],'TAG','EN');
					$tagData[$key]['tag_name'] = $rtlData['tag'];
	 			}
				$res = array('status'=>1,'data'=>array('data'=>$tagData,'meta'=>$meta));
			}
	
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}

 	public function addEvent($postData){
 		try{
 			ini_set("memory_limit", "-1");
	        set_time_limit(0);
	        $languages = getLanguages();
			$err = 0;
	        $postData['seat_pricing'] = $postData['custom_seat_layout'] = '';
	        if(isset($postData['layout_type'],$postData['fare_type']) && $postData['layout_type'] == 1 && $postData['fare_type'] == 2){
	            $postData['custom_seat_layout'] = $postData['layout'];
	        } else if($postData['layout_type'] == 2){
	            $postData['seat_pricing'] =  $postData['layout'];
	        }
	        $eventData = array('venue_id'=>$postData['venue_id'],
	                           'category_id'=>$postData['category_id'],
	                           'provider_id'=>$postData['organiser_id'],
	                           'max_booking'=>$postData['maximum_seat_booking'],
	                           'has_payment'=>$postData['payment_mode'],
	                           'seat_pricing'=>$postData['seat_pricing'],
	                           'custom_seat_layout'=>$postData['custom_seat_layout'],
	                           'approve_booking'=>$postData['approve_booking'],
	                       	   'status'=>3);
	 		$evtName = json_decode($postData['event_name'],true);
	 		$evtDesc = json_decode($postData['event_desc'],true);
	        $status = $this->db->insert('events',$eventData);
	 		if($status){
	 			$event_id = $this->db->insert_id();
		 		if(!empty($languages)){
		 			$insertArr = $languageArr = array();
		 			foreach ($languages AS $lang) {
	 					foreach ($evtName as $evkey => $evvalue) {
	 						if($lang == $evvalue['lang']){
	 							$languageArr[$lang]['event_name'] = $evvalue['event_name'];
	 						}
	 					}
	 					foreach ($evtDesc as $desckey => $descvalue) {
 							if($lang == $descvalue['lang']){
	 							$languageArr[$lang]['event_desc'] = $descvalue['event_desc'];
	 						}
 						}	
		 			}
		 			foreach ($languages AS $lang) {
		 				if(!isset($languageArr[$lang]) || (empty($languageArr[$lang]['event_name']) && 
		 				   empty($languageArr[$lang]['event_desc']))){
		 					continue;
		 				}
		 				$eName = (isset($languageArr[$lang]['event_name']) && !empty($languageArr[$lang]['event_name']))?$languageArr[$lang]['event_name']:'';
		 				$eDesc = (isset($languageArr[$lang]['event_desc']) && !empty($languageArr[$lang]['event_desc']))?$languageArr[$lang]['event_desc']:'';
		 				$insertArr[] = array('event_id'=>$event_id,'event_name'=>$eName,
		 									 'event_description'=>$eDesc,'language_code'=>$lang);
		 			}
		 			if(!empty($insertArr)){
		 				$this->db->insert_batch('translator_event',$insertArr);
		 			}
		 		}
	 		}
	        if(!empty($event_id)){
	            $insertEventDate = array();
	            if(isset($postData['show_type']) && $postData['show_type'] == 1){
	                $date = $postData['start_date'];
	                foreach (json_decode($postData['show_timing']) AS $time) {
	                    $insertEventDate[] = array('event_id'=>$event_id,'date'=>$date,'time'=>$time);
	                }
	            } else {
	                $cdate = strtotime($postData['start_date']);
	                while ($cdate <= strtotime($postData['end_date'])) {
	                    $cdate = date('Y-m-d',$cdate);
	                    foreach (json_decode($postData['show_timing']) AS $time) {
	                        $insertEventDate[] = array('event_id'=>$event_id,'date'=>$cdate,'time'=>$time);
	                    }
	                    $cdate = strtotime($cdate . ' +1 day');
	                }
	            }
	            $this->db->insert_batch('event_date_time',$insertEventDate);
	            $insertTag = array();
	            foreach (json_decode($postData['tag']) AS $tag) {
	                $insertTag[] = array('event_id'=>$event_id,'tag_id'=>$tag);
	            }
	            $this->db->insert_batch('event_tags',$insertTag);
	            if(isset($_FILES) && isset($_FILES['images']) && 
	               isset($_FILES['images']['name']) && count($_FILES['images']['name'])>=1){
	                $resp = $this->eventImageUpload($event_id,$_FILES);
	                $evtMediaData = (isset($resp['evtMediaData']))?$resp['evtMediaData']:array();
	                $errorMediaFiles = (isset($resp['errorMediaFiles']))?$resp['errorMediaFiles']:array();
	                $this->db->insert_batch('event_gallery',$evtMediaData);
	            }
	        }
	        $res = array('status'=>1,'message'=>'Event Added Successfully');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
 		}
 		return $res;
 	}

 	public function eventImageUpload($eId = '', $files = array(), $mTyp='0'){
        if(empty($eId) || empty($files)){
            return false;
        }
        $evtMediaData = array();
        $errorMediaFiles = array();
        $this->load->library('upload');
        $bPath = "assets/uploads/services/";
        $config = set_upload_service("assets/uploads/services");
        for($typ = 0; $typ < count($files['images']['name']); $typ++) { 
            $_FILES['file']['name'] = $files['images']['name'][$typ];
            $_FILES['file']['type'] = $files['images']['type'][$typ];
            $_FILES['file']['size'] = $files['images']['size'][$typ]; 
            $_FILES['file']['error'] = $files['images']['error'][$typ];
            $_FILES['file']['tmp_name'] = $files['images']['tmp_name'][$typ];

            $extn = substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.')+1);
            $file = date('YmdHis').gettimeofday()['usec']."_EVT_IMG.".$extn;
            $config['file_name'] = $file;

            $this->upload->initialize($config);
            if($this->upload->do_upload('file')){
                $iDat = $this->upload->data();
                $path = $bPath.$iDat['file_name'];
                if($extn != 'gif'){
                    $size  = array('width'=>'720','height'=>'480');
                    $tFile = date('YmdHis').gettimeofday()['usec'].'_EVT_IMG_720x480.'.$extn;
                    $resp  = $this->imageResize($tFile,$size,$path);
                    if($resp['status'] == '1'){
                        $file = $tFile;
                        unlink($path);
                        $path = $bPath.$tFile;
                    }
                }
                $imgSafety = $this->googleVisionApi(base_url($file));
                if($imgSafety == 1){
                    $evtMediaData[] = array('event_id'=>$eId,'media_type'=>$mTyp,'media_url'=>$path);
                    $mTyp = '1';
                } 
                else if ($imgSafety == 2) {
                    $errorMediaFiles[] = $_FILES['file']['name'];
                }
            } else {
                $errorMediaFiles[] = $_FILES['file']['name'];
            }
        }
        return array('evtMediaData'=>$evtMediaData,'errorMediaFiles'=>$errorMediaFiles);
    }

    public function imageResize($newImage,$size,$path){
        $this->load->library('image_lib');
        $config['width']          = $size['width'];
        $config['height']         = $size['height'];
        $config['new_image']      = $newImage;
        $config['source_image']   = $path;
        $config['create_thumb']   = FALSE;
        $config['image_library']  = 'gd2';
        $config['maintain_ratio'] = TRUE;
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();
        $res = array('status'=>'1');
        if(!$this->image_lib->resize()){
            $res['status'] = '0';
            $res['error'] = $this->image_lib->display_errors();
        }
        return $res;
    }
    
    public function googleVisionApi($img='', $typ='SAFE_SEARCH_DETECTION'){
        if(empty($img)){
            return 0;
        }
        $settings = getSettings();
        $api = $settings['google_api_key'];
        $url = "https://vision.googleapis.com/v1/images:annotate?key=".$api;
        $req = "{'requests':[{'image':{'source':{'imageUri':'$img'}},'features':[{'type':'$typ'}]}]}";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$req);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $resp = curl_exec($ch);
        curl_close ($ch);

        $safe = 1;
        if(!empty($resp) && !empty($resp = json_decode($resp,true)) && isset($resp['responses']) && 
           isset($resp['responses'][0]) && isset($resp['responses'][0]['safeSearchAnnotation'])){
            $resp = $resp['responses'][0]['safeSearchAnnotation'];
            
            if($resp['adult']=='Very Likely'||$resp['adult']=='Likely'||$resp['adult']=='Possible'){
                $safe = 2;
            }
            if($resp['spoof']=='Very Likely'||$resp['spoof']=='Likely'){
                $safe = 2;
            }
            if($resp['medical']=='Very Likely'||$resp['medical']=='Likely'){
                $safe = 2;
            }
            if($resp['violence']=='Very Likely'||$resp['violence']=='Likely'){
                $safe = 2;
            }
            if($resp['racy']=='Very Likely'||$resp['racy']=='Likely'||$resp['racy']=='Possible'){
                $safe = 2;
            }
        }
        return $safe;
    }

    public function getLanguages(){
    	try{
    		$sql = "SELECT country_id AS lang_id,language,language_code AS lang,country_name,country_code FROM country WHERE status='1' GROUP BY language ORDER BY language_code ASC";
    		$lang = $this->db->query($sql);
    		if(empty($lang) || empty($lang = $lang->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER05');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'Language Listed Successfully','data'=>$lang);
    	} catch(Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function getCategories(){
    	try{
    		$sql = "SELECT category_id AS cat_id,category_name AS cat_name FROM translator_category WHERE language_code='EN'";
    		$category = $this->db->query($sql);
    		if(empty($category) || empty($category = $category->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'Categories Listed Successfully','data'=>$category);
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function searchEvent($data){
    	try{
    		$sql = "SELECT TESVT.event_id,TSEVT.event_name,EVT.venue_id,EVT.category_id,EVT.status,VNE.region_id 
		    		FROM events AS EVT 
		    		INNER JOIN venue AS VNE ON (VNE.id = EVT.venue_id) 
		    		INNER JOIN translator_event AS TSEVT ON (TSEVT.event_id = EVT.event_id) 
		    		WHERE EVT.provider_id='".$data['organiser_id']."' AND TSEVT.event_name LIKE '%".$data['keyword']."%' AND TSEVT.language_code='EN'";
    		$evtData  = $this->db->query($sql);
    		if(empty($evtData) || empty($evtData = $evtData->result_array())){
    			$res = array('status'=>0,'message'=>'No data Found','code'=>'ER08');
    			return $res;
    		} 
    		foreach ($evtData as $key => $value) {
    			$trsData = langTranslator($value['venue_id'],'VEN','EN');
    			$evtData[$key]['venue'] = $trsData['venue_name'];
    			$trsData = langTranslator($value['category_id'],'CAT','EN');
    			$evtData[$key]['category'] = $trsData['category_name'];
    			$trsData = langTranslator($value['region_id'],'REG','EN');
    			$evtData[$key]['region'] = $trsData['region_name'];
    			unset($evtData[$key]['region_id'],$evtData[$key]['category_id'],$evtData[$key]['venue_id']);
    		}
    		$res = array('status'=>1,'message'=>'Search Successfully','data'=>$evtData);
    	} catch(Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function searchCustomer($data){
    	try{
    		$sql = "SELECT CUST.customer_id,CUST.name AS customer_name,CUST.email,CUST.phone,CUST.gender,CUST.city,CUST.profile_image AS image 
		    		FROM events AS EVT 
		    		INNER JOIN booking AS BUK ON (BUK.event_id = EVT.event_id) 
		    		INNER JOIN customer AS CUST ON (CUST.customer_id = BUK.customer_id) 
		    		WHERE EVT.provider_id='".$data['organiser_id']."' AND CUST.name LIKE '%".$data['keyword']."%' GROUP BY BUK.customer_id";
    		$custData = $this->db->query($sql);
    		if(empty($custData) || empty($custData = $custData->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'Search Successfull','data'=>$custData);
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function searchBooking($data){
    	try{
    		$sql = "SELECT TSEVT.event_id,TSEVT.event_name,BUK.bookId,TSCAT.category_name AS category,BUK.status,BUK.amount,CUST.name AS customer_name,EVDT.date AS scheduled_date, EVDT.time AS scheduled_time 
		    		FROM booking AS BUK 
		    		INNER JOIN events AS EVT ON (EVT.event_id = BUK.event_id) 
		    		INNER JOIN translator_event AS TSEVT ON (TSEVT.event_id = EVT.event_id) 
		    		INNER JOIN translator_category AS TSCAT ON (TSCAT.category_id = EVT.category_id) 
		    		INNER JOIN customer AS CUST ON (CUST.customer_id = BUK.customer_id) 
		    		INNER JOIN event_date_time AS EVDT ON (EVDT.id = BUK.event_date_id) 
		    		WHERE EVT.provider_id='".$data['organiser_id']."' AND TSEVT.event_name LIKE '%".$data['keyword']."%' AND TSEVT.language_code='EN' GROUP BY EVT.event_id";
    		$bookData = $this->db->query($sql);
    		if(empty($bookData) || empty($bookData = $bookData->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'Search Successfull','data'=>$bookData);
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function searchChecker($data){
    	try{
    		$sql = "SELECT CHKR.username AS checker_name,CHKR.id AS checker_id,CHKR.status,PDR.name AS provider FROM checker AS CHKR INNER JOIN provider AS PDR ON (PDR.provider_id = CHKR.provider_id) WHERE CHKR.username LIKE '%".$data['keyword']."%' AND CHKR.provider_id='".$data['organiser_id']."'";
    		$chkrData = $this->db->query($sql);
    		if(empty($chkrData) || empty($chkrData = $chkrData->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'Search Successfull','data'=>$chkrData);
    	} catch(Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function getCountryCode(){
    	try{
    		$sql = "SELECT DISTINCT phone_code,country_id,country_name,country_code FROM country WHERE status=1 GROUP BY phone_code";
    		$ctryData = $this->db->query($sql);
    		if(empty($ctryData) || empty($ctryData = $ctryData->result_array())){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$res = array('status'=>1,'message'=>'CountryCode Listed Successfully','data'=>$ctryData);
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER08');
    	}
    	return $res;
    } 

    public function getCheckerList($data){
    	try{
    		$count = $this->db->query("SELECT id FROM checker AS CHKR WHERE CHKR.status IN('0','1') AND CHKR.provider_id = '".$data['organiser_id']."'")->num_rows();
			if($count > 0) {
				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
						  'current_page'=>$page,'per_page'=>$perPage);
    			$sql = "SELECT CHKR.username AS checker_name,CHKR.id AS checker_id,PDR.name AS provider,CHKR.status FROM checker AS CHKR INNER JOIN provider AS PDR ON (PDR.provider_id = CHKR.provider_id) WHERE CHKR.status IN('0','1') AND CHKR.provider_id ='".$data['organiser_id']."' LIMIT $limit,$perPage";
    			$chkrData = $this->db->query($sql);
    			if(empty($chkrData) || empty($chkrData = $chkrData->result_array())){
    				$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    				return $res;
    			}
    			$res = array('status'=>1,'message'=>'Checkers Listed Successfully','data'=>array('data'=>$chkrData,'meta'=>$meta));
			}else{
				$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
			}
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function getEvent($data){
    	try{
    		$sql = "SELECT EVT.venue_id,EVT.category_id,EVT.max_booking AS max_seat_booking,
    					   EVT.has_payment AS payment_mode,
    					   GROUP_CONCAT(DISTINCT EVTG.tag_id) AS tags,
    					   GROUP_CONCAT(DISTINCT CONCAT_WS('#',EVDT.id,EVDT.date,EVDT.time)) AS date_time,
    					   EVT.custom_seat_layout,EVT.seat_pricing,VNE.layout,
    					   VNE.layout_details AS layoutDetails FROM events AS EVT 
	    			INNER JOIN event_date_time AS EVDT ON EVT.event_id = EVDT.event_id
	    			INNER JOIN venue AS VNE ON EVT.venue_id = VNE.id
					LEFT JOIN event_tags AS EVTG ON EVT.event_id=EVTG.event_id 
					WHERE EVDT.status='1' AND EVT.event_id='".$data['event_id']."' AND 
						  EVT.provider_id='".$data['organiser_id']."'";
			$evData = $this->db->query($sql);
			if(empty($evData) || empty($evData = $evData->row_array())){
				$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
				return $res;
			}
			if($evData['date_time'] != ''){
				$dates = explode(',', $evData['date_time']);
				$time_spec = array();
				$startDate = explode('#', $dates[0]);
				$endDate = explode('#', $dates[count($dates)-1]);
				foreach ($dates as $rss) {
					$timeArray = explode('#', $rss);
					if(strtotime($startDate[1]) == strtotime($timeArray[1])){
						$time_spec[] = $timeArray[2];
					}
				}
				$evData['start_date']=$startDate[1];
				$evData['end_date'] = ($startDate[1] == $endDate[1])?'':$endDate[1];
				$evData['show_type']=($startDate[1] == $endDate[1])?'1':'2';
				$evData['show_time']=(!empty($time_spec))?$time_spec:[];
			}
			$this->db->select('media_url');
			$evtGllry = $this->db->get_where('event_gallery',array('event_id'=>$data['event_id'],'status'=>'1'))->result_array();
			$gallry = array();
			foreach($evtGllry AS $value){
				$gallry[] = $value['media_url'];
			}
			$evData['event_images'] = [];
			if(!empty($evtGllry)){
				$evData['event_images'] = $gallry;
			}
			$tag = explode(',',$evData['tags']);
			$evData['tags'] = $tag;
			$language = getLanguages();
			$evData['layout_type'] = (!empty($evData['layout']))?'1':'2';
			if($evData['layout_type'] == '1'){
				if($evData['custom_seat_layout'] != ''){
					$evData['fare_type'] = '2';
					$evData['layout_details']['layout_pricing'] = json_decode($evData['custom_seat_layout']);
				}else{
					$evData['fare_type'] = '1';
					$evData['layout_details']['layout_pricing'] = json_decode($evData['layoutDetails']);
				}
				$evData['layout_details']['layout_image'] = $evData['layout'];
			}else{
				$evData['layout_details'] = '';
				if(isset($evData['seat_pricing']) && !empty($evData['seat_pricing']) && 
				  !empty($seatlyt = json_decode($evData['seat_pricing']))){
					$priceArr = array();
					foreach ($language as $lang) {
						if(!isset($seatlyt->{'price_details_'.$lang})){
							continue;
						}
						$sql = "SELECT country_id AS lang_id,language_code AS lang,language FROM country WHERE status='1' AND language_code='$lang'";
						$langSql = $this->db->query($sql)->row_array();
						$desc=(!empty($seatlyt->{'price_details_'.$lang}))?$seatlyt->{'price_details_'.$lang}:'';
						$priceArr[] = array('lang'=>$lang,'desc'=>$desc,'language'=>$langSql['language'],'language_id'=>$langSql['lang_id']);
						unset($seatlyt->{'price_details_'.$lang});
					}
					$seatlyt->about_price_division = $priceArr;
					$evData['layout_details'] = $seatlyt;
				}
			}
			unset($evData['layout'],$evData['date_time'],$evData['custom_seat_layout'],$evData['seat_pricing'],$evData['layoutDetails']);
			$evntDes = $this->db->get_where('translator_event',array('event_id'=>$data['event_id']))->result_array();
			if(!empty($evntDes)){
				foreach ($evntDes as $key => $value) {
					$sql = "SELECT country_id AS lang_id,language_code AS lang,language FROM country WHERE status='1' AND language_code='".$value['language_code']."'";
					$langSql = $this->db->query($sql)->row_array();

					if(!empty($value['event_name'])){
						$evtName[] =  array('lang'=>$value['language_code'],'language'=>$langSql['language'],'language_id'=>$langSql['lang_id'],'name'=>$value['event_name']);
					}
					if(!empty($value['event_description'])){
						$evtDesc[] =  array('lang'=>$value['language_code'],'language'=>$langSql['language'],'language_id'=>$langSql['lang_id'],'desc'=>$value['event_description']);
					}
				}
				$evData['event_name'] = (!empty($evtName))?$evtName:[];
				$evData['event_desc'] = (!empty($evtDesc))?$evtDesc:[];
			}
			$res = array('status'=>1,'message'=>'success','data'=>$evData);
    	} catch(Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

    public function checkerDelete($data){
    	try{
    		$count = $this->db->get_where('checker',array('id'=>$data['checker_id'],'provider_id'=>$data['organiser_id']))->num_rows();
    		if($count < 1){
    			$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER06');
    			return $res;
    		}
    		$this->db->update('checker',array('status'=>2),array('id'=>$data['checker_id'],'provider_id'=>$data['organiser_id']));
    		$res = array('status'=>1,'message'=>'Checker Deleted Successfully');
    	} catch (Exception $e){
    		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER08');
    	}
    	return $res;
    }

 	function checkerbookingdetails($data) {
 		try {
 			$res = $this->db->get_where('checker',array('id'=>$data['checker_id']));
 			$qrCode = $data['qr_pin'];
 			$count = $res->num_rows();
 			$res = $res->row_array();
			if($count>0 && !empty($res) && isset($res['provider_id']) && 
			   !empty($provider_id = $res['provider_id'])){
				$sql = "SELECT BUK.id AS book_id, BUK.bookId, CUST.name AS customer_name, BUK.status,
							   BUK.no_of_ticket, BUK.qrcode, BUK.ticket_details, EDATE.date AS BUK_date
						FROM booking AS BUK
						INNER JOIN events AS EVT ON (BUK.event_id = EVT.event_id)
						INNER JOIN event_date_time AS EDATE ON (BUK.event_date_id = EDATE.id)
						INNER JOIN customer AS CUST ON (CUST.customer_id=BUK.customer_id)
						WHERE EVT.provider_id IN (1,$provider_id) AND BUK.status='1' AND 
							  BUK.bookId='$qrCode'
						GROUP BY BUK.bookId";
				$result = $this->db->query($sql)->row();
				if(count($result)>0){
					$result->seat_class = '';
					if(!empty($ticketDetls = json_decode($result->ticket_details))){
						if(is_array($ticketDetls) && isset($ticketDetls[0]) && isset($ticketDetls[0]->color)){
							$result->seat_class = $ticketDetls[0]->color;	
						} else if (isset($ticketDetls->color)){
							$result->seat_class = $ticketDetls->color;	
						}
					}
					$this->db->insert('checker_bookings',
								array('checker_id'=>$data['checker_id'],'booking_id'=>$qrCode,
								      'checked_time'=>date('Y-m-d H:i:s')));

					$res = array('status'=>1,'data'=>$result);
				} else {
					$res = array('status'=>0,'message'=>'Invalid booking code','code'=>'ER24');
				}
			}else{
				$res = array('status'=>0,'message'=>'Checker Doesnot Exist','code'=>'ER24');
			}		
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function getCheckerBookList($data) {
 		try {
 			$checker_id = $data['checker_id'];
 			$count = $this->db->get_where('checker',array('id'=>$checker_id,'status'=>'1'))->num_rows();
			if($count > 0){
 				$sql = "SELECT BOOK.bookId AS booking_id
						FROM booking AS BOOK
						INNER JOIN events AS EVT ON (EVT.event_id=BOOK.event_id)
						INNER JOIN checker AS CHK ON (CHK.provider_id=EVT.provider_id)
						WHERE CHK.id='$checker_id' AND BOOK.status='1'";
 				$count = $this->db->query($sql)->num_rows();
 				if($count > 0) {
 					$perPage = 10;
 					$page = (isset($data['page']))?$data['page']:1;
 					$limit = ($page - 1) * $perPage;
 					$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
								  'current_page'=>$page,'per_page'=>$perPage);
 					if($count > $limit) {
						$sql = "SELECT TEVT.event_name,TCAT.category_name,CUST.name,EDATE.date,
									   EDATE.time,BOOK.amount,BOOK.bookId AS booking_id 
							    FROM booking AS BOOK
							    INNER JOIN events AS EVT ON (EVT.event_id=BOOK.event_id)
				    			INNER JOIN checker AS CHK ON (CHK.provider_id=EVT.provider_id)
							    INNER JOIN event_date_time AS EDATE ON (EDATE.event_id=EVT.event_id)
							    INNER JOIN event_category AS CAT ON (CAT.cat_id=EVT.category_id)
							    INNER JOIN customer AS CUST ON (CUST.customer_id=BOOK.customer_id)
							    INNER JOIN translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
							    INNER JOIN translator_category AS TCAT ON (TCAT.category_id=CAT.cat_id)
							    WHERE CHK.id='$checker_id' AND TEVT.language_code='EN' AND 
							    	  TCAT.language_code='EN' AND BOOK.status='1'
					    	    GROUP BY booking_id";
						$result = $this->db->query($sql)->result();
						$resp = array('data'=>$result,'meta'=>$meta);
 						$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
					} else {
						$resp = array('data'=>[],'meta'=>$meta);
						$res = array('status'=>1,'message'=>'No More Data Found','data'=>$resp);
					}
				} else {
					$res = array('status'=>0,'message'=>'No Record Found','code'=>'ER24');
				}
			} else {
				$res = array('status'=>0,'message'=>'Checker Doesnot Exist','code'=>'ER25');
			}
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function acceptBooking($data,$type=1){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$status = 1; $title = 'Booking Approved';
		    $msgContent = "Hi, Your Booking is confirmed by the Organizer<br>";
 			if($type == 2){
 				$title = 'Booking Rejected';
 				$status = 0;
 				$msgContent = "Hi, Your Booking is Rejected by the Organizer<br>";
 			}
 			$sql = "SELECT fcm_token,email FROM booking INNER JOIN customer ON customer.customer_id = booking.customer_id WHERE bookId='".$data['booking_id']."'";
 			$bData = $this->db->query($sql)->row_array();
 			$this->db->update('booking',array('status'=>$status),array('bookId'=>$data['booking_id']));
 			$userData = array('id'=>$data['booking_id'],
							  'param'=>'booking_id',
							  'title'=>$title,
							  'message'=>$data['message']);
	  		push_sent_cancel(2,$bData['fcm_token'],$userData);

	  		$subject    = "TimeOut Booking";
		    $message    = "<html><body><p>".$msgContent."</p><p>Reason : ".$data['message']."</p></body></html>";
		    $this->send_mail($subject,$bData['email'],$message);

 			$res = array('status'=>1,'message'=>(($type == 1)?'Booking Accepted Successfully':'Booking Rejected Successfully'));
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getOrganizerTagDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$sql = $this->db->get_where('translator_tag',array('tag_id'=>$data['tag_id']));
 			if(empty($sql) || empty($tagData = $sql->result_array())){
 				return $res;
 			}
 			$tags = array();
 			foreach ($tagData as $key => $value) {
 				$tags[$key]['lang'] = $value['language_code'];
 				$tags[$key]['tag_name'] = $value['tag'];
 			}
 			$res = array('status'=>1,'data'=>$tags,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function addTag($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$tagName = json_decode(json_encode($data['tag_name']),true);
 			$key = array_search('EN', array_column($tagName, 'lang'));
 			$this->db->insert('tags',array('tag'=>$tagName[$key]['tag_name']));
 			$last_id = $this->db->insert_id();
 			$insertArr = array();
 			foreach ($tagName as $key => $value) {
 				$insertArr[] = array('tag_id'=>$last_id,
	 									 'language_code'=>$value['lang'],
	 					                 'tag'=>$value['tag_name']);
 			}
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_tag',$insertArr);
 			}
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function editOrganizerTagDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$tagName = json_decode(json_encode($data['tag_name']),true);
 			$key = array_search('EN', array_column($tagName, 'lang'));
 			$this->db->update('tags',array('tag'=>$tagName[$key]['tag_name']),array('tag_id'=>$data['tag_id']));
 			$insertArr = array();
 			foreach ($tagName as $key => $value) {
 				$insertArr[] = array('tag_id'=>$data['tag_id'],
	 									 'language_code'=>$value['lang'],
	 					                 'tag'=>$value['tag_name']);
 			}
 			$this->db->delete('translator_tag',array('tag_id'=>$data['tag_id']));
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_tag',$insertArr);
 			}
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changeOrganizerTagStatus($data,$status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$this->db->update('tags',array('status'=>$status),array('tag_id'=>$data['tag_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}
	
	public function getOrganizerHostCategoryList($data,$status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$count = $this->db->get_where('host_categories')->num_rows();
 			if($count > 0){
 				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
							  'current_page'=>$page,'per_page'=>$perPage);
				$sql = $this->db->query("SELECT * FROM host_categories LIMIT $limit,$perPage");
				if(empty($sql) || empty($hostData = $sql->result_array())){
					return $res; exit;
				}
				$resp = array('data'=>$hostData,'meta'=>$meta);
	 			$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function addHostCategory($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			unset($data['organiser_id']);
	 		$status = $this->db->insert('host_categories',$data);
	 		$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changeOrganizerHostStatus($data,$status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$this->db->update('host_categories',array('status'=>$status),array('host_cat_id'=>$data['host_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getOrganizerCityList($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$count = $this->db->get_where('region',array('status !='=>2))->num_rows();
 			if($count > 0){
 				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
							  'current_page'=>$page,'per_page'=>$perPage);
				$sql = $this->db->query("SELECT * FROM region WHERE status !='2' LIMIT $limit,$perPage");
				if(empty($sql) || empty($regionData = $sql->result_array())){
					return $res; exit;
				}
				foreach ($regionData AS $key => $region) {
 					$regData = langTranslator($region['id'],'REG','EN');
					$regionData[$key] = array_merge($regionData[$key],$regData);
					$this->db->select('id,status');
					$loc = $this->db->get_where('locality',array('region_id'=>$region['id']));
					$regionData[$key]['locality'] = [];
					if(isset($loc) && !empty($locData = $loc->result_array())){
						foreach ($locData AS $key_loc => $locality) {
		 					$reglocData = langTranslator($locality['id'],'LOC','EN');
							$locData[$key_loc] = array_merge($locData[$key_loc],$reglocData);
		 				}
						$regionData[$key]['locality'] = $locData;						
					}
 				}
				$resp = array('data'=>$regionData,'meta'=>$meta);
	 			$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getCityDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$sql = $this->db->get_where('translator_region',array('region_id'=>$data['region_id']));
 			if(empty($sql) || empty($regionData = $sql->result_array())){
 				return $res;
 			}
 			$city = array();
 			foreach ($regionData as $key => $value) {
 				$city[$key]['lang'] = $value['language_code'];
 				$city[$key]['city_name'] = $value['region_name'];
 			}
 			$res = array('status'=>1,'data'=>$city,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function editOrganizerCityDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$insertArr = array();
 			foreach ($data['region_name'] as $key => $value) {
 				$insertArr[] = array('region_id'=>$data['region_id'],
 									 'language_code'=>$value->lang,
 					                 'region_name'=>$value->city_name);
 			}
 			$this->db->delete('translator_region',array('region_id'=>$data['region_id']));
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_region',$insertArr);
 			}
 			
 			$regionArr = json_decode(json_encode($data['region_name']),true);
 			$key = array_search('EN', array_column($regionArr, 'lang'));
 			$latLng = getLocationLatLng($regionArr[$key]['city_name']);

 			$config = set_upload_service("assets/uploads/services");
            $this->load->library('upload');
            $config['file_name'] = time()."_".$_FILES['region_icon']['name'];
            $this->upload->initialize($config);
            if(!$this->upload->do_upload('region_icon')){
                $err = 1;
                 return array('status'=>0,'code'=>'ER980','message'=>$this->upload->display_errors());exit;
            }else{
                $upload_data = $this->upload->data();
                $data['region_icon'] = $config['upload_path']."/".$upload_data['file_name'];
            }
 			
 			$status = $this->db->update('region',array("region_icon"=>$data['region_icon'],"region_lat"=>$latLng['lat'],"region_lng"=>$latLng['lng']),array('id'=>$data['region_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function addCity($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$regionArr = json_decode(json_encode(json_decode($data['region_name'])),true);
 			$key = array_search('EN', array_column($regionArr, 'lang'));
 			$latLng = getLocationLatLng($regionArr[$key]['city_name']);
 			
 			unset($data['region_name'],$data['organiser_id']);
 			
 			$data['region_lat'] = $latLng['lat'];
        	$data['region_lng'] = $latLng['lng'];

        	$config = set_upload_service("assets/uploads/services");
            $this->load->library('upload');
            $config['file_name'] = time()."_".$_FILES['region_icon']['name'];
            $this->upload->initialize($config);
            if(!$this->upload->do_upload('region_icon')){
                $err = 1;
                 return array('status'=>0,'code'=>'ER980','message'=>$this->upload->display_errors());exit;
            }else{
                $upload_data = $this->upload->data();
                $data['region_icon'] = $config['upload_path']."/".$upload_data['file_name'];
            }
 			
 			$this->db->insert('region',$data);
 			$last_id = $this->db->insert_id();
 			
 			$insertArr = array();
 			foreach ($regionArr as $key => $value) {
 				$insertArr[] = array('region_id'=>$last_id,
 									 'language_code'=>$value['lang'],
 					                 'region_name'=>$value['city_name']);
 			}
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_region',$insertArr);
 			}
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changeOrganizerCityStatus($data, $status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$this->db->update('region',array('status'=>$status),array('id'=>$data['region_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getOrganizerCategoryList($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$count = $this->db->query("SELECT * FROM event_category WHERE status != '2' ORDER BY priority")->num_rows();
 			if($count > 0){
 				$perPage = 10;
				$page = (isset($data['page']))?$data['page']:1;
				$limit = ($page - 1) * $perPage;
				$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
							  'current_page'=>$page,'per_page'=>$perPage);
				$sql = $this->db->query("SELECT * FROM event_category WHERE status != '2' ORDER BY priority LIMIT $limit,$perPage");
				if(empty($sql) || empty($categoryData = $sql->result_array())){
					return $res; exit;
				}
				foreach ($categoryData AS $key => $region) {
 					$rtlData = langTranslator($region['cat_id'],'CAT','EN');
 					$categoryData[$key] = array_merge($categoryData[$key],$rtlData);
 				}
				$resp = array('data'=>$categoryData,'meta'=>$meta);
	 			$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getOrganizerCategoryDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$sql = $this->db->get_where('translator_category',array('category_id'=>$data['category_id']));
 			if(empty($sql) || empty($regionData = $sql->result_array())){
 				return $res;
 			}
 			$category = array();
 			foreach ($regionData as $key => $value) {
 				$category[$key]['lang'] = $value['language_code'];
 				$category[$key]['category_name'] = $value['category_name'];
 				$category[$key]['category_image'] = $value['category_image'];
 			}
 			$this->db->select('category_banner');
 			$catBan = $this->db->get_where('event_category',array('cat_id'=>$data['category_id']))->row_array();
 			$res = array('status'=>1,'data'=>array('category_name'=>$category,'banner_image'=>$catBan['category_banner']),'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getOrganizerCategoryOrderList($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
			$sql = $this->db->query("SELECT * FROM event_category WHERE status = '1' ORDER BY priority");
			if(empty($sql) || empty($categoryData = $sql->result_array())){
				return $res; exit;
			}
			foreach ($categoryData AS $key => $region) {
				$rtlData = langTranslator($region['cat_id'],'CAT','EN');
				$categoryData[$key] = array_merge($categoryData[$key],$rtlData);
			}
 			$res = array('status'=>1,'message'=>'Successfully','data'=>$categoryData);
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function addCategory($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			
 			$this->load->library('upload');
            $config = set_upload_service("assets/uploads/services");

            $config['file_name'] = time()."_".$_FILES['category_banner']['name'];
            $this->upload->initialize($config);
            if(!$this->upload->do_upload('category_banner')){
                $err = 1;
                return array('status'=>0,'code'=>'ER980','message'=>$this->upload->display_errors());exit;
            }else{
                $upload_data = $this->upload->data();
                $data['category_banner'] = $config['upload_path']."/".$upload_data['file_name'];
            }

 			$this->db->insert('event_category',array(
 												'category_banner'=>$data['category_banner']));
 			$last_id = $this->db->insert_id();
 			$insertArr = array();
 			foreach ($data['category_name'] as $key => $value) {

                $config['file_name'] = time()."_".$_FILES['category_image_'.$value->lang]['name'];
                $this->upload->initialize($config);
                if(!$this->upload->do_upload('category_image_'.$value->lang)){
                    $err = 1;
                    $res = array('status'=>0,'code'=>'ER980','message'=>$this->upload->display_errors());
                    break;
                }else{
                    $upload_data = $this->upload->data();
                    $catImg=$config['upload_path']."/".$upload_data['file_name'];
                }
 				$insertArr[] = array('category_id'=>$last_id,
	 									 'category_name'=>$value->category_name,
	 									 'language_code'=>$value->lang,
	 					                 'category_image'=>$catImg);
 			}
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_category',$insertArr);
 			}
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function editOrganizerCategoryDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$insertArr = array();
 			foreach ($data['category_name'] as $key => $value) {
 				$insertArr[] = array('category_id'=>$data['category_id'],
	 									 'category_name'=>$value->category_name,
	 									 'language_code'=>$value->lang,
	 					                 'category_image'=>$value->category_image);
 			}
 			$this->db->delete('translator_category',array('category_id'=>$data['category_id']));
 			if(!empty($insertArr)){
 				$this->db->insert_batch('translator_category',$insertArr);
 			}
 			$status = $this->db->update('event_category',array('category_banner'=>$data['category_banner']),array('cat_id'=>$data['category_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changeOrganizerCategoryStatus($data, $status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$this->db->update('event_category',array('status'=>$status),array('cat_id'=>$data['category_id']));
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function AddVenue($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			if(isset($data['has_layout']) && $data['has_layout'] == 1){
	            $config = set_upload_service("assets/uploads/services");
	            $this->load->library('upload');
	            $config['file_name'] = time()."_".$_FILES['layout_image']['name'];
	            $this->upload->initialize($config);
	            if(!$this->upload->do_upload('layout_image')){
	                $err = 1;
	                return array('status'=>0,'code'=>'ER980','message'=>$this->upload->display_errors());exit;
	            } else {
	                $upload_data = $this->upload->data();
	                $data['layout'] = $config['upload_path']."/".$upload_data['file_name'];
	            }

	            $seatLayoutDetails = array();
	            foreach(json_decode($data['seat_color']) AS $index => $value){
	                $seatLayoutDetails[] = array('color'=>$value,
	                                             'price'=>json_decode($data['seat_price'])[$index],
	                                             'capacity'=>json_decode($data['seat_capacity'])[$index],
	                                             'weekend_price'=>json_decode($data['seat_price'])[$index]);
	            }

	            $data['layout_details'] = json_encode($seatLayoutDetails);
	        } else {
	            $data['layout'] = $data['layout_details'] = '';
	        }
	        $locData = getLocationLatLng($data['location']);
	   		if(empty($locData)){
	        	return array('status'=>0,'code'=>'ER958','message'=>'Provide a valid Location');exit;
	        }
	        if(isset($data['locality_name']) && (!empty($data['locality_name']) || count($data['locality_name']) > 0)){ 
	 			$locArr = json_decode(json_encode($data['locality_name']),true);
	 			$key = array_search('EN', array_column($locArr, 'lang'));
	 			$status = $this->db->insert('locality',array('locality'=>$locArr[$key]['locality_name'],
					 				  	      			 'region_id'=>$data['region_id']));
		        $data['locality_id'] = $this->db->insert_id();
		        $insertArr = array();
		        foreach($locArr AS $key => $value) {
		        	$insertArr[] = array('language_code'=>$value['lang'],
		        						'locality_id'=>$data['locality_id'],
		        						'locality_name'=>$value['locality_name']);
		        }

		        if(!empty($insertArr)){
					$this->db->insert_batch('translator_locality',$insertArr);
				}
	 		}
	        
			unset($data['has_layout'],$data['seat_capacity'],
	              $data['seat_color'],$data['locality_type'],$data['seat_price']);

	 		$status = $this->db->insert('venue',array('layout'=>$data['layout'],
							 						  'location'=>$data['location'],
	 												  'region_id'=>$data['region_id'],
													  'host_cat_id'=>$data['host_cat_id'],
													  'locality_id'=>$data['locality_id'],
							 						  'provider_id'=>$data['organiser_id'],
							 						  'location_lat'=>$locData['lat'],
							 						  'location_lng'=>$locData['lng'],
							 						  'layout_details'=>$data['layout_details']));
	 		if($status){
	 			$venue_id = $this->db->insert_id();
	 			$insertArr = array();
	 			if(isset($data['venue_name']) && !empty($data['venue_name']) && 
	 			   !empty($data['venue_name'] = json_decode($data['venue_name']))){
		 			foreach ($data['venue_name'] AS $key => $value) {
		 				$insertArr[] = array('venue_id'=>$venue_id,
		 									 'venue_name'=>$value->venue_name,
		 									 'language_code'=>$value->lang);
		 			}
		 			if(!empty($insertArr)){
						$this->db->insert_batch('translator_venue',$insertArr);
		 			}
	 			}
	 			$res = array('status'=>1,'message'=>'success');
	 		}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function changeOrganizerVenueStatus($data, $status=''){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$this->db->update('venue',array('status'=>$status),array('id'=>$data['venue_id']));
 			$venStatus = ($status == 2)?'Deleted':'Deactivated';
			$venStatus = ($status == 1)?'Activated':$venStatus;
			$res = array('status'=>1,'message'=>'Venue '.$venStatus.' Successfully');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function editOrganizerVenueDetails($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			unset($data['layout']);
	        if(isset($data['has_layout']) && $data['has_layout'] == 1){
	        	if(isset($_FILES) && isset($_FILES['layout_image']) && !empty($_FILES['layout_image'])){
	        		$config = set_upload_service("assets/uploads/services");
		            $this->load->library('upload');
		            $config['file_name'] = time()."_".$_FILES['layout_image']['name'];
		            $this->upload->initialize($config);
		            if($this->upload->do_upload('layout_image')){
		                $upload_data = $this->upload->data();
		                $data['layout'] = $config['upload_path']."/".$upload_data['file_name'];
		            }
	        	}
	            
	            $seatLayoutDetails = array();
	            foreach(json_decode($data['seat_color']) AS $index => $value){
	                $seatLayoutDetails[] = array('color'=>$value,
	                                             'price'=>json_decode($data['seat_price'])[$index],
	                                             'capacity'=>json_decode($data['seat_capacity'])[$index],
	                                             'weekend_price'=>json_decode($data['seat_price'])[$index]);
	            }
	            $data['layout_details'] = json_encode($seatLayoutDetails);
	        } else {
	            $data['layout'] = $data['layout_details'] = '';
	        }
	        $locData = getLocationLatLng($data['location']);
	        if(empty($locData)){
	        	return array('status'=>0,'code'=>'ER958','message'=>'Provide a valid Location');exit;
	        }
	        $data['location_lat'] = $locData['lat'];
	        $data['location_lng'] = $locData['lng'];
	         if(isset($data['locality_name']) && (!empty($data['locality_name']) || count($data['locality_name']) > 0)){ 
	 			$locArr = json_decode(json_encode(json_decode($data['locality_name'])),true);
	 			$key = array_search('EN', array_column($locArr, 'lang'));
	 			$status = $this->db->insert('locality',array('locality'=>$locArr[$key]['locality_name'],
					 				  	      			 'region_id'=>$data['region_id']));
		        $data['locality_id'] = $this->db->insert_id();
		        $insertArr = array();
		        foreach($locArr AS $key => $value) {
		        	$insertArr[] = array('language_code'=>$value['lang'],
		        						'locality_id'=>$data['locality_id'],
		        						'locality_name'=>$value['locality_name']);
		        }
		        if(!empty($insertArr)){
					$this->db->insert_batch('translator_locality',$insertArr);
				}
				unset($data['locality_name']);
	 		}
	        
			$data['provider_id'] = $data['organiser_id'];

			$insertArr = array();
			$venue_id = $data['venue_id'];
			foreach (json_decode($data['venue_name']) AS $key => $value) {
				$insertArr[] = array('venue_id'=>$venue_id,
									 'venue_name'=>$value->venue_name,
									 'language_code'=>$value->lang);
			}
			unset($data['has_layout'],$data['seat_capacity'],$data['seat_color'],$data['seat_price'],
				$data['locality_type'],$data['venue_name'],$data['venue_id'],$data['organiser_id']);
	 		$status = $this->db->update('venue',$data,array('id'=>$venue_id));

			$this->db->delete('translator_venue',array('venue_id'=>$venue_id));
			if($status && !empty($insertArr)){
				$this->db->insert_batch('translator_venue',$insertArr);
				$res = array('status'=>1,'message'=>'success');
			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function reorderOrganizerCategoryList($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$priority = 1;
	 		foreach($data['category_id'] AS $cat_id) {
	 			$this->db->update('event_category',array('priority'=>$priority),array('cat_id'=>$cat_id));
	 			$priority += 1;
	 		}
 			$res = array('status'=>1,'message'=>'success');
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function mobileNumberAvailability($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');	
 		try{
 			$number = trim(preg_replace('/[^A-Za-z0-9\-]/', '', $data['country_code'].$data['phone_no']),0);
 			$sql = "SELECT provider_id FROM provider AS PDR
 					INNER JOIN users AS USR ON (USR.id = PDR.provider_id)
					WHERE (PDR.phone LIKE '%".$number."' OR PDR.phone LIKE '%".$data['phone_no']."') AND 
						  USR.user_type = '2' AND USR.status = '1'";
			$resp = $this->db->query($sql)->row_array();

			$phAvail = false;
			if(!empty($resp) && isset($resp['provider_id']) && !empty($resp['provider_id'])){
				$phAvail = true;
			}
 			$res = array('status'=>1,'data'=>array("country_code"=>$data['country_code'],
												   "phone"=>$data['phone_no'],
												   "is_phone_available"=>$phAvail));
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	function send_mail($subject,$email,$message,$attach=null) {
 		$ci =& get_instance(); 
		$ci->load->library('email');
        $ci->email->initialize(array(
	        'protocol' => 'smtp',
	        'smtp_host' => 'smtp.sendgrid.net',
	        'smtp_user' => 'adarsh@techware.in',
	        'smtp_pass' => 'Golden_123',
	        'smtp_port' => 587,
	        'crlf' => "\r\n",
	        'newline' => "\r\n"
        ));
        
        $ci->email->from('hello@timeout.sa', 'TimeOut');
        $ci->email->to($email);
        $ci->email->subject($subject);
        $ci->email->message($message);
        $ci->email->set_mailtype('html');
        if($attach != null) {
            $ci->email->attach($attach);
        }
        return $ci->email->send();
 	}

}
?>
