<?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")->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_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);
			}
 		} 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;
			}

			$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'] = $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'=>'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{
 			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));
	 		}
 		} 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'=>'ohh No!! Something Went South','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));
	 		}
 		} 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'];
 			
 			$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_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,GROUP_CONCAT(DISTINCT CONCAT_WS('#',EVDT.id,EVDT.date,EVDT.time)) AS date_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 (EVT.event_id = EVDT.event_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();
	 			foreach ($custData as $key => $rss) {
	 				$tmarr = explode(',', $rss['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]);
						}
	 				}
					$custData[$key]['timings'] = $time_spec;
				}

	 			$res = array('status'=>1,'data'=>array('data'=>$custData,'meta'=>$meta));
	 		}
 		} 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');
 		} 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($data){
 		
 	}

} 

?>
