<?php 

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

 	public function login($data){
 		try{
			$res = array('status'=>0,'message'=>'Something went wrong','code'=>'ER07');
 		    $this->db->select('customer.name,customer.dob,customer.phone,customer.email,customer.profile_image 
 		   	   AS image,customer.gender,users.id AS userId,customer.profile_city AS city,customer.dob,customer.email_verified');
 			$this->db->where('users.status',1);
	 		$this->db->where('users.password',md5($data['password']));
	 		$this->db->where('customer.email',$data['email_id']);
	 		$this->db->from('users');
	 		$this->db->join('customer','customer.customer_id = users.id');
	 		$result = $this->db->get()->row();
	 		if($result){
	 			if(isset($result->email_verified) && $result->email_verified == '1'){
		 			$result->dob = (!empty($result->dob))?date("m/d/Y",$result->dob/1000):'';
		 			$result->auth_token = md5(microtime().rand());
		 			$this->generateAuth($result->userId,$result->auth_token);
		 			$res = array('status'=>1,'data'=>$result);
	 			} else {
	 				$res = array('status'=>0,'message'=>'Verify Your E-Mail','code'=>'ER07');
	 			}

	 		} else {
	 			$res = array('status'=>0,'message'=>'Wrong password. Try again or click Forgot password to reset it','code'=>'ER05');
	 		}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;	
 	}

 	function generateAuth($userId,$auth_token) {
 		$this->db->insert('customer_auth',array('user_id'=>$userId, 'auth_token'=>$auth_token));
 	}

 	function register($data) {
 		try{
 			$email = $data['email_id'];
 			$phone = preg_replace('/\D/', '', $data['phone']);
 			$phone_code = preg_replace('/\D/', '', $data['phone_code']);

 			$sql = "SELECT * FROM customer 
				    INNER JOIN `users` ON users.id=customer.customer_id AND users.user_type='3' 
				    WHERE users.status!='2' AND (customer.email = '$email' OR 
				  		  (customer.phone_code='$phone_code' AND customer.phone LIKE '%$phone'))";
 			$res_count = $this->db->query($sql)->row();

 			if(count($res_count) > 0) {
 				if($res_count->email == $data['email_id'] && 
 				   ($res_count->phone == $data['phone'] || strpos($res_count->phone,$data['phone'])!==false)){
 					return array('status'=>0,'message'=>'Already have an account with email id and phone no. Please login','code'=>'ER12');
 				} else if($res_count->email == $data['email_id']){
 					return array('status'=>0,'message'=>'Email id already exists','code'=>'ER09');
 				} else if(strpos($res_count->phone,$data['phone'])!==false||$res_count->phone==$data['phone']){
 					return array('status'=>0,'message'=>'Phone no already exists','code'=>'ER10');
 				}else{
 					return array('status'=>0,'message'=>'Something went wrong','code'=>'ER07');
 				}
 			} else {
 				$unique_id = uniqid().time();
 				$temp_password = $data['password'];
	 			$data['password'] = md5($data['password']);

	 			$user_data = array('password'=>$data['password'],'display_name'=>'Customer','user_type'=>3);
	 			$this->db->insert('users',$user_data);
	 			$id = $this->db->insert_id();

	 			if($id) {
	 				$customer_data = array('customer_id'=>$id,'phone'=>$data['phone'],
	 									   'phone_code'=>$data['phone_code'],
	 									   'email_verified'=>'0','email'=>$data['email_id'],
	 									   'name'=>$data['name'],'confirm_link'=>$unique_id);

	 				$this->db->insert('customer', $customer_data);

	 				$subject    = "TimeOut, Verify your account";
	 				$email_id   = $data['email_id'];
	 				$reset_link = base_url().'Api/verifyMail/'.$unique_id;
	 				$msgContent = "Hi, Welcome to TimeOut. Please Verify your E-mail for the username: 
	 							  ".$email_id.". User the following link verify your account 
	 							  ".$reset_link.".";
					$message    = "<html><body>".$msgContent."</body></html>";

					$template = getNotifTemplate();
		            if(isset($template['verify_mail']) && !empty($template['verify_mail'])){
		                $message = str_replace(array('{:user_name}','{:reset_link}'),
		                					   array($email_id,$reset_link),
		                					   $template['verify_mail']);
		            }
	 				$this->send_mail($subject,$email_id,$message);


	 				return array('status'=>1,'data'=>'');

	 				// $this->db->select('customer.name,customer.dob,customer.phone,customer.email,customer.profile_image AS image,customer.gender,users.id AS userId, customer.city');
		 			// $this->db->where('users.id',$id);
			 		// $this->db->from('users');
			 		// $this->db->join('customer','customer.customer_id = users.id');
			 		// $result = $this->db->get()->row();
			 		// if($result){
			 		// 	$result->dob = (!empty($result->dob))?date("m/d/Y",$result->dob/1000):'';
			 		// 	$result->auth_token = md5(microtime().rand());
			 		// 	$this->generateAuth($result->userId,$result->auth_token);
			 		// 	$res = array('status'=>1,'data'=>$result,'message'=>'An activation Email has been set to your mail id');
			 		// } else {
			 		// 	$res = array('status'=>0,'message'=>'No record found','code'=>'ER13');
			 		// }
	 			} else {
	 				return array('status'=>0,'message'=>'Registration failed please try again','code'=>'ER11');
	 			}	 			
		 	}
 		} catch(Exception $e) {
 			 return array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 	}

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

 	function forgot($data) {
 		try{
 			$settings   = getSettings();
    		$redUrl     = $settings['web_base_url'];

 			$res_count = $this->db->where('email',$data['email_id'])->get('customer')->num_rows();
 			if($res_count > 0) {
 				$unique_id = uniqid().time();
	 			$this->db->where('email',$data['email_id'])->update('customer',array('reset_key'=>$unique_id));

	 			$subject 	= "TimeOut: Forgot Password";
	 			$url 		= $redUrl.'forgot?reset_key='.$unique_id;
	 			$msgContent = "Hi, Welcome to TimeOut. Please use this link 
	 			               for reset your password: ".$url;
	 			$message	= "<html><body><p>".$msgContent."</p></body></html>";

			    $template 	= getNotifTemplate();
	            if(isset($template['forgot_mail']) && !empty($template['forgot_mail'])){
	                $message = str_replace(array('{:url}'),array($url),$template['forgot_mail']);
	            }
	 			$result = $this->send_mail($subject,$data['email_id'],$message);

	 			if($result){
	 				$res = array('status'=>1,'data'=>null);
	 			} else {	 				
	 				$res = array('status'=>0,'message'=>'Please try again','code'=>'ER15');
	 			}
 			} else {
 				$res = array('status'=>0,'message'=>'No account has been found in this email id','code'=>'ER14');
		 	}
 		} catch(Exception $e) {
		    $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function popular() {
 		try {
 			$rs = $this->db->get_where('region',array('status'=>'1'))->result_array();
 			if(count($rs) > 0) {
 				$cityData = array();
 				foreach ($rs AS $city) {
 					$cData = langTranslator($city['id'],'REG');
 					$cData['city_id'] = $city['id'];
 					$cData['city_image'] = $city['region_icon'];
 					$cityData[] = $cData;
 				}
 				$res = array('status'=>1,'data'=>$cityData);
 			} else {
 				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 

 		return $res;
 	}

 	function category() {
 		try {
			$sql = "SELECT * FROM event_category WHERE status='1' ORDER BY priority";
 			$rs = $this->db->query($sql)->result_array();

 			if(count($rs) > 0) {
 				$catData = array();
 				foreach ($rs AS $cat) {
 					$cData = langTranslator($cat['cat_id'],'CAT');
 					$cData['cat_id'] = $cat['cat_id'];
 					$cData['category_banner'] = $cat['category_banner'];
 					$catData[] = $cData;
 				}
 				$res = array('status'=>1,'data'=>$catData);
 			} else {
 				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 

 		return $res;
 	}

 	function getCountry() {
 		try {
 			$rs = $this->db->query("SELECT CTRY.language_code,CTRY.country_id,CTRY.country_name,
 										   CTRY.country_code,CTRY.language,CTRY.currency,CTRY.currency_symbol,
 										   CTRY.conversion_rate,CTRY.phone_code
		                            FROM country AS CTRY
		                            WHERE CTRY.status = 1 
		                            ORDER BY CTRY.country_name")->result();
 			if(count($rs) > 0) {
 				$res = array('status'=>1,'data'=>$rs);
 			} else {
 				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 

 		return $res;
 	}

 	function locality($city_id = '') {
 		try {
 			$cond['status'] = '1';
 			if(!empty($city_id)){
 				$cond['region_id'] = $city_id;
 			}
 			$rs = $this->db->select('id,region_id')->get_where('locality',$cond)->result_array();
 			if(count($rs) > 0) {
 				$locData = array();
 				foreach ($rs AS $loc) {
 					$lData = langTranslator($loc['id'],'LOC');
 					$lData['locality_id'] = $loc['id'];
 					$lData['region_id'] = $loc['region_id'];
 					$locData[] = $lData;
 				}
 				$res = array('status'=>1,'data'=>$locData);
 			} else {
 				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function favourite($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				if($data['status'] == 1) {
	 				$post_data = array('user_id'=>$user_id, 'event_id'=>$data['event_id'], 'status'=>1);
	 				$count_rs = $this->db->where($post_data)->get('favourite')->num_rows();
	 				if($count_rs > 0) {
	 					$res = array('status'=>0,'message'=>'Already submitted your Feedback','code'=>'ER21');
	 				} else {
	 					$rs = $this->db->insert('favourite', $post_data);
		 				if($rs) {
		 					$res = array('status'=>1,'data'=>null);
		 				} else {
		 					$res = array('status'=>0,'message'=>'Feedback submission failed','code'=>'ER20');
		 				}
	 				}	 				
	 			} else {
	 				$where = array('user_id'=>$user_id, 'event_id'=>$data['event_id'], 'status'=>1);
	 				$rs = $this->db->where($where)->update('favourite', array('status'=>0));
	 				if($rs) {
	 					$res = array('status'=>1,'data'=>null);
	 				} else {
	 					$res = array('status'=>0,'message'=>'Feedback submission failed','code'=>'ER20');
	 				}
	 			}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function auth_token_get($token) {
 		$rs = $this->db->select('user_id')->where('auth_token', $token)->get('customer_auth')->row();
 		if(count($rs) > 0) {
 			return $rs->user_id;
 		} else {
 			return 0;
 		}
 	}

 	function favouritelist($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$where = array(
 					'favourite.status'=>1,
 					'favourite.user_id'=>$user_id,
 					'events.status'=>1
 				);
 				$result = $this->db->select('events.event_id, events.event_name_en,events.seat_pricing,events.custom_seat_layout,venue.layout,venue.layout_details, event_gallery.media_url,favourite.status AS fav_status')->where($where)->from('favourite')->join('events', 'events.event_id = favourite.event_id')->join('venue', 'venue.id = events.venue_id')->join('event_gallery', 'events.event_id = event_gallery.event_id AND event_gallery.media_type = 0', 'LEFT')->group_by('events.event_id')->get()->result();
				if(count($result)>0){
					$response = array();
					foreach ($result as $rs) {
						if($rs->layout!=''){
							if($rs->custom_seat_layout!=''){
								$pricelist = json_decode($rs->custom_seat_layout, TRUE);
								$price = min(array_column($pricelist, 'price'));
							} else {
								$pricelist = json_decode($rs->layout_details, TRUE);
								$price = min(array_column($pricelist, 'price'));
							}
						} else {
							$pricelist = json_decode($rs->seat_pricing, TRUE);
							$price = $pricelist['price'];
						}
						$resData = array(
							'event_name_en'=>$rs->event_name_en,
							'media_url'=>$rs->media_url,
							'fav_status'=>$rs->fav_status,
							'price'=>$price,
							'event_id'=>$rs->event_id
						);
						array_push($response, $resData);
					}
					$res = array('status'=>1,'data'=>$response);
				} else {
					$res = array('status'=>0,'message'=>'No favourites yet!','code'=>'ER22');
				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function bookedlist($data,$per_page='',$page ='',$count ='') {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
				if($page == 0 && $per_page == 0){
					$page = $page;
				}else{
					$page = (isset($data['page']))? $data['page']:1;
				}
				$page_limit = ($page - 1) * $per_page;
				$cond =($per_page == 0 && $page == 0)?'':"LIMIT $page_limit, $per_page";

				$sql = "SELECT ODR.order_id,ODR.order_type,ODR.booking_id 
						FROM orders AS ODR
 						LEFT JOIN booking AS BOK ON 
 								(ODR.booking_id=BOK.bookId AND BOK.status IN (0,1,2,3,5,6))
 						LEFT JOIN flight_booking AS FBK ON 
 								(ODR.booking_id=FBK.flight_book_id AND FBK.status IN (0,1,2,3,5))
 						LEFT JOIN hotel_booking AS HBK ON 
 								(ODR.booking_id=HBK.hotel_book_id AND HBK.status IN (0,1,2,3,5)) 
						WHERE ODR.customer_id='$user_id'
 						GROUP BY ODR.order_id ORDER BY ODR.order_id DESC $cond";
				$bookedData = $this->db->query($sql);

				if($per_page == 0 && $page == 0){
					return $bookedData->num_rows();
				}
				if(count($bookedData) > 0) {
					if($count > $page_limit) {
						$bookData = array();
						foreach (($bookedData = $bookedData->result_array()) as $key => $value) {
							switch($value['order_type']){
								case 1 : $resp = $this->getEventData($value['booking_id'],$user_id);break;
								case 2 : $resp = $this->getHotelData($value['booking_id'],$user_id);break;
								case 3 : $resp = $this->getFlightData($value['booking_id'],$user_id);break;
							}
							if(!empty($resp)){
								$bookData[] = $resp;
							}
						}
 						$meta = array('total_pages'=>ceil($count/$per_page),'total'=>$count,
 									  'current_page'=>$page,'per_page'=>$per_page);

 						$response = array('data'=>$bookData,'meta'=>$meta);
 						$res = array('status'=>1,'data'=>$response);
 					} else {
 						$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 					}
 				} else {
 					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 				} 				
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function getEventData($booking_id='',$user_id=''){
		$sql = "SELECT booking.id AS book_id,booking.bookId AS bookingCode,booking.amount,
					   event_date_time.date AS event_date,booking.qrcode,booking.ticket_details,
					   venue.location,event_date_time.time AS event_time,booking.event_id,
					   event_gallery.media_url,booking.no_of_ticket,events.has_payment,
					   venue.id AS venue_id,venue.location_lat AS lat,venue.location_lng AS lng,
					   transaction.status AS transaction_status,booking.status AS book_status,
					   customer.name AS customer_name,customer.profile_image
				FROM booking
				INNER JOIN events ON booking.event_id = events.event_id
				INNER JOIN event_date_time ON booking.event_date_id = event_date_time.id
				INNER JOIN venue ON venue.id = events.venue_id
				INNER JOIN customer ON customer.customer_id=booking.customer_id
				LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
 														   event_gallery.media_type=0 
				LEFT JOIN transaction ON transaction.booking_id=booking.bookId
				WHERE booking.bookId='$booking_id' AND booking.customer_id=$user_id";

		$eventData = $this->db->query($sql)->row_array();
		$eventData['order_type'] = 1;

		$evtLang  = langTranslator($eventData['event_id'],'EVT');
		array_merge($eventData,$evtLang);
		$vneLang  = langTranslator($eventData['venue_id'],'VEN');
		return array_merge($eventData,$vneLang);

	}

	function getHotelData($booking_id='',$user_id=''){
		$sql = "SELECT HBK.id AS book_id, HBK.hotel_book_id AS bookingCode,HBK.price AS amount,
					   HBK.checkin AS event_date,HBK.hotel_name AS event_name,HBK.qrcode,
					   HBK.hotel_image AS media_url,HBK.status AS book_status,HBK.traveller_details,
					   TRS.status AS transaction_status
				FROM hotel_booking AS HBK
				LEFT JOIN transaction AS TRS ON TRS.booking_id=HBK.hotel_book_id
				WHERE HBK.hotel_book_id='$booking_id'";

		$hotelData =  $this->db->query($sql)->row_array();
		if(empty($hotelData)){
			return;
		}

		$hotelData['location'] = '';
		$hotelData['no_of_ticket'] = '';
		if(isset($hotelData['traveller_details']) && !empty($hotelData['traveller_details']) && 
		   !empty($trvlDtls = json_decode($hotelData['traveller_details']))){
			$hotelData['location'] = (isset($trvlDtls->hotel_address))?$trvlDtls->hotel_address:'';
			$hotelData['no_of_ticket'] = (isset($trvlDtls->roomDetails) && isset($trvlDtls->roomDetails->room))?$trvlDtls->roomDetails->room.' Room':'';
		}
		$hotelData['order_type'] = 2;
		$hotelData['has_payment'] = 1;
		$hotelData['event_time'] = '11:00';
		$hotelData['venue_id'] = $hotelData['event_id'] = $hotelData['book_id'];
		return $hotelData;
	}

	function getFlightData($booking_id='',$user_id=''){
		$sql = "SELECT FBK.id AS book_id,FBK.flight_book_id AS bookingCode,FBK.price AS amount,
					   FBK.departure_date AS event_date,FBK.flight_name AS event_name,FBK.qrcode,
					   FBK.flight_image AS media_url,FBK.status AS book_status,
					   FBK.traveller_details,TRS.status AS transaction_status 
				FROM flight_booking AS FBK
				LEFT JOIN transaction AS TRS ON TRS.booking_id=FBK.flight_book_id
				WHERE FBK.flight_book_id='$booking_id'";

		$flightData =  $this->db->query($sql)->row_array();
		if(empty($flightData)){
			return;
		}
		$flightData['location'] = '';
		$flightData['no_of_ticket'] = '';
		if(isset($flightData['traveller_details']) && !empty($flightData['traveller_details']) && 
		   !empty($trvlDtls = json_decode($flightData['traveller_details']))){
		   	if(isset($trvlDtls->fromAirportCity) && isset($trvlDtls->toAirportCity)){
		   		$flightData['location'] = $trvlDtls->fromAirportCity.' - '.$trvlDtls->toAirportCity;
		   	}
		   	if(isset($trvlDtls->passengerDetails) && isset($trvlDtls->passengerDetails->adult) && 
		       isset($trvlDtls->passengerDetails->children) && isset($trvlDtls->passengerDetails->infant)){
		   		$flightData['no_of_ticket'] = (int)$trvlDtls->passengerDetails->adult + 
		  			(int)$trvlDtls->passengerDetails->children + (int)$trvlDtls->passengerDetails->infant;
		   	}
			
		}
		
		$fghtTme = explode("T",$flightData['event_date']); 
		$flightData['event_date'] = (isset($fghtTme[0]) && !empty($fghtTme[0]))?$fghtTme[0]:'';
		$flightData['event_time'] = (isset($fghtTme[1]) && !empty($fghtTme[1]))?$fghtTme[1]:'';
		$flightData['order_type'] = 3;
		$flightData['has_payment'] = 1;
		$flightData['venue_id'] = $flightData['event_id'] = $flightData['book_id'];
		return $flightData;
	}

 	function bookingdetails($data) {
 		$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			if($user_id > 0) {
 				$cond = array('booking_id'=>$data['bookingCode'],'customer_id'=>$user_id);
 				$ordType = $this->get_where('orders',$cond)->row_array();
 				if(empty($ordType) || !isset($ordType['order_type']) || empty($ordType['order_type'])){
 					return array('status'=>0,'message'=>'Invalid booking code','code'=>'ER24');
 				}

 				if($ordType['order_type'] == 1){
					$resp = $this->getEventData($data['bookingCode'],$user_id);
					$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER30');
					if(!empty($resp)){
						$res = array('status'=>1,'data'=>$resp);
					}
				}
 			}
 		} catch(Exception $e) {} 
 		return $res;
 	}

 	function cancel($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
				$rs = $this->db->where('bookId',$data['bookingCode'])->update('booking',array('status'=>0));
				if($rs) {
					$res = array('status'=>1,'data'=>null);
				} else {
					$res = array('status'=>0,'message'=>'Cancel submission failed','code'=>'ER25');
				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}

 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function confirm($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
 				$res_count=$this->db->where('bookId',$data['bookingCode'])->get('booking')->num_rows();
 				if($res_count > 0) {
					$sql = "SELECT booking.id AS book_id,booking.event_id,booking.bookId AS bookingCode,
								   booking.qrcode,booking.no_of_ticket,booking.amount,venue.id AS venue_id,
								   booking.status AS book_status,event_gallery.media_url,venue.location,
								   customer.name AS customer_name,customer.profile_image,
								   booking.ticket_details,event_date_time.time,event_date_time.date,
								   venue.location_lat AS lat,venue.location_lng AS lng
						    FROM booking 
						    JOIN events ON booking.event_id=events.event_id 
						    JOIN event_date_time ON booking.event_date_id=event_date_time.id 
						    JOIN venue ON venue.id=events.venue_id 
						    LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id 
						    JOIN customer ON customer.customer_id=booking.customer_id 
						    WHERE booking.bookId='".$data['bookingCode']."'";
				    $result = $this->db->query($sql)->row_array();

	 				if(count($result)>0){
	 					$eData  = langTranslator($result['event_id'],'EVT');
	 					$result = array_merge($result,$eData);
	 					$vData  = langTranslator($result['venue_id'],'VEN');
	 					$result = array_merge($result,$vData);

	 					$res = array('status'=>1,'data'=>$result);
	 				} else {
	 					$res = array('status'=>0,'message'=>'Invalid booking code','code'=>'ER24');
	 				}
 				} else {
 					$res = array('status'=>0,'message'=>'Invalid booking code','code'=>'ER24');
 				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}

 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	public function userinfo($data){
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
 				$this->db->select('customer.name,customer.phone,customer.email,customer.profile_image AS image,customer.gender,users.id AS userId, customer.profile_city AS city');
	 			$this->db->where('users.id',$user_id);
		 		$this->db->from('users');
		 		$this->db->join('customer','customer.customer_id = users.id');
		 		$result = $this->db->get()->row();
		 		if($result){
		 			$res = array('status'=>1,'data'=>$result);
		 		} else {
		 			$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
		 		}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
 			} 			
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;	
 	}

    function imageResize($path,$size){
        $this->load->library('image_lib');
        $config['width']          = $size['width'];
        $config['height']         = $size['height'];
        $config['new_image']      = $path;
        $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();
    }

 	public function update_profile($data) {
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
		 		$post_data = $data;
		 		unset($post_data['file']);
		 		unset($post_data['auth_token']);
		 		$post_data['dob'] = (!empty($post_data['dob']))?strtotime($post_data['dob'])*1000:'';
		 		if(isset($post_data['city'])){
		 			$post_data['profile_city'] = $post_data['city'];
		 			unset($post_data['city']);
		 		}

	 			$state = $this->db->where('customer_id',$user_id)->update('customer',$post_data);
	 			if($state){
					$this->db->select('customer.name,customer.dob,customer.phone,customer.email,
		 							   customer.profile_image AS image,customer.gender,users.id AS userId,
		 							   customer.profile_image_qr,customer.profile_city AS city');
		 			$this->db->where('users.id',$user_id);
			 		$this->db->from('users');
			 		$this->db->join('customer','customer.customer_id = users.id');
			 		$result = $this->db->get()->row();
			 		
			 		if($result){
			 			$result->dob = (!empty($result->dob))?date("m/d/Y", ($result->dob)/1000):'';
			 			$res = array('status'=>1,'data'=>$result);
			 		} else {
			 			$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
			 		}
				} else {
					$res = array('status'=>0,'message'=>'Profile update failed','code'=>'ER32');
				}
		 	} else {
		 		$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
		 	} 
		} 
		catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function tempbooking($data) {
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$post_data = $data;
 				$status = (isset($post_data['has_payment']) && $post_data['has_payment'] == 0)?'1':'3';
				
 				$post_data['status'] 			= $status;
				$post_data['bookId'] 			= 'TO'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
				$post_data['qrcode'] 			= genQRcode($post_data['bookId']);
 				$post_data['customer_id'] 		= $user_id;
				$post_data['booking_date'] 		= date('Y-m-d H:i:s');
 				$post_data['ticket_details'] 	= json_encode($post_data['ticket_details']);

 				if(!isset($post_data['amount']) || $post_data['amount'] == ''){
 					$post_data['amount'] = 0;
 				}

 				$evtData = $this->db->get_where('event_date_time',array('event_id'=>$post_data['event_id'],
						        	    'date'=>$post_data['event_date'],'time'=>$post_data['event_time']));
				if(empty($evtData = $evtData->row_array()) || !isset($evtData['id']) || 
				   empty($post_data['event_date_id'] = $evtData['id'])){
					$res = array('status'=>0,'message'=>'Event date or time is invalid','code'=>'ER06');
				}

				$evtData = $this->db->get_where('events',array('event_id'=>$post_data['event_id']));
				$evtData = $evtData->row_array();
				if(!empty($evtData) && isset($evtData['approve_booking']) && $evtData['approve_booking']=='1'){
					$post_data['status'] = '6';
				}

				$promocodeData = array();
				if(isset($post_data['promocode_id']) && !empty($post_data['promocode_id']) && 
				   isset($post_data['redeem_amount']) && !empty($post_data['redeem_amount'])){

					$promoStatus   = ($post_data['status'] == '1')?1:0;
					$promocodeData = array('user_id'=>$user_id,'booking_id'=>$post_data['bookId'],
										   'promocode_id'=>$post_data['promocode_id'],
										   'redeem_amount'=>$post_data['redeem_amount'],
										   'created_date'=>date('Y-m-d H:i:s'),'status'=>$promoStatus);
				}
				$auth_token = $post_data['auth_token'];
				$card_data = (isset($post_data['cardData']))?$post_data['cardData']:array();
 				unset($post_data['auth_token'],$post_data['has_payment'],$post_data['cardData'],
 					  $post_data['promocode_id'],$post_data['redeem_amount'],$post_data['event_date'],
 					  $post_data['event_time']);

				$rs = $this->db->insert('booking', $post_data);
				$this->db->insert('orders',array('booking_id'=>$post_data['bookId'],'order_type'=>'1','created_date'=>date('Y-m-d h:i:s'),'customer_id'=>$user_id));
				if($rs){
					if(!empty($promocodeData)){
						$this->db->insert('promocode_used',$promocodeData);
					}
					$cardDetails = array();
					if(!empty($card_data)){
						switch($card_data->card_type) {
							case '1': $cardDetails['cardMode'] = 'DD'; break;
							case '2': $cardDetails['cardMode'] = 'CC'; break;
							default : $cardDetails['cardMode'] = 'CC'; break;
						}

						switch(substr($card_data->card_number,0,1)) {
							case '4': $cardDetails['cardType'] = 'VisaCard'; break;
							case '5': $cardDetails['cardType'] = 'Mastercard'; break;
							case '6': $cardDetails['cardType'] = 'DiscoverCard'; break;
							default : $cardDetails['cardType'] = 'Mastercard'; break;
						}

						$cardDetails['cvv'] = $card_data->card_cvv;
						$cardDetails['cardNumber'] = $card_data->card_number;
						$cardDetails['expMonthYear'] = $card_data->exp_date.$card_data->exp_year;
						$cardDetails['cardHolderName'] = $card_data->holder_name;
					}
		 			$reqData = array('amount'=>$post_data['amount'],'event_id'=>$post_data['event_id'],
		 							 'cardData'=>$cardDetails,'auth_token'=>$auth_token,
		 							 'booking_id'=>$post_data['bookId']);

		 			$res = array('status'=>1,'data'=>array('user_id'=>$user_id,
		 						 'bookingCode'=>$post_data['bookId'],'reqData'=>$reqData));

		 			if($status == 1){
		 				$sql = "SELECT TEVT.event_name,CUST.name,CUST.email,CUST.phone,
					            	   CONCAT(EDATE.date,' ',EDATE.time) AS show_time,PDR.fcm_token
					            FROM booking AS BK 
					            INNER JOIN events AS EVT ON (EVT.event_id=BK.event_id)
					            INNER JOIN provider AS PDR ON (PDR.provider_id=EVT.provider_id)
					            INNER JOIN customer AS CUST ON (CUST.customer_id=BK.customer_id)
					            INNER JOIN event_date_time AS EDATE ON (EDATE.id=BK.event_date_id)
					            INNER JOIN translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
					            WHERE EVT.status='1' AND BK.status IN ('1','6') AND EDATE.status='1' AND 
					                  TEVT.language_code='EN' AND BK.bookId='".$post_data['bookId']."'";
		          		$bkData = $this->db->query($sql)->row_array();

					    $subject    = "Your Tickets - TimeOut";
					    $showTime   = date("d'S F Y - h:i, (l)",strtotime($bkData['show_time']));
					    $msgContent = "Hi, Your booking is confirmed for the event '".
					    			   $bkData['event_name']."' and show is on '".$showTime."'. 
					    			   Booking ID ".$post_data['bookId'];
					    $message    = "<html><body><p>".$msgContent."</p></body></html>";

				        $template = getNotifTemplate();
			            if(isset($template['booking_mail']) && !empty($template['booking_mail'])){
			                $msgContent = str_replace(
					        				array('{:event_name}','{:booking_id}','{:time}'),
			    						    array($bkData['event_name'],$post_data['bookId'],$showTime),
			    						    $template['booking_mail']);
			            }
					    $this->send_mail($subject,$bkData['email'],$message);
					    
					    if(isset($template['booking_sms']) && !empty($template['booking_sms'])){
					        $msgContent = str_replace(
					        				array('{:event_name}','{:booking_id}','{:time}'),
			    						    array($bkData['event_name'],$post_data['bookId'],$showTime),
			    						    $template['booking_sms']);
					    }
					    $this->sendSMS($bkData['phone'],$msgContent);
					    if($post_data['status'] == 6){
					    	$userData = array('id'=>$post_data['bookId'],
							  'title'=>'New Booking',
							  'param'=>'booking_id',
							  'message'=>'New Booking is There For Approval');
	  						push_sent_cancel(2,$bkData['fcm_token'],$userData);
					    }
					}
		 		} else {
		 			$res = array('status'=>0,'message'=>'Seat booking failed','code'=>'ER37');
		 		}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
 			} 			
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function generateQR($data) {
 		return 'https://www.barcodefaq.com/wp-content/uploads/2018/08/gs1-qrcode-fnc1.png';
 	}

 	function recommend($data) {
 		try {
 			$locCond = '';
 			$per_page = 10;
 			$user_id = $this->auth_token_get($data['auth_token']);

 			if(isset($data['city_id']) && !empty($data['city_id'])){
 				$locCond = " AND venue.region_id='".$data['city_id']."'";
 			}

			$languages = getLanguages();	
			$tagDummy = array();
			foreach ($languages AS $lang) {
		 		$tagDummy['tag_'.$lang] = array();
		 	} 	
 			if($user_id > 0) {
 				$count = $this->db->query("
 					SELECT events.event_id 
 					FROM events 
 					INNER JOIN venue ON venue.id = events.venue_id
 					INNER JOIN event_date_time ON events.event_id = event_date_time.event_id
 					WHERE events.status = 1 AND event_date_time.status='1' AND  						  
 						  event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d') $locCond
 					GROUP BY events.event_id")->num_rows();
 				if($count > 0) {

 					if(isset($data['page'])) {
 						$page = $data['page']; 						
 					} else {
 						$page = 1;
 					}

 					$page_limit = ($page - 1) * $per_page;

 					if($count > $page_limit) {
 						$this->db->query("SET SESSION group_concat_max_len = 200000");
 						$sql = "SELECT events.event_id,venue.location,events.seat_pricing,venue.id AS venue_id,
 									   events.custom_seat_layout,venue.layout,venue.layout_details,
 									   event_gallery.media_url,favourite.status AS fav_status,
 									   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
 							FROM events 
 							INNER JOIN event_date_time ON events.event_id = event_date_time.event_id
 							INNER JOIN venue ON venue.id = events.venue_id 
 							LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
 											           event_gallery.media_type=0 
 							LEFT JOIN booking ON booking.event_id = events.event_id 
 							LEFT JOIN favourite ON favourite.event_id = events.event_id AND 
 												   favourite.user_id = '$user_id' AND favourite.status = 1 
 							LEFT JOIN event_tags ON events.event_id = event_tags.event_id 
 							WHERE events.status = 1 AND event_date_time.status='1' AND 
 								  event_date_time.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') $locCond
 							GROUP BY events.event_id 
 							LIMIT $page_limit,$per_page";
 						$result = $this->db->query($sql)->result();

						if(count($result)>0){
							$resultData = array();
							foreach ($result as $rs) {
								if(!empty($dates = explode(',',$rs->date_time))){
									$checkTime = 0;
									foreach ($dates as $date) {
										$dArr = explode('#', $date);
										if($dArr[1] == date("Y-m-d") && 
										   $dArr[1].' '.$dArr[2] < date("Y-m-d H:i", strtotime('+15 minutes'))){
											$checkTime += 1;
										}
									}
									if($checkTime == count($dates)){
										continue;
									}
								} else {
									continue;
								}

								$sql    = "SELECT AVG(review.rate) AS rate 
										   FROM review WHERE event_id=$rs->event_id";
								$rating = $this->db->query($sql)->row_array();
								$rate   = isset($rating['rate'])&&!empty($rating['rate'])?
										  round($rating['rate'],1):'0.0';

								$sql    = "SELECT SUM(booking.no_of_ticket) AS attend FROM booking 
										   WHERE status IN (1,2) AND event_id=$rs->event_id";
								$atten  = $this->db->query($sql)->row_array();
								$atte   = isset($atten['attend'])&&!empty($atten['attend'])?
											$atten['attend']:'0';

								if($rs->layout!=''){
									if($rs->custom_seat_layout!=''){
										$pricelist = json_decode($rs->custom_seat_layout, TRUE);
										$price = min(array_column($pricelist, 'price'));
									} else {
										$pricelist = json_decode($rs->layout_details, TRUE);
										$price = min(array_column($pricelist, 'price'));
									}
								} else {
									$pricelist = json_decode($rs->seat_pricing, TRUE);
									$price = $pricelist['price'];
								}

								$tagArr = array();
								$resData = array();

								$resData['rate'] = $rate;
								$resData['price'] = $price;
								$resData['event_id'] = $rs->event_id;
								$resData['attendees'] = $atte;
								$resData['media_url'] = $rs->media_url;
								$resData['fav_status'] = $rs->fav_status;
								$resData['venue_location'] = $rs->location;

								$evtData = langTranslator($rs->event_id,'EVT');
								$resData = array_merge($resData,$evtData);

								$venData = langTranslator($rs->venue_id,'VEN');
								$resData = array_merge($resData,$venData);

								if(!empty($rs->tag_ids) && !empty($tag_ids = explode(',',$rs->tag_ids))){
									foreach ($tag_ids AS $key => $id) {
										$tags = langTranslator($id,'TAG');
										foreach ($tags AS $key => $id) {
											if(isset($tagArr[$key])){
												$tagArr[$key][] = $id;
											} else {
												$tagArr[$key] = array($id);
											}
										}
								 	} 
								} else {
									$tagArr = $tagDummy;
								}
								$resData = array_merge($resData,$tagArr);
								array_push($resultData, $resData);
							}
							
							$meta = array('total_pages'=>ceil($count/$per_page),
		 									  'total'=>$count,
		 									  'current_page'=>$page,
		 									  'per_page'=>$per_page
		 									 );
							$response = array('data'=>$resultData,'meta'=>$meta);
							$res = array('status'=>1,'data'=>$response);
						} else {
							$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
						}
					} else {
 						$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 					}
 				} else {
 					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}

 	function discover($data) {

 		try {
			$cat_id = $data['cat_id'];
			$city_id = $data['city'];
			$category = $this->db->where('cat_id',$cat_id)->get('event_category')->row();
			$this->db->query("SET SESSION group_concat_max_len = 200000");
			$sql = "SELECT events.event_id,events.seat_pricing,events.custom_seat_layout,venue.layout, 
						   venue.layout_details,event_gallery.media_url,GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time 
				    FROM events 
				    INNER JOIN venue ON venue.id=events.venue_id 
				    INNER JOIN event_date_time ON events.event_id=event_date_time.event_id AND 
				    							  event_date_time.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') 
				    LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
				    						   event_gallery.media_type=0 
				    WHERE events.status=1 AND events.category_id='$cat_id' AND 
			    		  event_date_time.status='1' AND venue.region_id='$city_id'
				    GROUP BY events.event_id";
			$result = $this->db->query($sql)->result();

			if(count($result)>0){
				$resultData = array();
				foreach ($result as $rs) {
					if(!empty($dates = explode(',',$rs->date_time))){
						$checkTime = 0;
						foreach ($dates as $date) {
							$dArr = explode('#', $date);
							if($dArr[1] == date("Y-m-d") && 
							   $dArr[1].' '.$dArr[2] < date("Y-m-d H:i", strtotime('+15 minutes'))){
								$checkTime += 1;
							}
						}
						if($checkTime == count($dates)){
							continue;
						}
					} else {
						continue;
					}

					if($rs->layout!=''){
						if($rs->custom_seat_layout!=''){
							$pricelist = json_decode($rs->custom_seat_layout, TRUE);
							$price = min(array_column($pricelist, 'price'));
						} else {
							$pricelist = json_decode($rs->layout_details, TRUE);
							$price = min(array_column($pricelist, 'price'));
						}
					} else {
						$pricelist = json_decode($rs->seat_pricing, TRUE);
						$price = $pricelist['price'];
					}
					$resData = langTranslator($rs->event_id,'EVT');
					$resData['price'] = $price;
					$resData['event_id'] = $rs->event_id;
					$resData['media_url'] = $rs->media_url;
					array_push($resultData, $resData);
				}
				$category->data = $resultData;
				$res = array('status'=>1,'data'=>$category);
			} else {
				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}


 	function event($data) {
 		try {
 			$bookedCount = 0;
			$event_id    = $data['event_id'];
			if(isset($data['auth_token']) && !empty($data['auth_token'])){
				$user_id = $this->auth_token_get($data['auth_token']); 
			}

			$tagDummy = array();
			$languages = getLanguages();	
			foreach ($languages AS $lang) {
		 		$tagDummy['tag_'.$lang] = array();
		 	} 	
		 	
 			if(!empty($user_id)) {
 				$sql = "SELECT SUM(no_of_ticket) AS bookCount FROM booking AS BOK
						WHERE event_id='$event_id' AND customer_id='$user_id' AND status IN (1)";
				$result = $this->db->query($sql)->row_array();
				if(!empty($result)){
					$bookedCount = $result['bookCount'];
				}
 			}

			$this->db->query("SET SESSION group_concat_max_len = 200000");
			$sql = "SELECT events.has_payment,events.event_id,events.seat_pricing,venue.layout,
						   events.custom_seat_layout,venue.id AS venue_id,events.seat_pricing,
						   venue.layout_details,events.max_booking,venue.location,
						   venue.location_lat AS lat,venue.location_lng AS lng, 
						   favourite.status AS fav_status,host_categories.show_layout,
						   GROUP_CONCAT(DISTINCT event_gallery.media_url) AS media_url,
						   GROUP_CONCAT(DISTINCT event_tags.tag_id) AS tag_ids,
						   GROUP_CONCAT(DISTINCT event_date_time.date) AS event_date,
						   GROUP_CONCAT(DISTINCT event_date_time.time) AS event_time
					FROM events 
				    INNER JOIN event_date_time ON events.event_id = event_date_time.event_id 
				    INNER JOIN venue ON venue.id = events.venue_id 
				    LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
				   			                  event_gallery.status!=0 
                    LEFT JOIN favourite ON favourite.event_id=events.event_id AND 
                   						  favourite.status=1 AND favourite.user_id='$user_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.event_id='$event_id' AND event_date_time.status='1'
					GROUP BY events.event_id, event_date_time.event_id";
			$result = $this->db->query($sql)->result();

			if(count($result)>0){
				$resultData = array();
				$event_layout = '';
				foreach ($result as $rs) {
					$sql = "SELECT AVG(review.rate) AS rate 
							FROM review WHERE event_id=$rs->event_id";
					$rating = $this->db->query($sql)->row_array();
					$rate=isset($rating['rate'])&&!empty($rating['rate'])?$rating['rate']:'0.0';

					$sql = "SELECT SUM(booking.no_of_ticket) AS attend FROM booking 
							WHERE status IN (1,2) AND event_id=$rs->event_id";
					$atten = $this->db->query($sql)->row_array();
					$atte=isset($atten['attend'])&&!empty($atten['attend'])?$atten['attend']:'0';
					$latlng = array('lat'=>$rs->lat, 'lng'=>$rs->lng);
					if($rs->layout!=''){
						if($rs->custom_seat_layout!=''){
							$pricelist = json_decode($rs->custom_seat_layout, TRUE);
							$price = min(array_column($pricelist, 'price'));
							$event_layout = $rs->custom_seat_layout;
						} else {
							$pricelist = json_decode($rs->layout_details, TRUE);
							$price = min(array_column($pricelist, 'price'));
							$event_layout = $rs->layout_details;
						}
					} else {
						$pricelist = json_decode($rs->seat_pricing, TRUE);
						$price = $pricelist['price'];
						$event_layout = $rs->seat_pricing;
					}

					$resData = array();
					$resData['latlng'] = $latlng;
					$resData['event_id'] = $rs->event_id;
					$resData['event_date'] = explode(',',$rs->event_date);
					$resData['event_time'] = explode(',',$rs->event_time);
					$resData['event_rate'] = $rate;
					$resData['event_urls'] = explode(',',$rs->media_url);
					$resData['fav_status'] = $rs->fav_status;
					$resData['event_price'] = $price;
					$resData['has_payment'] = $rs->has_payment;
					$resData['max_booking'] = $rs->max_booking-$bookedCount;
					$resData['show_layout'] = $rs->show_layout;
					$resData['seat_pricing'] = $rs->seat_pricing;
					$resData['venue_location'] = $rs->location;
					$resData['event_attendees'] = $atte;
					$resData['event_layout_url'] = $rs->layout;
					$resData['event_price_layout'] = $event_layout;

					$evtData = langTranslator($rs->event_id,'EVT');
					$resData = array_merge($resData,$evtData);

					$venData = langTranslator($rs->venue_id,'VEN');
					$resData = array_merge($resData,$venData);

					$tagArr  = array();
					if(!empty($rs->tag_ids) && !empty($tag_ids = explode(',',$rs->tag_ids))){
						foreach ($tag_ids AS $key => $id) {
							$tags = langTranslator($id,'TAG');
							foreach ($tags AS $key => $id) {
								if(isset($tagArr[$key])){
									$tagArr[$key][] = $id;
								} else {
									$tagArr[$key] = array($id);
								}
							}
					 	} 
					} else {
						$tagArr = $tagDummy;
					}
					$resData = array_merge($resData,$tagArr);
					array_push($resultData, $resData);
				}
				$res = array('status'=>1,'data'=>$resultData);
			} else {
				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
			}
 			
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}

 	function search($data) {
 		try {
 			$per_page = 10;
			$where = $case = '';
			$user_id = (!isset($data['auth_token']) || empty($data['auth_token']))?'':$this->auth_token_get($data['auth_token']); 	

			$languages = getLanguages();	
			$tagDummy = array();
			foreach ($languages AS $lang) {
		 		$tagDummy['tag_'.$lang] = array();
		 	} 	

			if(isset($data['cat_id']) && !empty($data['cat_id'])) {
				$where = ' AND events.category_id='.$data['cat_id'];
			}

			if(isset($data['choose_date']) && !empty($data['choose_date'])) {
				switch ($data['choose_date']) {
					case '1':$case = "";break;
					case '2':$case = "AND event_date_time.date = DATE_FORMAT(NOW(),'%Y-%m-%d')";break;
					case '3':
						$case = "AND event_date_time.date = DATE_FORMAT(NOW() + INTERVAL 1 DAY,'%Y-%m-%d')";
						break;
					case '4':
						$first_day_of_the_week = 'Monday';
						$start_of_the_week     = strtotime("Last $first_day_of_the_week");
						if ( strtolower(date('l')) === strtolower($first_day_of_the_week) ) {
						    $start_of_the_week = strtotime('today');
						}
						$end_of_the_week = $start_of_the_week + (60 * 60 * 24 * 7) - 1;
						$date_format =  'Y-m-d';
						$start_date =  date($date_format, $start_of_the_week);
						$end_date = date($date_format, $end_of_the_week);
						$case = "AND event_date_time.date>=$start_date AND event_date_time.date<=$end_date";
						break;
					case '5':
						$sunday = date( 'Y-m-d', strtotime( 'sunday this week'));
						$saturday = date( 'Y-m-d', strtotime( 'saturday this week'));
						$case = "AND event_date_time.date = $sunday OR event_date_time.date = $saturday";
						break;
				}
			}

			$sql = "SELECT events.event_id FROM events 
		 		    INNER JOIN event_date_time ON events.event_id=event_date_time.event_id $case 
		 		    WHERE events.status = 1 AND event_date_time.status='1' $where 
		 		    GROUP BY events.event_id";
			$count = $this->db->query($sql)->num_rows();

			if(isset($data['venue_id']) && !empty($data['venue_id'])) {
				$where .= " AND locality.id ='".$data['venue_id']."'";
			}

			if(isset($data['city_id']) && !empty($data['city_id'])) {
				$where .= " AND venue.region_id='".$data['city_id']."'";
			}

			if($count > 0) {
				if(isset($data['page'])) {
					$page = $data['page']; 						
				} else {
					$page = 1;
				}
				$page_limit = ($page - 1) * $per_page;

				if($count > $page_limit) {
					$this->db->query("SET SESSION group_concat_max_len = 200000");
					$result = $this->db->query("
						SELECT events.event_id,venue.id AS venue_id,venue.location,events.seat_pricing,
							   venue.layout,venue.layout_details,events.custom_seat_layout,
							   event_gallery.media_url,favourite.status AS fav_status,
							   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 
						FROM events 
						INNER JOIN event_date_time ON events.event_id=event_date_time.event_id $case
						INNER JOIN venue ON venue.id=events.venue_id 
						LEFT JOIN locality ON locality.id=venue.locality_id
						LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
												   event_gallery.media_type=0 
						LEFT JOIN favourite ON favourite.event_id=events.event_id AND 
						          			   favourite.user_id='$user_id' AND favourite.status=1 
						LEFT JOIN event_tags ON events.event_id=event_tags.event_id AND event_tags.status=1
						WHERE events.status=1 AND event_date_time.status='1' AND 
							  event_date_time.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') $where 
						GROUP BY events.event_id 
						ORDER BY events.event_id DESC LIMIT $page_limit,$per_page")->result();

			if(count($result)>0){
				$resultData = array();
				foreach ($result as $rs) {
					if(!empty($dates = explode(',',$rs->date_time))){
						$checkTime = 0;
						foreach ($dates as $date) {
							$dArr = explode('#', $date);
							if($dArr[1] == date("Y-m-d") && 
							   $dArr[1].' '.$dArr[2] < date("Y-m-d H:i", strtotime('+15 minutes'))){
								$checkTime += 1;
							}
						}
						if($checkTime == count($dates)){
							continue;
						}
					} else {
						continue;
					}

					$sql    = "SELECT AVG(review.rate) AS rate 
							   FROM review WHERE event_id=$rs->event_id";
					$rating = $this->db->query($sql)->row_array();
					$rate   = isset($rating['rate'])&&!empty($rating['rate'])?
							  $rating['rate']:'0.0';

					$sql    = "SELECT SUM(booking.no_of_ticket) AS attend FROM booking 
							   WHERE status IN (1,2) AND event_id=$rs->event_id";
					$atten  = $this->db->query($sql)->row_array();
					$atte   = isset($atten['attend'])&&!empty($atten['attend'])?
								$atten['attend']:'0';

					if($rs->layout!=''){
						if($rs->custom_seat_layout!=''){
							$pricelist = json_decode($rs->custom_seat_layout, TRUE);
							$price = min(array_column($pricelist, 'price'));
						} else {
							$pricelist = json_decode($rs->layout_details, TRUE);
							$price = min(array_column($pricelist, 'price'));
						}
					} else {
						$pricelist = json_decode($rs->seat_pricing, TRUE);
						$price = $pricelist['price'];
					}

					$tagArr = array();
					$resData = array();

					$resData['rate'] = $rate;
					$resData['price'] = $price;
					$resData['event_id'] = $rs->event_id;
					$resData['attendees'] = $atte;
					$resData['media_url'] = $rs->media_url;
					$resData['fav_status'] = $rs->fav_status;
					$resData['venue_location'] = $rs->location;

					$evtData = langTranslator($rs->event_id,'EVT');
					$resData = array_merge($resData,$evtData);

					$venData = langTranslator($rs->venue_id,'VEN');
					$resData = array_merge($resData,$venData);

					if(!empty($rs->tag_ids) && !empty($tag_ids = explode(',',$rs->tag_ids))){
						foreach ($tag_ids AS $key => $id) {
							$tags = langTranslator($id,'TAG');
							foreach ($tags AS $key => $id) {
								if(isset($tagArr[$key])){
									$tagArr[$key][] = $id;
								} else {
									$tagArr[$key] = array($id);
								}
							}
					 	} 
					} else {
						$tagArr = $tagDummy;
					}
					$resData = array_merge($resData,$tagArr);
					array_push($resultData, $resData);
				}
				$meta = array('total_pages'=>ceil($count/$per_page),'total'=>$count,
							  'current_page'=>$page,'per_page'=>$per_page);

				$response = array('data'=>$resultData,'meta'=>$meta);
				$res = array('status'=>1,'data'=>$response);
			} else {
				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
			}
		} else {
					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
				}
			} else {
				$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
			}
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}


	function searchEvent($data) {
 		$str = urldecode(strtolower($data['str']));

		$this->db->query("SET SESSION group_concat_max_len=20000");
		$sql = "SELECT GROUP_CONCAT(DISTINCT CONCAT_WS('#',EDATE.id,EDATE.date,EDATE.time)) 
					   AS date_time,EVT.event_id
				FROM events AS EVT
				INNER JOIN event_date_time AS EDATE ON (EVT.event_id=EDATE.event_id)
				INNER JOIN translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
				WHERE TEVT.event_name LIKE '%$str%' AND EDATE.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND 
					  EVT.status='1' AND EDATE.status='1'
	  		    GROUP BY EVT.event_id LIMIT 5";
		$resCount = $this->db->query($sql)->result_array();
		
		if(!empty($resCount)){
			foreach ($resCount AS $key => $rs) {
			  	if(!empty($dates = explode(',',$rs['date_time']))){
					$checkTime = 0;
					foreach ($dates as $date) {
						if(empty($date)){ unset($resCount[$key]); continue; }

						$dArr = explode('#', $date);
						if($dArr[1] == date("Y-m-d") && 
						   $dArr[1].' '.$dArr[2] < date("Y-m-d H:i", strtotime('+15 minutes'))){
							$checkTime += 1;
						}
					}
					if($checkTime == count($dates)){ 
						unset($resCount[$key]); 
						continue; 
					}
					$evtData = langTranslator($rs['event_id'],'EVT');
					$resCount[$key] = array_merge($resCount[$key],$evtData);
				} else { 
					unset($resCount[$key]); continue; 
				}
				unset($resCount[$key]->date_time);
			}
		}
		$sEvents = (!empty($resCount))?$resCount:[];

 		$region = $this->db->query("SELECT REG.id FROM region AS REG
 									INNER JOIN translator_region AS TREG ON (TREG.region_id=REG.id)
 			                        WHERE TREG.region_name LIKE '%$str%' AND REG.status=1 
	                                GROUP BY REG.id LIMIT 5")->result_array();
 		if(!empty($region)){
 			foreach ($region AS $key => $regData) {
 				$reg = langTranslator($regData['id'],'REG');
 				$region[$key] = array_merge($region[$key],$reg);
 			}
 		}
 		$response = array('events'=>$sEvents, 'cityList'=>$region);
 		$res = array('status'=>1,'data'=>$response);
 		return $res;
 	}

 	function getUserData($cust_id = ''){
 		if(empty($cust_id)){
 			return 0;
 		}
	    $this->db->select('customer.name,customer.dob,customer.phone,customer.email,customer.gender,
	    				   customer.profile_image AS image,users.id AS userId,customer.profile_city AS city,customer.dob,
	    				   customer.email_verified');
		$this->db->where('users.status',1);
 		$this->db->where('customer.customer_id',$cust_id);
 		$this->db->from('users');
 		$this->db->join('customer','customer.customer_id = users.id');
 		return $this->db->get()->row();
 	}

 	function payNow($data){
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$callback_url = (isset($data['callback_url']))?$data['callback_url']:'';
 				$insertData = array('customer_id'=>$user_id,'booking_id'=>$data['booking_id'],
 								    'datetime'=>date('Y-m-d h:i:s'),'amount'=>$data['amount'],
 								    'callback_url'=>$callback_url);
				$this->db->insert('transaction',$insertData);
				$last_id = $this->db->insert_id();

				$custData = $this->getUserData($user_id);
				$res = array('status'=>1,'transaction_id'=>$last_id,'custData'=>$custData);
			}else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		}
 		return $res; 
 	}

 	function updateWalletTxn($txnData = array()){
 		try{
 			if(empty($txnData)){
 				return;
 			}
 			if($txnData['status'] == '0'){
 				if(!isset($txnData['mode']) || empty($txnData['mode']) || 
 				   !isset($txnData['amount']) || empty($txnData['amount']) || 
 				   !isset($txnData['auth_token']) || empty($txnData['auth_token'])){
 					return;
 				}
 				$user_id = $this->auth_token_get($txnData['auth_token']);
 				if(empty($user_id)){
 					return;
 				}
 				$txnCode = 'TXN'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
				$insertData = array('customer_id'=>$user_id,'transaction_type'=>$txnData['mode'],
									'created_date'=>date('Y-m-d h:i:s'),'amount'=>$txnData['amount'],
									'transaction_code'=>$txnCode,'status'=>0);
				$this->db->insert('wallet_transactions',$insertData);
				return array('status'=>1,'transaction_id'=>$txnCode);
 			} else {
 				if(!isset($txnData['tnx_id']) || empty($txnData['tnx_id'])){
 					return;
 				}
 				$this->db->update('wallet_transactions',array('status'=>$txnData['status']),
 												        array('transaction_code'=>$txnData['tnx_id']));
 				if($txnData['status'] == 1){
 					$cond = array('transaction_code'=>$txnData['tnx_id'],'status'=>'1');
 					$lastTxn = $this->db->get_where('wallet_transactions',$cond)->row_array();
 					
 					$amount = $lastTxn['amount'];
 					$customer_id = $lastTxn['customer_id'];
 					$sql = "UPDATE wallet SET balance_amount=balance_amount+$amount
 							WHERE customer_id=$customer_id";
 					$this->db->query($sql);
 				}
 			}
 		}catch(Exception $e){}
 	}

 	function update_payment($response='',$transactionid='',$last_id,$status,$eventid = ''){
 		try{
 			if(empty($last_id)){
 				return;
 			}
 			$this->db->update('transaction',array('transaction_id'=>$transactionid,'status'=>$status,
			 				              	      'transaction_response'=>json_encode($response)),
 				              				array('id'=>$last_id));
 			$callback_url = '';
 			$transResp = $this->db->get_where('transaction',array('id'=>$last_id))->row_array();
 			if(!empty($transResp)){
 				$callback_url = $transResp['callback_url'];
 			}
 			if($status == 1){
	 			$trBook = $this->db->get_where('transaction',array('id'=>$last_id))->row_array();
	 			$book_id = $trBook['booking_id'];

				$sql = "SELECT TEVT.event_name,CONCAT(EDATE.date,' ',EDATE.time) AS show_time,
			            	   CUST.name,CUST.email,CUST.phone,EVT.approve_booking,PDR.fcm_token
			            FROM booking AS BK 
			            INNER JOIN events AS EVT ON (EVT.event_id=BK.event_id)
					    INNER JOIN provider AS PDR ON (PDR.provider_id=EVT.provider_id)
			       	    INNER JOIN translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
			            INNER JOIN customer AS CUST ON (CUST.customer_id=BK.customer_id)
			            INNER JOIN event_date_time AS EDATE ON (EDATE.id=BK.event_date_id)
			            WHERE BK.bookId='".$trBook['booking_id']."' AND EVT.status='1' AND 
			                  BK.status IN('3','6') AND EDATE.status='1' AND TEVT.language_code='EN'";
          		$bkData = $this->db->query($sql)->row_array();

          		$bokStatus = '1';
			    if(!empty($bkData)){
		    		$bokStatus  = (isset($bkData['approve_booking'])&&$bkData['approve_booking']=='1')?'6':'1';

				    $subject    = "Your Tickets - TimeOut";
				    $showTime   = date("d'S F Y - h:i, (l)",strtotime($bkData['show_time']));
				    $msgContent = "Hi, Your booking is confirmed for the event '".$bkData['event_name'].
				    			  "' and show is on '".$showTime."'. Booking ID ".$trBook['booking_id'];
				    $message    = "<html><body><p>".$msgContent."</p></body></html>";

			        $template = getNotifTemplate();
		            if(isset($template['booking_mail']) && !empty($template['booking_mail'])){
		                $msgContent = str_replace(
				        				array('{:event_name}','{:booking_id}','{:time}'),
		    						    array($bkData['event_name'],$trBook['booking_id'],$showTime),
		    						    $template['booking_mail']);
		            }
				    $this->send_mail($subject,$bkData['email'],$message);

				    if(isset($template['booking_sms']) && !empty($template['booking_sms'])){
				        $msgContent = str_replace(array('{:event_name}','{:booking_id}','{:time}'),
		    						    		  array($bkData['event_name'],$trBook['booking_id'],$showTime),
	    						    			  $template['booking_sms']);
				    }
				    $this->sendSMS($bkData['phone'],$msgContent);
				    if($bokStatus == '6'){
				    	$userData = array('id'=>$book_id,
						  'title'=>'New Booking',
						  'param'=>'booking_id',
						  'message'=>'New Booking is There For Approval');
  						push_sent_cancel(2,$bkData['fcm_token'],$userData);
				    }
			    }
          		$this->db->update('booking',array('status'=>$bokStatus),array('bookId'=>$book_id));
          		$this->db->update('event_invites',array('status'=>'1'),array('book_id'=>$book_id));
          		$this->db->update('promocode_used',array('status'=>'1'),array('booking_id'=>$book_id));
 			}
 			$res = array('status'=>1,'callback_url'=>$callback_url);
 		}catch(Exception $e){
 			$res = array('status'=>0,'callback_url'=>$callback_url);
 		}
 		return $res; 
 	}

 	function get_cms_data(){
 		$language = array();
 		try{
 			$cmsData = $this->db->get('translator_policies')->result_array();
 			if(!empty($cmsData)){
 				foreach ($cmsData AS $cms) {
 					$lang = $cms['language_code'];
 					$language['faq_'.$lang] = $cms['faq'];
 					$language['instruction_'.$lang] = $cms['instruction'];
 					$language['privacy_policy_'.$lang] = $cms['privacy_policy'];
 					$language['terms_and_conditions_'.$lang] = $cms['terms_and_conditions'];
 				}
 				$res = array('status'=>1,'data'=>$language);
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		}
 		return $res; 
 	}

 	public function save_organizer($data){
 		try{
 			$data['phone'] = preg_replace('/\D/', '', $data['phone']);
	 		$userNameChk = $this->db->query("SELECT * FROM users 
 									     	 WHERE user_type='2' AND status!='2' AND 
 									     		   username='".$data['email_id']."'");
	 		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 LIKE '%".$data['phone']."%'");
	 		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['email_id'],'display_name'=>$data['name'],
							  'password'=>md5($data['password']),'user_type'=>'2','status'=>'0'));

 			$last_id = $this->db->insert_id();
 			if($this->db->insert('provider',array('provider_id'=>$last_id,'name'=>$data['name'],
 												  'email'=>$data['email_id'],'phone'=>$data['phone']))){
 				$res = array('status'=>1);	
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		}
 		return $res;
 	}

	public function reset_password($data){
		try{
			$cust = $this->db->query("SELECT CUST.customer_id FROM customer AS CUST
									INNER JOIN users AS USER ON (USER.id=CUST.customer_id)
									WHERE CUST.reset_key='".$data['reset_key']."' AND USER.status!='2'");
			if(!empty($cust)){
				$cust = $cust->row_array();
				if($this->db->update('users',array('password'=>md5($data['password'])),
											 array('id'=>$cust['customer_id']))){
					$this->db->update('customer',array('reset_key'=>''),
												 array('customer_id'=>$cust['customer_id']));
				    $res= array('status'=>1,'data'=>'Password Updated Successfully');
				}else{
				    $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER24');
				}
			} else {
			    $res = array('status'=>0,'message'=>'Sorry, Reset Key Expired','code'=>'ER25');
			}
		}catch(Exception $e){
		  	$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		}
		return $res;
	}

	public function verifyMail($data = ''){
		$settings   = getSettings();
		$redUrl     = $settings['web_base_url'];
		try{
			$cust = $this->db->query("SELECT CUST.customer_id,CUST.email,CUST.phone 
									  FROM customer AS CUST
									  INNER JOIN users AS USER ON (USER.id=CUST.customer_id)
									  WHERE CUST.confirm_link='".$data['unique_id']."' AND USER.status!='2'");

			if(!empty($cust) && !empty($cust = $cust->row_array())){
				$email    = $cust['email'];
				$subject  = "New account created successfully";
				$message  = "Hi, Welcome to TimeOut. Please use username: ".$email.
				            " for access your account";

	 			if(isset($template['registration_mail']) && !empty($template['registration_mail'])){
	               $message=str_replace(array('{:email}'),array($email),$template['registration_mail']);
	            }
	            $this->send_mail($subject,$email,$message);

	 			if(isset($template['registration_sms']) && !empty($template['registration_sms'])){
	                $message=str_replace(array('{:email}'),array($email),$template['registration_sms']);
	            }
	            $this->sendSMS($cust['phone'],$message);

				if($this->db->update('customer',array('confirm_link'=>'','email_verified'=>'1'),
												array('customer_id'=>$cust['customer_id']))){
					header('Location:'.$redUrl.'location?login=1');
				}
			}
		}catch(Exception $e){}
		header('Location:'.$redUrl.'location');
	}

	public function checkSeatAvailability($data = ''){
		try{
 			$date   	 = $data['date'];
 			$time  	 	 = $data['time'];
 			$user_id 	 = $this->auth_token_get($data['auth_token']);
 			$event_id 	 = $data['event_id'];
	    	$lyCapacity  = array();

	    	$capacity = $usrBooked = $maxBooking = 0;
 			$sql = "SELECT EDATE.date,EDATE.time,EVT.custom_seat_layout,EVT.seat_pricing,
 			               EVT.max_booking,VEN.layout_details,HST.show_layout 
				    FROM events AS EVT 
				    INNER JOIN venue AS VEN ON (VEN.id=EVT.venue_id) 
				    INNER JOIN event_date_time AS EDATE ON (EVT.event_id=EDATE.event_id) 
				    INNER JOIN host_categories AS HST ON (VEN.host_cat_id=HST.host_cat_id) 
				    WHERE EVT.event_id='$event_id' AND EDATE.date='$date' AND EDATE.time='$time' AND 
				    	  EDATE.status='1' AND EDATE.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
		    $evtSql = $this->db->query($sql);

		    if(empty($evtSql) || empty($evtData = $evtSql->row_array())){
		    	return array('status'=>0,'message'=>'No Record Found','code'=>'ER25');
		    }

		    if($evtData['date'].' '.$evtData['time'] < date("Y-m-d H:i", strtotime('+15 minutes'))){
				return array('status'=>0,'message'=>'Booking Closed','code'=>'ER26');
			}

 			if(!empty($user_id)){
				$sql = "SELECT SUM(BOK.no_of_ticket) AS bookCount
						FROM booking AS BOK
						INNER JOIN event_date_time AS EDATE ON (BOK.event_date_id=EDATE.id)
						WHERE BOK.event_id='$event_id' AND BOK.customer_id='$user_id' AND 
						      EDATE.date='$date' AND EDATE.time='$time' AND EDATE.status='1' AND 
						      BOK.status IN (1,2)";

				$result = $this->db->query($sql)->row_array();
				$usrBooked = (!empty($result))?$result['bookCount']:0;
			}

		    $maxBooking = $evtData['max_booking']-$usrBooked;
		    if($evtData['show_layout'] == 0){
		    	$lyout = json_decode($evtData['seat_pricing'],true);
		    	$capacity = $lyout['capacity'];
		    } else {
		    	$lyout = (!empty($evtData['custom_seat_layout']))
						 ?json_decode($evtData['custom_seat_layout'],true)
						 :json_decode($evtData['layout_details'],true);

	 			foreach($lyout AS $custLy) {
	 				$lyCapacity[$custLy['color']] = $custLy['capacity'];
	 			}
		    }

			$sql = "SELECT BOOK.no_of_ticket,BOOK.ticket_details
				    FROM booking AS BOOK 
				    INNER JOIN event_date_time AS EDATE ON (BOOK.event_date_id=EDATE.id) 
				    WHERE EDATE.status='1' AND BOOK.event_id='$event_id' AND EDATE.date='$date' AND 
				    	  EDATE.time='$time'";

		    if(!empty($result = $this->db->query($sql)->result_array())){
		    	foreach($result AS $value) {
			    	if($evtData['show_layout'] == 0){
			    		$capacity = $capacity-$value['no_of_ticket'];
			    	} else {
			    		$tkDtls = json_decode($value['ticket_details'],true);
			    		$aval = $lyCapacity[$tkDtls['color']];
			    		$aval = ($tkDtls['no_ticket']>$aval)?0:$aval-$tkDtls['no_ticket'];
			    		$lyCapacity[$tkDtls['color']] = $aval;
			    	}
		    	}
		    }

		    if($evtData['show_layout'] == 0){
		    	$capacity = ($capacity < $maxBooking)?$capacity:$maxBooking;
	    	} else {
	    		foreach($lyCapacity AS $block => $avail) {
	    			$lyCapacity[$block] = ($avail < $maxBooking)?$avail:$maxBooking;
	    		}
	    	}
	    	$res = array('status'=>1,'data'=>array('capacity'=>$capacity,'lyCapacity'=>$lyCapacity,
							    				   'show_layout'=>$evtData['show_layout']));
		} catch(Exception $e) {
		  	$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
	  	}
  		return $res;
	}

	function sendSMS($phone_no, $message) {
		$phone_no = trim($phone_no);
		$phone_no = trim($phone_no,'+');
		if(empty($phone_no) && count($phone_no) < 10 && empty($message)){
			return;
		}

		$user     = "eventstimeout";
		$senderid = "SMSCountry";
		$password = "timeout2030";
		$url      = "http://www.smscountry.com/SMSCwebservice_Bulk.aspx";
		$message  = urlencode($message);

		if($ch = curl_init()){
			$ret = curl_setopt ($ch, CURLOPT_URL, $url);
				   curl_setopt ($ch, CURLOPT_POST, 1);
				   curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
				   curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);
				   curl_setopt ($ch, CURLOPT_POSTFIELDS, "User=$user&passwd=$password&mobilenumber=$phone_no&message=$message&sid=$senderid&mtype=N&DR=Y");
			$ret = curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			$curlresponse = curl_exec ($ch);		
		}	
	}

	public function validate_promo_code($data =array()){
		$user_id = $this->auth_token_get($data['auth_token']);
		if($user_id > 0){
			$date = date('Y-m-d');
			$tot_cost  = $data['tot_cost'];
			$promoCode = $data['promo_code'];
			$promoData = $this->db->query("SELECT PROM.* FROM promocode_management AS PROM 
										   WHERE PROM.promocode_name='$promoCode' AND PROM.status='1' AND 
										  	     PROM.start_date<='$date' AND PROM.end_date>='$date' AND 
										         PROM.use_limit>(SELECT count(id) FROM promocode_used AS PU 
										         				 WHERE PU.promocode_id=PROM.promocode_id AND 
										         				       PU.status=1)");
			if(empty($promoData) || empty($promoData = $promoData->row_array())){
				$respArr['code'] = 980;
				$respArr['status'] = 0;
				$respArr['message'] = 'Promocode Invalid or Expired';
				return $respArr;
			}
			if(!empty($promoData['event_id']) && $promoData['event_id'] != $data['event_id']){
				$respArr['code'] = 981;
				$respArr['status'] = 2;
				$respArr['message'] = 'Promocode is not valid for this Event';
				return $respArr;
			}
			if(!empty($promoData['category_id']) || !empty($promoData['city_id'])){
				$sql = "SELECT VEN.region_id,EVT.category_id FROM events AS EVT 
					    INNER JOIN venue AS VEN ON (VEN.id = EVT.venue_id) 
					    WHERE EVT.event_id='".$data['event_id']."' AND EVT.status=1";
				$eventData = $this->db->query($sql)->row_array();

				if(empty($eventData)){
					$respArr['code'] = 982;
					$respArr['status'] = 0;
					$respArr['message'] = 'Invalid Event ID or wrong Data';
					return $respArr;
				}
				if(!empty($promoData['category_id']) && $promoData['category_id']!=$eventData['category_id']){
					$respArr['code'] = 983;
					$respArr['status'] = 3;
					$respArr['message'] = 'Promocode is not valid for this Category';
					return $respArr;	
				}
				if(!empty($promoData['city_id']) && $promoData['city_id']!=$eventData['region_id']){
					$respArr['code'] = 984;
					$respArr['status'] = 4;
					$respArr['message'] = 'Promocode is not valid for the selected region';
					return $respArr;	
				}
			}
			if(!empty($promoData['min_order_amount']) && $promoData['min_order_amount'] > $tot_cost){
				$respArr['code'] = 985;
				$respArr['status'] = 5;
				$respArr['message'] = 'Minimum amount is not satisfied';
				$respArr['data'] = array('message'=>'Minimum amount is not satisfied',
									     'minimum_amount'=>$promoData['min_order_amount']);
				return $respArr;	
			}

			$discAmt = 0;
			if($promoData['discount_type'] == 1){
				$discAmt = ($tot_cost * $promoData['discount_percentage'])/100;
			} else {
				$discAmt = ($tot_cost<=$promoData['discount_percentage'])?$tot_cost:$promoData['discount_percentage'];
			}
			$discAmt = (!empty($maxReedem=$promoData['max_redeem'])&&$maxReedem<$discAmt)?$maxReedem:$discAmt;
			$tot_cost = $tot_cost-$discAmt;
			$tot_cost = ($tot_cost <= 0)?0:$tot_cost;

			$datas['discount'] = $data['tot_cost']-$tot_cost;
			$datas['promocode_id'] = $promoData['promocode_id'];
			$datas['discounted_price'] = $tot_cost;
			$promDetails = langTranslator($promoData['promocode_id'],'PROMO');

			$datas = array_merge($datas,$promDetails);
			$respArr['status'] = 1;
			$respArr['message'] = 'Success';
			$respArr['data'] = $datas;
			return $respArr;
		}else{
			return array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
		}
	}

	public function hotelBooking($txnData = array()){
		try{
 			if(empty($txnData)){
 				return;
 			}
 			if($txnData['status'] == '0'){
 				if(!isset($txnData['mode']) || empty($txnData['mode']) || 
 				   !isset($txnData['amount']) || empty($txnData['amount']) || 
 				   !isset($txnData['auth_token']) || empty($txnData['auth_token']) || 
 				   !isset($txnData['bookData']) || empty($bookData = $txnData['bookData'])){
 					return;
 				}
 				$user_id = $this->auth_token_get($txnData['auth_token']);
 				if(empty($user_id)){
 					return;
 				}
 				$bookId = 'HTL'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
 				$qrcode = genQRcode($bookId);
 				$trvlerDtls = array("roomDetails"=>array("room"=>$bookData['rooms'],"adult"=>$bookData['adult'],"children"=>$bookData['child']),"checkin"=>$bookData['checkin'],"checkout"=>$bookData['checkout'],"hotel_address"=>$bookData['hotelAddress']);

				$insert = array('hotel_book_id'=>$bookId,'customer_id'=>$user_id,'hotel_name'=>
								$bookData['hotelName'],'hotel_image'=>$bookData['hotelImage'],'checkin'=>
								$bookData['checkin'],'checkout'=>$bookData['checkout'],'price'=>
								$bookData['amount'],'request_data'=>json_encode($bookData['requestData']),'traveller_details'=>json_encode($trvlerDtls),
								'qrcode'=>$qrcode);
				$this->db->insert('hotel_booking',$insert);
				$this->db->insert('orders',array('booking_id'=>$bookId,'order_type'=>'2','created_date'=>date('Y-m-d h:i:s'),'customer_id'=>$user_id));
				return array('status'=>1,'transaction_id'=>$bookId);
 			} else if($txnData['status'] == '1' && isset($txnData['tnx_id']) && 
 				      !empty($txnData['tnx_id'])){
 				$bookedHotelData = $this->db->get_where('hotel_booking',array('hotel_book_id'=>$txnData['tnx_id']))->row_array();
				if(!empty($bookedHotelData) && !empty($bookedHotelData['request_data'])){
					$hotelData = json_decode($bookedHotelData['request_data'])->getBookingDetails;
					$result = $this->bookHotel($hotelData);
					$this->db->update('hotel_booking',array('booking_response'=>json_encode($result),'status'=>'1'),array('hotel_book_id'=>$txnData['tnx_id']));
					return array('status'=>1);
				} 				
 			} else if($txnData['status'] == '2' && isset($txnData['tnx_id']) && !empty($txnData['tnx_id'])){
				$this->db->update('hotel_booking',array('status'=>'5'),array('hotel_book_id'=>$txnData['tnx_id']));
				return array('status'=>1);	
 			}
 		}catch(Exception $e){
 			return array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER19');
 		}
 	}

 	public function flightBooking($txnData = array()){
 		try{
 			if(empty($txnData)){
 				return;
 			}
 			if($txnData['status'] == '0'){
 				if(!isset($txnData['mode']) || empty($txnData['mode']) || 
 				   !isset($txnData['amount']) || empty($txnData['amount']) || 
 				   !isset($txnData['auth_token']) || empty($txnData['auth_token']) || 
 				   !isset($txnData['bookData']) || empty($bookData = $txnData['bookData'])){
 					return;
 				}
 				$user_id = $this->auth_token_get($txnData['auth_token']);
 				if(empty($user_id)){
 					return;
 				}
 				$bookId = 'FBK'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
 				$qrcode = genQRcode($bookId);
				$insert = array('flight_book_id'=>$bookId,'customer_id'=>$user_id,'flight_name'=>
					$bookData['flightName'],'flight_image'=>$bookData['flightImage'],
					'departure_date'=>$bookData['departure_date'],'price'=>$bookData['amount'],
					'arrival_date'=>$bookData['arrival_date'],'request_data'=>json_encode($bookData['requestData']),'traveller_details'=>json_encode($bookData['requestData']['traveller_details']),'qrcode'=>$qrcode);
				$this->db->insert('flight_booking',$insert);
				$this->db->insert('orders',array('booking_id'=>$bookId,'order_type'=>'3','created_date'=>date('Y-m-d h:i:s'),'customer_id'=>$user_id));
				return array('status'=>1,'transaction_id'=>$bookId);
 			} else if($txnData['status'] == '1' && isset($txnData['tnx_id']) && 
 				      !empty($txnData['tnx_id'])){
 				$bookedFlightData = $this->db->get_where('flight_booking',array('flight_book_id'=>$txnData['tnx_id']))->row_array();
				if(!empty($bookedFlightData) && !empty($bookedFlightData['request_data'])){
					$flightData = json_decode($bookedFlightData['request_data'])->flightRequestDetails;
					$result = $this->bookFlight($flightData);
					$this->db->update('flight_booking',array('booking_response'=>json_encode($result),'status'=>'1'),array('flight_book_id'=>$txnData['tnx_id']));
					return array('status'=>1);
				} 				
 			} else if($txnData['status'] == '2' && isset($txnData['tnx_id']) && !empty($txnData['tnx_id'])){
				$this->db->update('flight_booking',array('status'=>'5'),array('flight_book_id'=>$txnData['tnx_id']));
				return array('status'=>1);
 			}
 		}catch(Exception $e){
 			return array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER19');
 		}
 	}

 	public function bookHotel($data = ''){
 		$settings = getSettings();
		$url = "https://trawex.biz/api/hotel_trawexv5/hotel_book";
		$postData = array(
						"user_id"=>$settings['trawex_user_id'],
						"user_password"=>$settings['trawex_user_password'],
						"access"=>$settings['trawex_access'],
						"ip_address"=>$settings['trawex_ip_address'],
						"TraceId"=>$data->TraceId,"propertyid"=>$data->propertyid,
						"trackingId"=>$data->trackingId,"sessionId"=>$data->sessionId,
						"productId"=>$data->productId,"TokenId"=>$data->TokenId,
						"resultindex"=>$data->resultindex,"hotelcode"=>$data->hotelcode,
						"changedOccupancy"=>$data->changedOccupancy,
						"extrabeds"=>$data->extrabeds,
						"guests_details"=>$data->guests_details,"refcode"=>$data->refcode,
						"prebookingtoken"=>$data->prebookingtoken
					);
		$result = passToJsonCurl($url,$postData);
	    if(!empty($result)){
	    	$result = json_decode($result,true);
	    	return $result;
	    }
	    return;
 	}

 	public function bookFlight($data = ''){
    	$settings = getSettings();
		$data->first_name = str_replace(" ","<br>",$data->first_name);
		$data->last_name = str_replace(" ","<br>",$data->last_name);
		$data->title = str_replace(" ","<br>",$data->title);
		$data->dob = str_replace(" ","<br>",$data->dob);
		$data->gender = str_replace(" ","<br>",$data->gender);
		$data->issue_country = str_replace(" ","<br>",$data->issue_country);
		$data->passport_expiry = str_replace(" ","<br>",$data->passport_expiry);
		$data->passport_no = str_replace(" ","<br>",$data->passport_no);
        $childMealplan = (isset($data->childMealplan) && !empty($data->childMealplan))?$data->childMealplan:'';
        $infantMealplan = (isset($data->infantMealplan) && !empty($data->infantMealplan))?$data->infantMealplan:'';
        $adultmealplan = (isset($data->adultmealplan) && !empty($data->adultmealplan))?$data->adultmealplan:'';
        $postCode = (isset($data->PostCode) && !empty($data->PostCode))?$data->PostCode:'';

		$url = "https://trawex.biz/api/flight_trawex/book?user_id=".$settings['trawex_user_id']."&user_password=".$settings['trawex_user_password']."&access=".$settings['trawex_access']."&ip_address=".$settings['trawex_ip_address']."&target=".$data->target."&session_id=".$data->session_id."&area_code=".$data->area_code."&country_code=".$data->country_code."&first_name=".$data->first_name."&last_name=".$data->last_name."&title=".$data->title."&email_id=".$data->email_id."&mobile_no=".$data->mobile_no."&dob=".$data->dob."&gender=".$data->gender."&issue_country=".$data->issue_country."&passport_expiry=".$data->passport_expiry."&passport_no=".$data->passport_no."&type=".$data->type."&IsPassportMandatory=".$data->IsPassportMandatory."&adult_flight=".$data->adult_flight."&child_flight=".$data->child_flight."&infant_flight=".$data->infant_flight."&frequentFlyrNum=".$data->frequentFlyrNum."&adultmealplan=".$adultmealplan."&child_dob=".$data->child_dob."&child_gender=".$data->child_gender."&child_title=".$data->child_title."&child_first_name=".$data->child_first_name."&child_last_name=".$data->child_last_name."&child_passport_expiry_date=".$data->child_passport_expiry_date."&child_passport_no=".$data->child_passport_no."&child_frequentFlyrNum=".$data->child_frequentFlyrNum."&childMealplan=".$childMealplan."&infant_dob=".$data->infant_dob."&infant_gender=".$data->infant_gender."&infant_first_name=".$data->infant_first_name."&infant_last_name=".$data->infant_last_name."&infant_title=".$data->infant_title."&infantMealplan=".$infantMealplan."&FareSourceCode=".$data->FareSourceCode."&PostCode=".$postCode."";
		$result = passToJsonCurl($url,'');
		if(!empty($result)){
			//$result = json_decode($result);
            $result = array('BookFlightResponse'=>array('BookFlightResult'=>array('Errors'=>'','Status'=>'CONFIRMED','Success'=> 'true','Target'=> 'Test','TktTimeLimit'=>'', 'UniqueID'=>'TR04632018')));
			return $result;
		}
    	return;
 	}
} 
?>
