<?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;
  	}

  	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,host_categories.show_layout,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 
   						   INNER JOIN host_categories ON venue.host_cat_id=host_categories.host_cat_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();
			$resultData = array();
			$event_layout = '';
			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;
				} else {
					$pricelist = json_decode($result->layout_details, TRUE);
					$price = min(array_column($pricelist, 'price'));
					$event_layout = $result->layout_details;
				}
			} 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();
				foreach ($dates as $rss) {
					$timeArray = explode('#', $rss);

					$sTime = $timeArray[1].' '.$timeArray[2];
					$cTime = date("Y-m-d H:i", strtotime('+15 minutes'));

					if($cTime < $sTime){ 
						$time_spec[$timeArray[1]][] = array("id"=>$timeArray[0],"time"=>$timeArray[2]);
					}
				}
			}
			
			$tagArr  = array();
			$resData = array();

			$resData['ticket_price'] = $price;
			$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['about_ticket'] = $result->seat_pricing;
			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; 		
 	}

 	function editOrganizerEventDetails($data){

 	}

 	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;
 	}

 	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;
	 		}
			
			$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 TESVT.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,GROUP_CONCAT(DISTINCT CONCAT_WS('#',EVDT.id,EVDT.date,EVDT.time)) AS date_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) 
 				INNER 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 (EVT.event_id = EVDT.event_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['show_time'] = '';
 			if(!empty($query['date_time'])){
 				$tmarr = explode(',', $query['date_time']);
				foreach ($tmarr as $value) {
					$timeArray = explode('#', $value);
					$sTime = $timeArray[1].' '.$timeArray[2];
					$cTime = date("Y-m-d H:i", strtotime('+15 minutes'));

					if($cTime < $sTime){ 
						$time_spec[$timeArray[1]][] = array("id"=>$timeArray[0],"time"=>$timeArray[2]);
					}
				}
				$query['show_time'] = $time_spec;
				unset($query['date_time']);
 			}

			$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;
 	}

 	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){
 		ini_set("memory_limit", "-1");
        set_time_limit(0);
        $language = getLanguages();

		$err = 0;
        $errMsg = '';
        // if($err == 0 && (!isset($postData['event_name_EN']) || empty($postData['event_name_EN']))){
        //     $err = 1;
        //     $errMsg = 'Provide Event Name (English)';
        // } 
        // else if ($err == 0 && (!isset($postData['event_description_EN']) || $postData['event_description_EN']=='')){
        //     $err = 1;
        //     $errMsg = 'Provide Event Description (English)';
        // }  
        // else if ($err == 0 && (!isset($postData['event_start_date']) || $postData['event_start_date'] == '')){
        //     $err = 1;
        //     $errMsg = 'Provide Event Start Date';
        // } 
        // else if ($err == 0 && (!isset($postData['event_time']) || count($postData['event_time']) <= 0)){
        //     $err = 1;
        //     $errMsg = 'Provide Event Timing';
        // } 
        // else if ($err == 0 && (!isset($postData['category_id']) || $postData['category_id'] == '')){
        //     $err = 1;
        //     $errMsg = 'Provide Event Category';
        // } 
        // else if ($err == 0 && (!isset($postData['tags']) || count($postData['tags']) <= 0)){
        //     $err = 1;
        //     $errMsg = 'Provide Proper Event Details';
        // } 
        // else if ($err == 0 && isset($postData['fare_type']) && $postData['fare_type'] == 1 && 
        //           !isset($postData['seat_color']) || empty($postData['seat_color']) || 
        //           !isset($postData['seat_price']) || empty($postData['seat_price']) || 
        //           count($postData['seat_price']) != count($postData['seat_color'])){
        //     $err = 1;
        //     $errMsg = 'Provide Proper Layout details';
        // }

        $postData['seat_pricing'] = $postData['custom_seat_layout'] = '';
        if(isset($postData['fare_type']) && $postData['fare_type'] == 1){
            $cstmSeatLayout = array();
            for($i = 0 ; $i < count($postData['seat_block']) ; $i++){
                $cstmSeatLayout[] = array('color'=>$postData['seat_block'][$i]['block_name'],
                                          'price'=>$postData['seat_block'][$i]['seat_price'],
                                          'capacity'=>$postData['seat_block'][$i]['capacity'],
                                          'weekend_price'=>$postData['seat_block'][$i]['custom_price']);
            }
            $postData['custom_seat_layout'] = json_encode($cstmSeatLayout);
        }
         // else {
        //     $seatPriceArr = array('price'=>$postData['price'],'capacity'=>$postData['capacity']);
        //     foreach($language AS $lang) {
        //         $details = $postData['price_details_EN'];
        //         if(isset($postData['price_details_'.$lang]) && !empty($postData['price_details_'.$lang])){
        //             $details = $postData['price_details_'.$lang];
        //         }
        //         $seatPriceArr['price_details_'.$lang] = $details;
        //     }
        //     $postData['seat_pricing'] = json_encode($seatPriceArr);
        // }

        // $postData['maximum_seat_booking'] = (isset($postData['maximum_seat_booking']) && !empty($postData['maximum_seat_booking']))?$postData['maximum_seat_booking']:'14';

        $provider = ($this->session->userdata['user_type']==1)?'1':$this->session->userdata['id'];
        $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);
        
        $languageArr = array();
        foreach($postData['event_name'] AS $key => $value) {
            $languageArr[$value['lang']]['event_name'] = $value['name'];
            foreach($postData['event_desc'] AS $eve_key => $eve_value) {
            	if($value['lang'] == $eve_value['lang']){
            		$languageArr[$value['lang']]['event_desc'] = $eve_value['desc'];
            	}
            }
        }
        $eventData['status'] = '3';
        $status = $this->db->insert('events',$eventData);
 		if($status){
 			$event_id = $this->db->insert_id();
 			$languages = getLanguages();
	 		if(!empty($languages)){
	 			$insertArr = array();
	 			foreach ($languages AS $lang) {
	 				if(!isset($languageArr[$lang]) || (empty($languageArr[$lang]['event_name']) && 
	 				   empty($languageArr[$lang]['event_desc']))){
	 					continue;
	 				}
	 				$eName = !empty($languageArr[$lang]['event_name'])?$languageArr[$lang]['event_name']:'';
	 				$eDesc = !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 ($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 ($postData['event_time'] 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 ($postData['tags'] 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);
            }
        }
 	}

 	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['event_image']['name']); $typ++) { 
            $_FILES['file']['name'] = $files['event_image']['name'][$typ];
            $_FILES['file']['type'] = $files['event_image']['type'][$typ];
            $_FILES['file']['size'] = $files['event_image']['size'][$typ]; 
            $_FILES['file']['error'] = $files['event_image']['error'][$typ];
            $_FILES['file']['tmp_name'] = $files['event_image']['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);
    }

    function getLanguages(){
    	try{
    		$sql = "SELECT country_id AS lang_id,language_code AS lang 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;
    }

    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;
    }

    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;
    }

    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;
    }

    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;
    }

    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;
    }

    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;
    }

} 

?>
