<?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 * FROM events AS EVT WHERE EVT.provider_id = '$organizer_id' AND EVT.status=1")->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 EVT.status=1 AND TSEVT.language_code='EN' AND TSVNE.language_code='EN' AND TSCAT.language_code='EN' AND TSREG.language_code='EN' 
 				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");
			$sql = "SELECT events.has_payment,events.event_id,events.seat_pricing,events.custom_seat_layout,
						   events.seat_pricing,venue.layout,venue.layout_details,events.max_booking,
						   venue.location,venue.location_lat AS lat,venue.location_lng AS lng,venue.id AS venue_id,
						   GROUP_CONCAT(DISTINCT event_tags.tag_id) AS tag_ids,
						   GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time,translator_event.event_name,translator_venue.venue_name,translator_region.region_name 
						   FROM events 
						   INNER JOIN event_date_time ON events.event_id = event_date_time.event_id 
						   INNER JOIN translator_event ON events.event_id = translator_event.event_id 
						   INNER JOIN translator_venue ON events.venue_id = translator_venue.venue_id 
						   INNER JOIN venue ON venue.id = events.venue_id 
						   INNER JOIN translator_region ON venue.region_id = translator_region.region_id 
   						   LEFT JOIN event_tags ON events.event_id=event_tags.event_id 
   						   WHERE events.provider_id='$organizer_id' AND translator_event.language_code='EN' AND translator_venue.language_code='EN' AND translator_region.language_code='EN' AND events.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!=''){
					$pricelist = json_decode($result->custom_seat_layout, TRUE);
					$price = min(array_column($pricelist, 'price'));
					$event_layout = $result->custom_seat_layout;
					$faretype = 2;
				} else {
					$pricelist = json_decode($result->layout_details, TRUE);
					$price = min(array_column($pricelist, 'price'));
					$event_layout = $result->layout_details;
					$faretype = 1;
				}
			} else {
				$pricelist = json_decode($result->seat_pricing, TRUE);
				$price = $pricelist['price'];
				$event_layout = $result->seat_pricing;
			}
			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 = array();

			$resData['ticket_price'] = $price;
			$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';
			if($resData['layout_type'] == '1'){
				$resData['layout_pricing'] = $event_layout;
				$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);
			array_push($resultData, $resData);
			$res = array('status'=>1,'data'=>$resultData);
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}

 	public function editOrganizerEventDetails($data){
 		try{
 			ini_set("memory_limit","-1");
 			set_time_limit(0);
 			$languages = getLanguages();
 			pr($languages);

 		} 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']))){
 				$res = array('status'=>1,'message'=>($status == 2)?'Event Deleted Successfully':'Event DeActivated Successfully');
 			}
 		} catch(Exception $e){
 			$res = array('status'=>'0','message'=>'Ohh No!! Something Went South!!','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function getVenueList($data){
 		try{
 			$count = $this->db->query("SELECT * FROM venue AS VNE WHERE VNE.status != '2' AND VNE.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);

	 			$cond  = (!empty($view))?" VNE.status IN ($view) ":" VNE.status != '2' ";
		 		$cond .= (!empty($data['organiser_id']))?" AND VNE.provider_id='".$data['organiser_id']."' ":"";

		 		$sql = "SELECT VNE.id AS venue_id,VNE.location AS venue_location,VNE.region_id
		 				FROM venue AS VNE
		 				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,VNE.location AS venue_location
	 				FROM venue AS VNE
	 				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;
	 		}
			$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['region_id'],'REG','EN');
			$venueData['venue_region'] = $rtlData['region_name'];
	 		unset($venueData['region_id']);

	 		$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' 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,CASE WHEN BUK.status ='0' THEN 'Cancelled' WHEN BUK.status='1' THEN 'Booked' WHEN BUK.status='2' THEN 'Completed' WHEN BUK.status='3' THEN 'Pending' WHEN BUK.status='4' THEN 'Deleted' ELSE 'Payment Failed' END AS 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'
	 			GROUP BY BUK.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 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,CASE WHEN BUK.status ='0' THEN 'Cancelled' WHEN BUK.status='1' THEN 'Booked' WHEN BUK.status='2' THEN 'Completed' WHEN BUK.status='3' THEN 'Pending' WHEN BUK.status='4' THEN 'Deleted' ELSE 'Payment Failed' END AS booking_status,EVDT.date AS scheduled_date,EVDT.time AS scheduled_time 
 				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;
 			}
			$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;
	 		}

	 		$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{
 			$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']."' AND USR.user_type='".$data['user_type']."'");

 			if(empty($sql) || empty($custData = $sql->row_array())){
 				$res = array('status'=>0,'message'=>'User Doesnot Exist','code'=>'ER09');
 				return $res;
 			}
 			$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;
 			}
			if($this->db->query("UPDATE users SET password='".md5($data['confirm_password'])."' WHERE id='".$data['user_id']."' AND user_type='".$data['user_type']."'")){
				$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){
 		try{
 			if($this->db->update('checker',array('status'=>'0'),array('id'=>$data['checker_id'],'provider_id'=>$data['organiser_id']))){
 				$res = array('status'=>1,'message'=>'Checker Deactivated');
 			}
 		} 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'];

	 		$tagData = $this->db->query("SELECT tag_id AS id FROM tags WHERE status='1'");
	 		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'=>$tagData);
 		} 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['layout_type'] == 1){
	            $postData['custom_seat_layout'] = $postData['layout'];
	        } else {
	            $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'],
	                       	   '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_code AS lang,language FROM country WHERE status='1' 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 country_id,country_name,country_code FROM country WHERE status='1'";
    		$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=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 = '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));
			}
    	} 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 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'] = $evData['custom_seat_layout'];
				}else{
					$evData['fare_type'] = '1';
					$evData['layout_details']['layout_pricing'] = $evData['layoutDetails'];
				}
				$evData['layout_details']['layout_image'] = $evData['layout'];
			}else{
				$seatlyt = json_decode($evData['seat_pricing']);
				$priceArr = array();
				foreach ($language as $lang) {
					if(!isset($seatlyt->{'price_details_'.$lang})){
						continue;
					}
					$desc=(!empty($seatlyt->{'price_details_'.$lang}))?$seatlyt->{'price_details_'.$lang}:'';
					$priceArr[] = array('lang'=>$lang,'desc'=>$desc);
					unset($seatlyt->{'price_details_'.$lang});
				}
				$seatlyt->about_price_division = $priceArr;
				$evData['layout_details'] = json_encode($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) {
					if(!empty($value['event_name'])){
						$evtName[] =  array('lang'=>$value['language_code'],'name'=>$value['event_name']);
					}
					if(!empty($value['event_description'])){
						$evtDesc[] =  array('lang'=>$value['language_code'],'desc'=>$value['event_description']);
					}
				}
				$evData['event_name'] = $evtName;
				$evData['event_desc'] = $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;
    }

} 

?>
