<?php 

class Webservice_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
    	$this->load->model('Api_model'); 
	}
	
	function update_fcm_token($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$Data = array('fcm_token'=>$data['fcm_token']);
				$this->db->where('customer_id', $user_id);
				$status = $this->db->update('customer', $Data);
				if ($status){
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Update failed please try again','code'=>'ER15');
				}	 			
			} 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 login($data){
		try{
			$sql = "SELECT region.id AS city_id, customer.name AS user_name,customer.phone, customer.email,
					customer.profile_image AS profile_photo,customer.profile_image_qr,
					IF(customer.phone_verified=0,'false', 'true') AS is_phone_verified,
					IF(customer.city='', 'false', 'true') AS is_location_updated,users.id AS user_id
					FROM users
					INNER JOIN customer ON (customer.customer_id=users.id)
					LEFT JOIN region ON (region.id=customer.city)
					WHERE users.status = 1
					AND users.password = '".md5($data['password'])."'
					AND customer.email = '".$data['email']."'";
			$result = $this->db->query($sql)->row();
			if($result){
				$auth_token = md5(microtime().rand());
				
				$countryData = $this->getCountryData($result->user_id);
				$lang = $countryData['language_code'];

				if(!empty($lanTrans = langTranslator($result->city_id,'REG',$lang))){
					$result->city = $lanTrans['region_name'];
				}

				if($result->city_id != ''){
					$cityId = $result->city_id;
					$cityName = $result->city;
				}else{
					$cityId = 'null';
					$cityName = 'null';
				}
				$resultArray = array(
					'city_id'=>$cityId === 'null'? null: $cityId,
					'city_name'=>$cityName === 'null'? null: $cityName,
					'user_name'=>$result->user_name,
					'phone'=>$result->phone,
					'email'=>$result->email,
					'profile_photo'=>$result->profile_photo,
					'profile_image_qr'=>$result->profile_image_qr,
					'user_id'=>$result->user_id,
					'is_phone_verified'=>$result->is_phone_verified === 'true'? true: false,
					'is_location_updated'=>$result->is_location_updated === 'true'? true: false,
				);
				$this->db->update('customer',array('country_id'=>$data['country_id']),
											 array('customer_id'=>$result->user_id));
				$response = array('user'=>$resultArray,'auth_token'=>$auth_token);
				$this->generateAuth($result->user_id,$auth_token);
				$res = array('status'=>1,'data'=>$response);
			} else {
				$res = array('status'=>0,'message'=>'Invalid username / Password','code'=>'ER05');
			}
		} catch(Exception $e) {
			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		} 
		return $res;	
	}
	
	function user_language($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$this->db->where('customer_id', $user_id);
				$id = $this->db->update('customer', array('country_id'=>$data['country_id']));
				if($id) {
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Update failed please try again','code'=>'ER15');
				}	 			
			} 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 availability($data) {
		try{
			$is_email_available = "true";
			$is_phone_available = "true";
			$data['phone'] = preg_replace('/\D/', '', $data['phone']);

			$sql = "SELECT * FROM customer 
					WHERE phone like '%".$data['phone']."' OR email='".$data['email']."'";
			$res_count = $this->db->query($sql)->result();
			if(count($res_count) > 0) {
				foreach ($res_count as $rs) {
					if($rs->email == $data['email']) {
						$is_email_available = "false";
					}
					if(strpos($rs->phone,$data['phone']) !== false) {
						$is_phone_available = "false";
					}
				}
			}
			$data = array(
				'is_email_available'=>$is_email_available === 'true'? true: false,
				'is_phone_available'=>$is_phone_available === 'true'? true: false
			);
			$res = array('status'=>1,'data'=>$data);

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

	function register($data) {
		try{
			$email = $data['email'];
			$phone = preg_replace('/\D/', '', $data['phone']);
			$res_count = $this->db->query("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 LIKE '%$phone')")->row();
			if(count($res_count) > 0) {
				if($res_count->email == $data['email'] && $res_count->phone == $data['phone']){
					$res = 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']){
					$res = array('status'=>0,'message'=>'Email id already exists','code'=>'ER09');
				} else if(strpos($res_count->phone,$data['phone']) !== false) {
					$res = array('status'=>0,'message'=>'Phone no already exists','code'=>'ER10');
				}
			}else {
				$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'],
						'email'=>$data['email'],
						'name'=>$data['name'],
						'country_id'=>$data['country_id']
					);
					$this->db->insert('customer', $customer_data);
					$email    = $data['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($data['phone'],$message);
					$this->db->select("customer.name AS user_name,customer.phone,customer.email,customer.profile_image AS profile_photo,customer.profile_image_qr,users.id AS user_id, IF(customer.phone_verified = 0,'false','true') AS is_phone_verified");
					$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){
						$auth_token = md5(microtime().rand());
						$this->generateAuth($result->user_id,$auth_token);
						$resultArray = array(
							'user_id'=>$result->user_id,
							'user_name'=>$result->user_name,
							'phone'=>$result->phone,
							'email'=>$result->email,
							'profile_photo'=>$result->profile_photo,
							'profile_image_qr'=>$result->profile_image_qr,
							'is_phone_verified'=>$result->is_phone_verified === 'true'? true: false			
						);
						$response = array('user'=>$resultArray,'auth_token'=>$auth_token);
						$res = array('status'=>1,'data'=>$response);
					} else {
						$res = array('status'=>0,'message'=>'No record found','code'=>'ER13');
					}
				} else {
					$res = array('status'=>0,'message'=>'Registration failed please try again','code'=>'ER11');
				}	 			
			}
		} catch(Exception $e) {
			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		} 
		return $res;
	}

	function profile_details($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$settings = getSettings();
				$sql = "SELECT faq FROM translator_policies 
					    WHERE language_code='$lang' OR language_code='EN'";
				$settingsDetails = $this->db->query($sql)->row_array();
				$settingsDetails['contact_number'] = $settings['contact_number'];

				$sql = "SELECT customer.name AS name,customer.profile_image AS profile_photo,
							   customer.profile_image_qr,customer.gender AS gender,customer.email,
							   customer.dob,customer.profile_city AS city_name,users.email_status,
							   users.notification_status,customer.enable_chat AS user_visible 
					    FROM customer 
					    INNER JOIN users ON users.id=customer.customer_id 
					    WHERE customer.customer_id=$user_id AND users.status='1'";
				$userDetails = $this->db->query($sql)->row_array();
				if(count($settingsDetails)>0 && count($userDetails)){
					$resultData = array();					
					$resultData = array_merge($settingsDetails, $userDetails);
					$res = array('status'=>1,'data'=>$resultData);
				} 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 {
			$per_page = 10;	
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$where = '';
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];
				$rate = (!empty($countryData['conversion_rate']))?$countryData['conversion_rate']:1;
				$sql = "SELECT region.id FROM customer
						INNER JOIN region ON customer.city=region.id
						WHERE customer.customer_id='$user_id' AND region.status='1'";
				$cityName = $this->db->query($sql)->row_array();
				
				if(!empty($cityName)){
					$regData = langTranslator($cityName['id'],'REG',$lang);
					$cityName['city'] = $regData['region_name'];
				} else {
					$cityName['city'] = 'null';
				}
				if(isset($data['category_id'])) {
					$where = ' AND events.category_id = '.$data['category_id'];
				}
				$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
				if(isset($data['latitude']) && isset($data['longitude'])) {
					$radius = 25;
					$res = $this->db->query("SELECT events.event_id,venue.id,venue.status, (((acos(sin((".$data['latitude']."*pi()/180)) * sin((venue.location_lat*pi()/180)) + cos((".$data['latitude']."*pi()/180)) * cos((venue.location_lat*pi()/180)) * cos(((".$data['longitude']." - venue.location_lng)*pi()/180))))*180/pi())*60*1.1515) as distance FROM venue RIGHT JOIN events ON events.venue_id = venue.id HAVING distance < ".$radius." AND venue.status = '1'")->result_array();
					$otherV = '';
					foreach($res as $key => $value){
						if ($otherV) $otherV .= ',';
						$otherV .= $value['event_id'];
					}
					if($otherV!='')	{
						$where = ' AND events.event_id IN ('.$otherV.')';
					} else{
						$where = ' AND events.category_id IN (0)';
					}
				}
				if(isset($cityName['id'])) {
					$where .= ' AND venue.region_id = '.$cityName['id'];
				}
				if(isset($data['filters'])){
					$filtersElement = json_decode($data['filters'], true);
					$locality_id_Array = $filtersElement['cities'];
					$locality_id = preg_replace("/[^a-zA-Z 0-9]+/", "", $locality_id_Array);
					$dateId_Array = $filtersElement['date'];
					$dateId = preg_replace("/[^a-zA-Z 0-9]+/", "", $dateId_Array);
					$categoryId_Array = $filtersElement['category'];
					$categoryId = preg_replace("/[^a-zA-Z 0-9]+/", "", $categoryId_Array);
					if($categoryId!=''){
						$where = ' AND events.category_id='.$categoryId;
					}	
					if($dateId != '') {
						switch ($dateId) {
							case '1':
							$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
							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";
							case '6':
							$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";
							default:
							$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
							break;
						} 					
					}
					if($locality_id!=''){
						$venue_res = $this->db->select('id')->where('locality_id',$locality_id)->get('venue')->result_array();
						$list = implode(',', array_map(function($v) { return $v['id']; }, $venue_res));
						$where .= ' AND events.venue_id IN('.$list.')';
					}
				}
				$this->db->query("SET SESSION group_concat_max_len = 200000");
				$resCount = $this->db->query("
					SELECT 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 
					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 event_category ON events.category_id = event_category.cat_id 
					LEFT JOIN review ON review.event_id = events.event_id 
					INNER JOIN venue ON venue.id = events.venue_id 
					LEFT JOIN favourite ON favourite.event_id = events.event_id AND 
										   favourite.user_id = $user_id AND favourite.status = 1 
					WHERE events.status = 1 AND event_date_time.status='1' $where
					GROUP BY events.event_id")->result();
				if(empty($resCount)){
					return array('status'=>1,'data'=>array('city_name'=>$cityName['city']));
				}
			  	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]);
						}
					} else {
						unset($resCount[$key]);
					}
				}
				$count = count($resCount);
				if($count > 0) {
					$page = (isset($data['page']))?$data['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.seat_pricing,events.custom_seat_layout,event_category.cat_id,venue.id AS venue_id,venue.location_lat AS latitude,venue.location_lng AS longitude,venue.layout,venue.layout_details,events.event_id AS event_id,event_gallery.media_url AS image, (SELECT SUM(booking.no_of_ticket) FROM booking WHERE booking.event_id = events.event_id AND booking.status IN (1,2)) AS attendees,CAST(AVG (review.rate) AS DECIMAL (12,1)) AS rating,venue.location, IF(events.avg_price = 0, '100','150') AS rate, IF(events.provider_id = 1,'true','false') AS is_editors_choice, IF(favourite.is_favorite = 1, 'true','false') AS is_favorite, GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time,
								events.has_payment
							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 
							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 event_category ON events.category_id=event_category.cat_id 
							LEFT JOIN review ON review.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 
							WHERE events.status = 1 AND event_date_time.status='1' $where $case
							GROUP BY events.event_id 
							LIMIT $page_limit,$per_page")->result();	
						$response = array();
						foreach ($result as $key=>$rs) {
					  		if(!empty($dates = explode(',',$rs->date_time)) && count($dates) > 0){
								$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 = $rate*min(array_column($pricelist, 'price'));
								} else {
									$pricelist = json_decode($rs->layout_details, TRUE);
									$price = $rate*min(array_column($pricelist, 'price'));
								}
							} else {
								$pricelist = json_decode($rs->seat_pricing, TRUE);
								$price = $rate*$pricelist['price'];
							}

							$transData = array('event'=>'','category'=>'','venue'=>'');
							if(!empty($lanTrans = langTranslator($rs->event_id,'EVT',$lang))){
								$transData['event'] = $lanTrans['event_name'];
							}
							if(!empty($lanTrans = langTranslator($rs->cat_id,'CAT',$lang))){
								$transData['category'] = $lanTrans['category_name'];
							}
							if(!empty($lanTrans = langTranslator($rs->venue_id,'VEN',$lang))){
								$transData['venue'] = $lanTrans['venue_name'];
							}

							$resData = array(
								'id' => "$key",
								'event_id'=>$rs->event_id,
								'image'=>$rs->image,
								'attendees'=>(!empty($rs->attendees))?$rs->attendees:'0',
								'category'=>$transData['category'],
								'name'=>$transData['event'],
								'rating'=>(!empty($rs->rating))?$rs->rating:'0',
								'location'=>$transData['venue'].', '.$rs->location,
								'rate'=>$price,
								'is_editors_choice'=>$rs->is_editors_choice,
								'is_favorite'=>$rs->is_favorite === 'true'? true: false,
								'latitude'=>$rs->latitude,
								'longitude'=>$rs->longitude,
								'has_payment'=>$rs->has_payment,
								'currency_symbol'=>$countryData['currency_symbol']
							);
							array_push($response, $resData);
						}
						$sql = "SELECT booking.id,review.rate 
								FROM booking 
								LEFT JOIN review ON review.event_id=booking.event_id AND 
													review.customer_id=booking.customer_id
								WHERE booking.customer_id = ".$user_id." AND booking.status='2' 
								ORDER BY booking.id DESC LIMIT 1";
						$lastBooking = $this->db->query($sql)->row_array();
						if($lastBooking['id'] != ''){
							if($lastBooking['rate'] != ''){
								$lastBooking = "false";
							}else{
								$lastBooking = "true";
							}
						}else{
							$lastBooking = "false";
						}
						$meta = array('total_pages'=>ceil($count/$per_page),
							'total'=>$count,
							'current_page'=>$page,
							'per_page'=>$per_page
						);
						if(count($result)>0){
							$resultData = array();
							$resultData['is_last_booking_avail'] = $lastBooking;
							$resultData['city_name'] = $cityName['city'];				
							$resultData['events'] = $response;
							$resultData['meta'] = $meta;
							$response = $resultData;
							$res = array('status'=>1,'data'=>$response);
						}else {
							$res = array('status'=>1,'data' => array('city_name'=>$cityName['city']));
						}
					} else {
						$res = array('status'=>1,'data' => array('city_name'=>$cityName['city']));
					}
				} else {
					$res = array('status'=>1,'data' => array('city_name'=>$cityName['city']));
				}
			} 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 event($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']); 			
			if($user_id > 0) {
				$event_id = $data['event_id'];
				$cTime = date("H:i", strtotime('+15 minutes'));

				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];
				$rate = (!empty($countryData['conversion_rate']))?$countryData['conversion_rate']:1;

				$this->db->query("SET SESSION group_concat_max_len = 200000");
				$sql = "SELECT host_categories.show_layout AS is_layout,venue.id AS venue_id,
							   events.has_payment AS is_payment_required,favourite.is_favorite AS is_favorite,
							   events.seat_pricing,events.custom_seat_layout,events.event_id,
						       venue.layout, venue.layout_details,venue.location,venue.location AS address, 
						       venue.location_lat AS lat,venue.location_lng AS lng,events.max_booking,
						       GROUP_CONCAT(DISTINCT event_gallery.media_url) AS 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 
			            INNER JOIN host_categories ON venue.host_cat_id = host_categories.host_cat_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.user_id=$user_id AND favourite.status = 1 
			            WHERE event_date_time.date>='".date('Y-m-d')."' AND 
			            	  event_date_time.status='1' AND events.event_id=$event_id 
			            GROUP BY events.event_id, event_date_time.event_id";
				$rs = $this->db->query($sql)->row();

				if(count($rs) > 0){
					$event_layout = '';
					$colorData = array();
					$resultData = array();
					$sql    = "SELECT AVG(review.rate) AS rate FROM review WHERE event_id=$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=$event_id";
					$atten  = $this->db->query($sql)->row_array();
					$atte   = isset($atten['attend'])&&!empty($atten['attend'])?$atten['attend']:'0';

					if(!empty($rs->layout)){
						if(!empty($rs->custom_seat_layout)){
							$seatLayout = $rs->custom_seat_layout;
							if(!empty($seatLayout) && !empty($seatLayout = json_decode($seatLayout,true))){
								foreach ($seatLayout AS $key => $seat) {
									$seatLayout[$key]['price'] = $seat['price']*$rate;
								}
							}
							$event_layout = json_encode($seatLayout);
						} else {
							$seatLayout = $rs->layout_details;
							if(!empty($seatLayout) && !empty($seatLayout = json_decode($seatLayout,true))){
								foreach ($seatLayout AS $key => $seat) {
									$seatLayout[$key]['price'] = $seat['price']*$rate;
								}
							}
							$event_layout = json_encode($seatLayout);
						}
					} else {
						$seatLayout = $rs->seat_pricing;
						if(!empty($seatLayout) && !empty($seatLayout = json_decode($seatLayout,true))){
							$seatLayout['price'] = $seatLayout['price']*$rate;
						}
						$event_layout = json_encode($seatLayout);
					}
					$dates = explode(',', $rs->date_time);
					$time_spec = array();
					$data_array = array();
					foreach ($dates as $rss) {
						list($id,$date,$time) = explode('#', $rss);
						$sTime = $date.' '.$time;
						$cTime = date("Y-m-d H:i", strtotime('+15 minutes'));
						if($cTime < $sTime){
							$time_spec[] = array('id'=>$id, 'date'=>$date, 'time'=>$time);
							$data_array[$date][] = array('id'=>$id, 'time'=>$time);
						}
					}
					$date_list = array();
					foreach ($data_array as $key => $value) {
						$date_list[] = array('date'=>$key, 'time'=>$value);
					}
					$custDesc = '';
					if($rs->is_layout == 1 && !empty($pData = json_decode($rs->seat_pricing, TRUE))){
						$cSymbol = $countryData['currency_symbol'];
						if(isset($pData['price_details_'.$lang]) && !empty($pData['price_details_'.$lang])){
							$custDesc = '<p>'.$pData['price_details_'.$lang].' ('.$cSymbol.' '.$pData['price']*$rate.')</p>';
						}
						
					}
					$event_layouts = [];
					if(isset($data['event_date_id']) && !empty($eDateId = $data['event_date_id'])){
						$param = array('user_id'=>$user_id,'event_id'=>$event_id,'time_id'=>$eDateId);
						$event_layouts = $this->checkSeatAvailability($param);
					}

					$transData = array('event'=>'','description'=>'','category'=>'','venue'=>'');
					if(!empty($lanTrans = langTranslator($rs->event_id,'EVT',$lang))){
						$transData['event'] = $lanTrans['event_name'];
						$transData['description'] = $lanTrans['event_description'].$custDesc;
					}
					if(!empty($lanTrans = langTranslator($rs->venue_id,'VEN',$lang))){
						$transData['venue'] = $lanTrans['venue_name'];
					}

					$media_url = explode(',', $rs->media_url);	
					$resData = array(
						'event_id'=>$rs->event_id,
						'name'=>$transData['event'],
						'description'=>$transData['description'],
						'rating'=>$rate,
						'total_attendees'=>$atte,
						'layout_image'=>$rs->layout,
						'is_favorite'=>$rs->is_favorite == '1'? true: false,
						'is_payment_required'=>$rs->is_payment_required == '1'? true: false,
						'is_layout'=>$rs->is_layout == '1'? true: false,
						'photos'=>$media_url,
						'time'=>$time_spec[0]['time'],
						'date'=>$time_spec[0]['date'],
						'date_list'=>$date_list,
						'classes'=>$event_layouts,
						'latitude'=>$rs->lat,
						'address_name'=>$transData['venue'],
						'address'=>$rs->address,
						'longitude'=>$rs->lng,
						'currency_symbol'=>$countryData['currency_symbol']
					);
					$res = array('status'=>1,'data'=>$resData);
				} 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 generateAuth($userId,$auth_token) {
		$this->db->insert('customer_auth',array('user_id'=>$userId, 'auth_token'=>$auth_token));
	}

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

	function get_category_list($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$where = '';
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];
				if(isset($data['query']) && !empty($data['query'])) {
					$where = ' AND TC.category_name LIKE '."'%".$data['query'].'%'."'";
				}
				$sql = "SELECT TC.category_id,TC.category_name,TC.category_image
						FROM translator_category AS TC 
						INNER JOIN event_category AS ECAT ON (ECAT.cat_id=TC.category_id)
						WHERE ECAT.status = 1 AND TC.language_code='$lang'
							  $where 
						GROUP BY ECAT.cat_id ORDER BY ECAT.priority";
				$result = $this->db->query($sql)->result();
				if(count($result) > 0){
					$res = array('status' => 1,'data' => array('category'=>$result));
				} else {
					$res = array('status'=>1,'data' => []);
				}
			} 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 add_favorites($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$res_count = $this->db->where('event_id',$data['event_id'])->where('user_id',$user_id)->get('favourite')->num_rows();
				$favoriteList = array('user_id'=>$user_id, 'event_id'=>$data['event_id'], 'is_favorite'=>$data['is_favorite']);
				if($res_count > 0) {
					$data=array('event_id'=>$data['event_id'], 'is_favorite'=>$data['is_favorite']);
					$this->db->where('user_id',$user_id);
					$this->db->where('event_id',$data['event_id']);
					$id = $this->db->update('favourite',$data);
				}else{
					$id = $this->db->insert('favourite',$favoriteList);
				}
				if($id) {
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Add Favorite failed please try again','code'=>'ER14');
				}	 			
			} 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 get_cities_list($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];
				
				$sql = "SELECT REG.id AS city_id, REG.region_icon AS city_image,
							   TREG.region_name AS city_name 
					   	FROM region AS REG 
					   	INNER JOIN translator_region AS TREG ON (TREG.region_id = REG.id) 
					   	WHERE REG.status=1 AND (TREG.language_code='$lang') 
					   	GROUP BY city_id ORDER BY city_name";
				$result = $this->db->query($sql)->result();
				if(count($result)>0){
					$res = array('status'=>1,'data'=>array('cities'=>$result));
				} 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 update_city($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			$countryData = $this->getCountryData($user_id);
			$lang = $countryData['language_code'];
			if($user_id > 0) {
				if(isset($data['city_id']) && !empty($data['city_id'])){
					$city_id = $data['city_id'];
					$sql = "SELECT TREG.region_name FROM region AS REG 
							INNER JOIN translator_region AS TREG ON (TREG.region_id = REG.id) 
							WHERE REG.status='1' AND REG.id='$city_id' AND 
								  TREG.language_code='$lang'
						    GROUP BY REG.id";
					$re = $this->db->query($sql)->row();
					$cityName = $re->region_name;
					$cityId = $data['city_id'];
				}else{
					$radius = 25;
					$data = $this->db->query("
						SELECT REG.id,TREG.region_name,REG.status, (((acos(sin((".$data['latitude']."*pi()/180)) * sin((region_lat*pi()/180)) + cos((".$data['latitude']."*pi()/180)) * cos((region_lat*pi()/180)) * cos(((".$data['longitude']." - region_lng)*pi()/180))))*180/pi())*60*1.1515) as distance 
						FROM region AS REG 
						INNER JOIN translator_region AS TREG ON (TREG.region_id = REG.id) 
						WHERE REG.status = '1' AND 
							  TREG.language_code='$lang'
						HAVING distance < ".$radius." 
						ORDER BY distance ASC LIMIT 1")->row_array();
					if(!empty($data)){
						$cityId = $data['id'];
						$cityName = $data['region_name'];
					}
				}
				if(!empty($cityId)){
					$this->db->where('customer_id', $user_id);
					$this->db->update('customer', array('city' => $cityId));
					$res = array('status'=>1, 'data'=>array('city_id'=>$cityId,'city_name'=>$cityName));
				}else {
					$res = array('status'=>0,'message'=>'Update failed please try again','code'=>'ER15');
				}	 			
			} 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 booking_summary($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$bookId = $data['booking_id'];

				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$kk = array();
				$sql = "SELECT ticket_details FROM booking WHERE bookId='$bookId'";
				$ticketDetails = $this->db->query($sql)->row();
				if(!empty($ticketDetails)){
					$res = json_decode($ticketDetails->ticket_details);
					$kk['ticket_rate'] = (!empty($res))?"$res->price":'';
				}

				$settings = getSettings();
				$sql = "SELECT instruction FROM translator_policies 
						WHERE language_code='$lang' OR language_code='EN'";
				$settingsDetails = $this->db->query($sql)->row_array();
				$settingsDetails['contact_number'] = $settings['contact_number'];

				$sql = "SELECT booking.qrcode,events.event_id,events.venue_id,event_date_time.date,
							   events.has_payment AS is_payment_required,booking.bookId AS ticket_id,
							   event_gallery.media_url AS event_image,booking.amount AS total_rate,
							   event_date_time.time,venue.location AS address,
							   customer.name AS profile_name,
							   venue.location_lng AS longitude,venue.location_lat AS latitude,
							   booking.no_of_ticket AS ticket_count,
							   customer.profile_image AS profile_photo,
							   customer.profile_image_qr,booking.status
						FROM events 
						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 
						RIGHT JOIN event_date_time ON event_date_time.id = booking.event_date_id
						LEFT JOIN venue ON venue.id = events.venue_id 
						LEFT JOIN customer ON customer.customer_id = booking.customer_id  
						WHERE booking.bookId = '$bookId' AND booking.customer_id = ".$user_id;
				$result = $this->db->query($sql)->row_array();

				if(count($result) > 0 && count($settingsDetails) > 0){
					if(!empty($lanTrans = langTranslator($result['event_id'],'EVT',$lang))){
						$result['event_name'] = $lanTrans['event_name'];
					}
					if(!empty($lanTrans = langTranslator($result['venue_id'],'VEN',$lang))){
						$result['address_name'] = $lanTrans['venue_name'];
					}

					$resultData = array();
					$result['is_payment_required'] = ($result['is_payment_required'] == 1) ? true: false;
					$resultData = array_merge($settingsDetails, $result,!empty($kk)?$kk:[]);
					$resultData['currency_symbol'] = $countryData['currency_symbol'];
					$res = array('status'=>1,'data'=>$resultData);
				} 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 payment($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$this->db->where('customer_id', $user_id);
				$this->db->where('status', 1);
				$this->db->where('id', $data['booking_id']);
				$id = $this->db->update('booking', array('payment_status' => 1));
				if($id) {
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Update failed please try again','code'=>'ER11');
				}	 			
			} 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 event_rating($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$ratingDetails = array(
					'event_id'=>$data['event_id'],
					'customer_id'=>$user_id,
					'rate'=>$data['rating'],
					'feedback'=>$data['description']
				);
				$id = $this->db->insert('review', $ratingDetails);
				if($id) {
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Event Rating  failed please try again','code'=>'ER11');
				}	 			
			} 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 update_notification_email_status($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$notData = array('notification_status'=>$data['notification_status'], 'email_status'=>$data['email_status']);
				$this->db->where('id', $user_id);
				$this->db->where('status', 1);
				$this->db->where('user_type', 3);
				$status = $this->db->update('users', $notData);
				if ($status){
					$res = array('status'=>1);
				}else {
					$res = array('status'=>0,'message'=>'Update failed please try again','code'=>'ER15');
				}	 			
			} 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 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']);

				if(isset($data['email'])){
					$this->db->select('customer.email');
					$this->db->where('customer.email',$data['email']);
					$this->db->where('customer_id !=',$user_id);
					$this->db->where('users.status !=',2);
					$this->db->from('users');
					$this->db->join('customer','customer.customer_id = users.id');
					$num = $this->db->get()->num_rows();
					if($num > 0) {
						$res = array('status'=>0,'message'=>'Email address already exist','code'=>'ER32');
						return $res;
					}
				}

				if(isset($data['file']) && !empty($data['file'])){
					$imgName = explode('.',$data['file']['name']); 
					$imgExt  = strtolower($imgName[1]);

					if($imgExt=='png' || $imgExt=='jpeg' || $imgExt == 'jpg' || $imgExt == 'gif'){
						$imgPath = 'assets/uploads/user/CUST_'.$user_id.'_'.time().'.'.$imgExt;
					 	$imgQRPath = 'assets/uploads/user/CUST_QR_'.$user_id.'_'.time().'.png';
					 	$imgFramePath = 'assets/images/bitmojiFrame.png';

						array_map('unlink', glob('assets/uploads/user/CUST_'.$user_id.'_*.*'));
						array_map('unlink', glob('assets/uploads/user/CUST_QR_'.$user_id.'_*.*'));
						
						move_uploaded_file($data['file']['tmp_name'],"./".$imgPath);
						$this->imageResize($imgPath,array('width'=>'300','height'=>'300'));

						switch ($imgExt) {
							case 'png': $usrImage = imagecreatefrompng($imgPath);break;
							case 'gif': $usrImage = imagecreatefromgif($imgPath);break;
							case 'jpg': $usrImage = imagecreatefromjpeg($imgPath);break;
							case 'jpeg': $usrImage = imagecreatefromjpeg($imgPath);break;
						}
						$imgFrame = imagecreatefrompng($imgFramePath);

						if(empty($usrImage) || empty($imgFrame)){
							return array('status'=>0,'message'=>'Unsupported File Type','code'=>'ER32');
						}

						imagecopy($imgFrame,$usrImage,(imagesx($imgFrame)/2)-(imagesx($usrImage)/2),(imagesy($imgFrame)/2)-(imagesy($usrImage)/2),0,0,imagesx($usrImage),imagesy($usrImage));
						imagesavealpha($imgFrame, true);
						imagepng($imgFrame,$imgPath,0);
						genQRcode(encode_param($user_id),$imgQRPath,$imgPath);

						$post_data['profile_image'] = $imgPath;
						$post_data['profile_image_qr'] = $imgQRPath;

						$state = $this->db->where('customer_id',$user_id)->update('customer',$post_data);
						if(!$state){
							return array('status'=>0,'message'=>'Profile update failed','code'=>'ER32');
						}
					} else {
						return array('status'=>0,'message'=>'Invalid Image type','code'=>'ER41');	
					}
				} else {
					$state = $this->db->where('customer_id',$user_id)->update('customer',$post_data);
					if(!$state){
						return array('status'=>0,'message'=>'Profile update failed','code'=>'ER32');
					}
				}

				$this->db->select('customer.name,customer.dob,customer.phone,customer.email,customer.gender,
								   customer.profile_image AS image,users.id AS userId, customer.city,
								   customer.profile_image_qr');
				$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 booking($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$post_data = $data;
				$status = '3';
				$book_id = 'TO'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
				$post_data['bookId'] = $book_id;
				$post_data['qrcode'] = genQRcode($post_data['bookId']);
				$post_data['booking_date'] = date('Y-m-d H:i:s');
				$post_data['customer_id'] = $user_id;
				$post_data['ticket_details'] = json_encode($post_data['ticket_details']);
				$post_data['status'] = '3';

				if(!isset($post_data['amount']) || empty($post_data['amount'])){
					$post_data['amount'] = 0;
				}
				if(isset($post_data['has_payment']) && $post_data['has_payment'] == 0){
					$status = $post_data['status'] = '1';
				}

				$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['promo_code']) && !empty($post_data['promo_code']) && 
				   isset($post_data['discounted_price']) && !empty($post_data['discounted_price']) && 
				   !empty($post_data['amount'])){
					$promoData = $this->db->get_where('promocode_management',array('status'=>'1',
								            'promocode_name'=>$post_data['promo_code']))->row_array();

					$promo_id = $promoData['promocode_id'];
					$post_data['amount'] = $post_data['discounted_price'];
					$redeem_amount = $post_data['amount']-$post_data['discounted_price'];

					$promoStatus  = ($post_data['status'] == '1')? 1 : 0;
					$promocodeData = array('user_id'=>$user_id,'booking_id'=>$book_id,
										   'promocode_id'=>$promo_id,'redeem_amount'=>$redeem_amount,
										   'created_date'=>date('Y-m-d H:i:s'),'status'=>$promoStatus);
				}
				$invite_ids = (isset($post_data['friends_ids']))?$post_data['friends_ids']:'';
				$invite_phone = (isset($post_data['invite_list']))?$post_data['invite_list']:'';

 				unset($post_data['auth_token'],$post_data['has_payment'],$post_data['friends_ids'],
 					  $post_data['promo_code'],$post_data['discounted_price'],$post_data['invite_list']);
				
				$rs = $this->db->insert('booking', $post_data);
				$id = $this->db->insert_id();

				if($id){
					if(!empty($promocodeData)){
						$this->db->insert('promocode_used',$promocodeData);
					}
					$res = array('status'=>1,'data'=>array('bookingCode'=>$post_data['bookId']));
					$insertArr = array();
					$inStatus = ($post_data['status'] == 1)?'1':'0';
					if(!empty($invite_ids)){
						foreach($invite_ids AS $userId) {
							$insertArr[] = array('book_id'=>$book_id,'phone'=>'',
												 'user_id'=>$userId,'status'=>$inStatus);
						}
					}
					if(!empty($invite_phone)){
						foreach($invite_phone AS $key => $phone) {
							$phone = preg_replace('/\D/','',$phone);
							$insertArr[] = array('book_id'=>$book_id,'user_id'=>'',
												 'phone'=>$phone,'status'=>$inStatus);
						}
					}
					if(!empty($insertArr)){
						$this->db->insert_batch('event_invites',$insertArr);
					}

					if($status == 1){
						$countryData = $this->getCountryData($user_id);

						$bookId = $post_data['bookId'];
						$lang = $countryData['language_code'];
						$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 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='$bookId' AND EVT.status='1' AND 
					                  BK.status IN ('1','6') AND EDATE.status='1' AND 
					                  (TEVT.language_code='$lang' OR TEVT.language_code='EN')";

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

					    $msg = "Hi, You are invited for the event '".$bkData['event_name']."', and show is on '".$showTime."'. Booking ID ".$post_data['bookId'];
						if(!empty($invite_ids)){
							foreach($invite_ids AS $userId) {
								$usrData = $this->db->get_where('customer',
													  array('customer_id'=>$userId))->row_array();
								$this->sendSMS($usrData['phone'],$msg);
							}
						}
						if(!empty($invite_phone)){
							foreach($invite_phone AS $key => $phone) {
								$this->sendSMS($phone,$msg);
							}
						}
						if($post_data['status'] == 6){
					    	$userData = array('id'=>$post_data['bookId'],
					    					  'param'=>'booking_id',
											  'title'=>'New Booking',
											  '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 cancel($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$rs = $this->db->where('bookId',$data['booking_id'])->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 favouritelist($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];
				$rate = (!empty($countryData['conversion_rate']))?$countryData['conversion_rate']:1;

				$this->db->query("SET SESSION group_concat_max_len = 200000");
				$result = $this->db->query("
					SELECT (SELECT COUNT(booking.id) FROM booking WHERE booking.event_id=events.event_id) AS 
						   attendees, events.event_id, event_gallery.media_url,event_category.cat_id,
						   CAST(AVG (review.rate) AS DECIMAL (12, 1)) AS rating,
						   venue.location, IF(favourite.is_favorite = 0, 'false', 'true') AS is_favorite, 
						   IF(events.provider_id = 0, 'false', 'true') AS is_editors_choice, 
						   events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,
						   GROUP_CONCAT(DISTINCT CONCAT_WS('#', event_date_time.id, event_date_time.date, 
						   event_date_time.time)) AS date_time
					FROM favourite
					INNER JOIN events ON events.event_id=favourite.event_id
					INNER JOIN venue ON venue.id=events.venue_id
					INNER JOIN event_date_time ON event_date_time.event_id=events.event_id
					INNER JOIN event_category ON events.category_id=event_category.cat_id
					LEFT JOIN review ON review.event_id=favourite.event_id
					LEFT JOIN booking ON booking.event_id=events.event_id
					LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
							                   event_gallery.media_type=0
					WHERE favourite.status=1 AND favourite.is_favorite=1 AND 
					      favourite.user_id='$user_id' AND events.status=1 AND 
					      event_date_time.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND 
					      event_date_time.status='1'
					GROUP BY events.event_id")->result();
				if(empty($result)){
					return array('status'=>1,'data' => []);
				}
			  	foreach ($result AS $key => $rs) {
				  	if(!empty($dates = explode(',',$rs->date_time))){
						$checkTime = 0;
						foreach ($dates as $date) {
							if(empty($date)){ unset($result[$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($result[$key]); }
					} else { unset($result[$key]); }
				}
				if(($count = count($result)) > 0){
					$response = array();
					foreach ($result as $rs) {

						$transData = array('event'=>'','category'=>'','venue'=>'');
						if(!empty($lanTrans = langTranslator($rs->event_id,'EVT',$lang))){
							$transData['event'] = $lanTrans['event_name'];
						}
						if(!empty($lanTrans = langTranslator($rs->cat_id,'CAT',$lang))){
							$transData['category'] = $lanTrans['category_name'];
						}

						if($rs->layout != ''){
							if($rs->custom_seat_layout != ''){
								$pricelist = json_decode($rs->custom_seat_layout, TRUE);
								$price = min(array_column($pricelist, 'price')) * $rate;
							} else {
								$pricelist = json_decode($rs->layout_details, TRUE);
								$price = min(array_column($pricelist, 'price')) * $rate;
							}
						} else {
							$pricelist = json_decode($rs->seat_pricing, TRUE);
							$price = $pricelist['price'] * $rate;
						}
						$resData = array(
							'event_id'=>$rs->event_id,
							'image'=>$rs->media_url,
							'attendees'=>$rs->attendees,
							'category'=>$transData['category'],
							'name'=>$transData['event'],
							'rating'=>$rs->rating,
							'rate'=>$price,
							'location'=>$rs->location,
							'is_favorite'=>$rs->is_favorite === 'true'? true: false,
							'is_editors_choice'=>$rs->is_editors_choice === 'true'? true: false,
							'currency_symbol'=>$countryData['currency_symbol']
						);
						array_push($response, $resData);
					}
					$res = array('status'=>1,'data'=>$response);
				} else {
					$res = array('status'=>1,'data' => []);
				}
			} 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_old($data) {
		try {
			$per_page = 10;
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$count = $this->db->select('booking.bookId AS booking_id,booking.event_id,events.event_name,event_gallery.media_url AS event_image,venue.location,event_date_time.date,event_date_time.time,booking.no_of_ticket AS ticket_count,(CASE booking.status WHEN 1 THEN 0 WHEN 2 THEN 1 WHEN 0 THEN 2 ELSE 2 END) AS booking_status')->where('booking.customer_id',$user_id)->from('booking')->join('transaction','transaction.booking_id = booking.bookId AND transaction.status = 1', 'LEFT')->join('events','booking.event_id = events.event_id')->join('event_date_time','booking.event_date_id = event_date_time.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')->order_by('booking.id','DESC')->get()->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) {
						$lang = $this->getCountryData($user_id);
						
						if($lang == 'en'){
							$cat_field = 'events.event_name AS event_name';
						}else{
							$cat_field = 'events.event_name_ar AS event_name';
						}	
						$result = $this->db->select("booking.bookId AS booking_id,booking.event_id,$cat_field,event_gallery.media_url AS event_image,venue.location,event_date_time.date,event_date_time.time,booking.no_of_ticket AS ticket_count,
							(CASE booking.status WHEN 1 THEN 0 WHEN 2 THEN 1 WHEN 0 THEN 2 ELSE 2 END) AS booking_status")->where('booking.customer_id',$user_id)->from('booking')->join('transaction','transaction.booking_id = booking.bookId', 'LEFT')->join('events','booking.event_id = events.event_id')->join('event_date_time','booking.event_date_id = event_date_time.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')->where('booking.payment_status', 1)->order_by('booking.id','DESC')->limit($per_page,$page_limit)->get()->result();

						$meta = array('total_pages'=>ceil($count/$per_page),
							'total'=>$count,
							'current_page'=>$page,
							'per_page'=>$per_page
						);

						$response = array('bookings'=>$result,'meta'=>$meta);
						$res = array('status'=>1,'data'=>$response);
					} else {
						$res = array('status'=>1,'data' => []);
					}
				} else {
					$res = array('status'=>1,'data' => []);
				} 				
			} 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) {
		try {
			$per_page = 10;
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$count = $this->db->query("
 					SELECT BOK.id FROM booking AS BOK
 					INNER JOIN events AS EVT ON (EVT.event_id=BOK.event_id)
 					INNER JOIN event_date_time AS EDT ON (EVT.event_id=EVT.event_id)
 					WHERE BOK.customer_id='$user_id' AND BOK.status IN (0,1,2,6) AND EVT.status='1'
 					GROUP BY BOK.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) {
						$countryData = $this->getCountryData($user_id);
						$lang = $countryData['language_code'];

						$sql = "SELECT booking.bookId AS booking_id,event_date_time.date,
									   translator_event.event_name,booking.qrcode AS event_image,
									   venue.location,event_date_time.time,booking.event_id,
									   booking.no_of_ticket AS ticket_count,events.has_payment,
									   booking.status AS booking_status,transaction.status AS transaction_status
								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 translator_event ON translator_event.event_id=events.event_id
								LEFT JOIN transaction ON transaction.booking_id=booking.bookId
								WHERE booking.customer_id = '$user_id' AND booking.status IN (0,1,2,6) 
									  AND (translator_event.language_code='$lang' OR 
									       translator_event.language_code='EN')
								GROUP BY booking.id
								ORDER BY booking.id DESC
								LIMIT $page_limit, $per_page";
						$result = $this->db->query($sql)->result_array();
						if(!empty($result)){
							foreach ($result AS $key => $value) {
								if($value['has_payment'] == '1' && $value['transaction_status'] != '1'){
									unset($result[$key]);
								}
							}
							$result = array_values($result);
						}
						$meta = array('total_pages'=>ceil($count/$per_page),
							'total'=>$count,
							'current_page'=>$page,
							'per_page'=>$per_page
						);
						$response = array('bookings'=>$result,'meta'=>$meta);
						$res = array('status'=>1,'data'=>$response);
					} else {
						$res = array('status'=>1,'data' => []);
					}
				} else {
					$res = array('status'=>1,'data' => []);
				} 				
			} 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 get_settings($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$settings = getSettings();
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$sql = "SELECT privacy_policy,terms_and_conditions 
						FROM translator_policies WHERE (language_code='$lang' OR language_code='EN')";
				$setDetails = $this->db->query($sql)->row_array();
				$setDetails['contact_number'] = $settings['contact_number'];

				$sql = "SELECT notification_status, email_status FROM users WHERE id=".$user_id;
				$notifDetails = $this->db->query($sql)->row_array();

				if(count($setDetails) > 0 && count($notifDetails) > 0){
					$resultData = array_merge($setDetails, $notifDetails);
					$resultArray = array(
						'privacy_policy'=>$resultData['privacy_policy'],
						'terms_and_conditions'=>$resultData['terms_and_conditions'],
						'contact_number'=>$resultData['contact_number'],
						'notification_status'=>$resultData['notification_status'] == 0? 0: 1,
						'email_status'=>$resultData['email_status'] == 0? 0: 1
					);
					$res = array('status'=>1,'data'=>$resultArray);
				} 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 forgot_password($data) {
		try {
			$data['phone'] = preg_replace('/\D/', '', $data['phone']);
			$sql = "SELECT CUST.customer_id FROM customer AS CUST 
					INNER JOIN users AS USR ON (CUST.customer_id=USR.id)
				    WHERE USR.status='1'AND CUST.phone LIKE '%".$data['phone']."'";
			$res_count = $this->db->query($sql)->row_array();

			if($res_count!='') { 
				$rs = $this->db->where('id',$res_count['customer_id'])->update('users',array('password'=> md5($data['new_password'])));
				if($rs) {
					$res = array('status'=>1,'data'=>null);
				} else {
					$res = array('status'=>0,'message'=>'Updation failed Please try again','code'=>'ER15');
				}
			} else {
				$res = array('status'=>0,'message'=>'Phone Number Does not exists','code'=>'ER19');
			}
		} catch(Exception $e) {
			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		} 
		return $res;
	} 	

	function get_last_booking($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$cat_feild = '';
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$sql = "SELECT IF(review.event_id = '','false','true') AS is_last_booking_rated, 
							   booking.id AS booking_id, events.event_id AS event_id, 
							   event_gallery.media_url AS event_image,UNIX_TIMESTAMP(event_date_time.date) AS date,
							   booking.amount AS amount,translator_event.event_name 
						FROM events 
						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 
						RIGHT JOIN event_date_time ON event_date_time.id = booking.event_date_id 
						LEFT JOIN venue ON venue.id = events.venue_id 
						INNER JOIN translator_event ON translator_event.event_id = events.event_id 
						LEFT JOIN customer ON customer.customer_id = booking.customer_id 
						LEFT JOIN review ON review.event_id = booking.event_id 
						WHERE booking.customer_id = '$user_id' AND booking.status='2' AND 
							  (translator_event.language_code='$lang' OR translator_event.language_code='EN')
						ORDER BY booking.id DESC LIMIT 1";

				$result = $this->db->query($sql)->row_array();
				if(count($result)>0){
					$resultData = array(
						'is_last_booking_rated'=>$result['is_last_booking_rated'] === 'true'? true: false,
						'booking_id'=>$result['booking_id'],
						'event_id'=>$result['event_id'],
						'event_name'=>$result['event_name'],
						'event_image'=>$result['event_image'],
						'amount'=>$result['amount'],
						'date'=>$result['date']
					);
					$res = array('status'=>1,'data'=>$resultData);
				} 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 filters($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$sql = "SELECT LOC.id AS city_id,TLOC.locality_name AS city_name
						FROM locality AS LOC
						INNER JOIN customer AS CUST ON (CUST.city=LOC.region_id)
						INNER JOIN translator_locality AS TLOC ON (TLOC.locality_id=LOC.id)
						WHERE CUST.customer_id='$user_id' AND LOC.status='1' AND 
							  (TLOC.language_code='$lang' OR TLOC.language_code='EN')
						GROUP BY LOC.id";
				$locality = $this->db->query($sql)->result();

				$sql = "SELECT ECAT.cat_id AS category_id,TCAT.category_name AS category,
							   TCAT.category_image AS category_image
					    FROM event_category AS ECAT
						INNER JOIN translator_category AS TCAT ON (TCAT.category_id=ECAT.cat_id)
					    WHERE ECAT.status = 1 AND TCAT.language_code='$lang'
					    GROUP BY ECAT.cat_id
					    ORDER BY ECAT.priority";
				$category = $this->db->query($sql)->result();

				$locality = (!empty($locality))?$locality:array();
				$category = (!empty($category))?$category:array();

				if(!empty($locality) && !empty($category)){
					$res = array('status'=>1,'data'=>array('cities'=>$locality,'categories'=>$category));
				} 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 get_app_version() {
		$res = array();
		try{
			$settings = $this->db->get('setting')->row_array();
			if (!empty($settings)){
				$data = array('android_version_code'=>$settings['android_version'],
							  'ios_version_code'=>$settings['ios_version'],
							  'android_playstore_link'=>$settings['android_playstore_url'],
							  'ios_playstore_link'=>$settings['ios_playstore_url'],
							  'is_force_update'=>($settings['force_update'])?true:false);

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

	function logout($data) {
		$res = array();
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				$status = $this->db->update('customer',array('fcm_token'=>''),
													   array('customer_id'=>$user_id));
				if ($status){
					$res =array('status'=>1);
				}else {
					$res =array('status'=>0,'message'=>'Update failed please try again','code'=>'ER15');
				}
			}else {
				$res = array('status'=>0,'message'=>'No Data Found','code'=>'ER15');
			}
		} catch(Exception $e) {
			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		} 
		return $res;
	}

	function event_search($data) {
		$res = array();
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$per_page = 10;
				$str = urldecode(strtolower($data['query']));
				$countryData = $this->getCountryData($user_id);
				$lang = $countryData['language_code'];

				$this->db->query("SET SESSION group_concat_max_len = 200000");
				$sql = "SELECT GROUP_CONCAT(DISTINCT CONCAT_WS('#',EDATE.id,EDATE.date,EDATE.time)) 
							   AS date_time
						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)
						LEFT JOIN event_gallery AS IMG ON (IMG.event_id=EVT.event_id AND 
															IMG.media_type=0 AND IMG.status='1' )
						WHERE EDATE.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND EVT.status='1' AND 
					  		  VEN.status='1' AND EDATE.status='1' AND 
					  		  EVT.event_id IN (SELECT event_id FROM translator_event 
					  		  				   WHERE event_name LIKE '%$str%' OR 
					  		  				   		 event_description LIKE '%$str%' 
			  		  				   		   GROUP BY EVT.event_id)";

				$resCount = $this->db->query($sql)->result();

				if(empty($resCount)){
					return array('status'=>1,'data'=>array('events'=>[],'meta'=>$meta));
				}
			  	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]);
						}
					} else {
						unset($resCount[$key]);
					}
				}
				$count = count($resCount);
				$page = (isset($data['page']))?$data['page']:1;
				$page_limit = ($page - 1) * $per_page;
			  	$meta = array('total_pages'=>ceil($count/$per_page),'total'=>$count,
			  		          'current_page'=>$page,'per_page'=>$per_page);
				if($count > 0 && $count > $page_limit) {
					$limit = $page_limit.','.$per_page;

					$this->db->query("SET SESSION group_concat_max_len = 200000");
				  	$sql = "SELECT EVT.event_id,VEN.location,IMG.media_url AS event_image,
								   GROUP_CONCAT(DISTINCT CONCAT_WS('#',EDATE.id,EDATE.date,EDATE.time)) 
								   AS date_time,TEVT.event_name
							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 translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
							LEFT JOIN event_gallery AS IMG ON (IMG.event_id=EVT.event_id AND 
															   IMG.media_type=0  AND IMG.status='1')
							WHERE EDATE.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND EVT.status='1' AND 
						  		  VEN.status='1' AND EDATE.status='1' AND 
						  		  EVT.event_id IN (SELECT event_id FROM translator_event 
					  		  				  	   WHERE (event_name LIKE '%$str%' OR 
				  		  				  	   			 event_description LIKE '%$str%')
					  		  				  	   GROUP BY event_id)
						  	GROUP BY EVT.event_id
						  	ORDER BY EVT.event_id DESC
						  	LIMIT $limit";

				  	$resp = array();
				  	$result = $this->db->query($sql)->result();
				  	foreach ($result AS $key => $rs) {
					  	if(!empty($dates = explode(',',$rs->date_time)) && count($dates) > 0){
							$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)){
								unset($result[$key]);
								continue;
							}
						} else {
							unset($result[$key]);
							continue;
						}
						unset($result[$key]->date_time);
						$resp[] = $result[$key];
					}
					$res = array('status'=>1,'data'=>array('events'=>$resp,'meta'=>$meta));
			    } else {
					$res = array('status'=>1,'data'=>array('events'=>[],'meta'=>$meta));
		 		} 
	 		} else {
				$res = array('status'=>0,'message'=>'User Authentication Failed','code'=>'ER15');
			}
		} catch(Exception $e) {
			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		}
		return $res;
	}

	public function checkSeatAvailability($data = ''){
		$user_id 	 = $data['user_id'];
		$event_id 	 = $data['event_id'];
		$evtTimeId   = $data['time_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.id='$evtTimeId' AND 
			    	  EDATE.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
	    $evtSql = $this->db->query($sql);
	    $evtData = $evtSql->row_array();
		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.status='1' AND EDATE.id='$evtTimeId' 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);
	    	$lyCapacity['price'] = $lyout['price'];
	    	$lyCapacity['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']] = array('price'=>$custLy['price'],
 													  'capacity'=>$custLy['capacity'],
 													  'weekend_price'=>$custLy['weekend_price']);
 			}
	    }
		$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 BOOK.event_date_id='$evtTimeId'";
	    if(!empty($result = $this->db->query($sql)->result_array())){
	    	foreach($result AS $value) {
		    	if($evtData['show_layout'] == 0){
		    		$lyCapacity['capacity'] = $lyCapacity['capacity']-$value['no_of_ticket'];
		    	} else {
		    		$tkDtls = json_decode($value['ticket_details'],true);
		    		$aval = $lyCapacity[$tkDtls['color']]['capacity'];
		    		$aval = ($tkDtls['no_ticket']>$aval)?0:$aval-$tkDtls['no_ticket'];
	    			$lyCapacity[$tkDtls['color']]['capacity'] = $aval;
		    	}
	    	}
	    }
	    $event_layouts = array();
	    if($evtData['show_layout'] == 0){
	    	$capacity = $lyCapacity['capacity'];
	    	$lyCapacity['capacity'] = ($capacity < $maxBooking)? $capacity : $maxBooking;
	    	$event_layouts[] = array('rate'		  	=> $lyCapacity['price'],
    								 'class_name' 	=> null,
									 'max_ticket'	=> $lyCapacity['capacity']);
    	} else {
    		foreach($lyCapacity AS $block => $sData) {
    			$capacity = $sData['capacity'];
    			$lyCapacity[$block]['capacity'] = ($capacity < $maxBooking)? $capacity : $maxBooking;
	    		$event_layouts[] = array('rate'		    => $lyCapacity[$block]['price'],
    								     'class_name' 	=> $block,
									     'max_ticket'	=> $lyCapacity[$block]['capacity']);
    		}
    	}
  		return $event_layouts;
	}

	public function sync_contacts($data){
		$user_id = $this->auth_token_get($data['auth_token']);
		if(empty($data)){
			return array('status'=>0,'code'=>'918','message'=>'Data Missing');
		}
		$phNumbers = '';
		foreach($data['contacts'] AS $key => $number) {
			$number = preg_replace('/\D/', '', $number);
			$cond  = " AND CUST.enable_chat='1' AND USR.status='1'";
			$eCond = ($key != count($data['contacts'])-1)?') OR ':')';
			$eCond = $cond.$eCond;
			if(strlen($number) > 9){
				$phNumbers .= " (CUST.phone LIKE '%".substr($number, strlen($number)-9)."' ".$eCond;
			} else {
				$phNumbers .= " (CUST.phone LIKE '%".$number."' ".$eCond;
			}
		}
		if(empty($phNumbers)){
			return array('status'=>0,'code'=>'919','message'=>'Invalid Data');
		}

		$sql = "SELECT CUST.customer_id FROM customer AS CUST 
			    INNER JOIN users AS USR ON (USR.id=CUST.customer_id)
			    WHERE $phNumbers";
		$custIds = $this->db->query($sql)->result_array();
		if(empty($custIds)){
			return array('status'=>0,'code'=>'919','message'=>'No Data Found');
		}
		$user_ids = '';
		foreach ($custIds AS $id) {
			$user_ids = $id['customer_id'].',';
		}
		$user_ids = trim($user_ids,',');

		$result = $this->db->query("SELECT CUST.customer_id,CUST.name,CUST.phone,CUST.profile_image,
										   CUST.profile_image_qr,CHT.type AS friend_status 
								    FROM customer AS CUST 
								    LEFT JOIN chats AS CHT ON ((CUST.customer_id=CHT.from_user OR CUST.customer_id=CHT.to_user) AND CHT.type IN (0,1))
								    WHERE CUST.customer_id IN ($user_ids) AND 
								          customer_id NOT IN 
								          	(SELECT from_user FROM chats 
								          	 WHERE (from_user=$user_id AND type='2') OR 
								          	 	   (to_user=$user_id AND type='2')) 
						          	 	  AND 
								          customer_id NOT IN 
								          	(SELECT to_user FROM chats 
							          		WHERE (from_user=$user_id AND type='2') OR 
							          			  (to_user=$user_id AND type='2'))
						            GROUP BY CUST.customer_id");		
		$respArr['status'] = 1;	
		$respArr['data'] = (!empty($result) && !empty($result=$result->result_array()))?$result:[];
		return $respArr;
	}

	public function update_friend_request($data){
		$fromUser = $data['user_id'];
		$user_id = $this->auth_token_get($data['auth_token']);
		$status = $this->db->query("UPDATE chats SET type='".$data['add_as_friend']."' 
									WHERE from_user='".$fromUser."' AND to_user='".$user_id."'");

		if($data['add_as_friend'] == 1){
			$toCustData = $this->db->get_where('customer',array('customer_id'=>$fromUser))->row_array();
		    $frmCustData = $this->db->get_where('customer',array('customer_id'=>$user_id))->row_array();
		    $fcmData  = array('id'=>$user_id,'param'=>'user_id',
							  'title'=>'Accepted Chat Request',
							  'message'=>$frmCustData['name'].' has Accepted Your Chat Request');
			push_sent_cancel(1,$toCustData['fcm_token'],$fcmData);
		}
		return ($status)?1:0;
	}

	public function send_friend_request($data){
		$respArr = array('status'=>0,'code'=>'918','message'=>'Something Went Wrong..Try Again');
		$user_id = $this->auth_token_get($data['auth_token']);
		$toUser  = (is_numeric($data['user_id']))?$data['user_id']:decode_param($data['user_id']);
		
		if(empty($toUser)){
			return array('status'=>0,'code'=>'919','message'=>'Something Went Wrong.. Try Again..');
		}
		$result = $this->db->get_where('chats',array('from_user'=>$user_id,'to_user'=>$toUser))->row_array();
		if(empty($result)){
			$result=$this->db->get_where('chats',array('to_user'=>$user_id,'from_user'=>$toUser))->row_array();
			if(empty($result)){	
			    $this->db->insert('chats',array('from_user'=>$user_id,'to_user'=>$toUser,'type'=>'0'));

			    $toCustData = $this->db->get_where('customer',array('customer_id'=>$toUser))->row_array();
			    $frmCustData = $this->db->get_where('customer',array('customer_id'=>$user_id))->row_array();
			    $fcmData  = array('id'=>$toUser,'param'=>'user_id',
								  'title'=>'New Chat Request',
								  'message'=>'You got a New Chat Request from '.$toCustData['name']);
				push_sent_cancel(1,$frmCustData['fcm_token'],$fcmData);
			} else if (!empty($result) && $result['type'] == '0'){
				$this->db->update('chats',array('type'=>'1'),array('chat_id'=>$result['chat_id']));
			}
			$respArr['status'] = 1;
		}else{
			$respArr['status'] = 1;
		}
		return $respArr;	
	}

	public function get_friend_requests($data){
		$respArr = array('status'=>0,'code'=>'918','message'=>'No Request for you');
		$user_id = $this->auth_token_get($data['auth_token']);
		$result  = $this->db->query("SELECT CUST.name,CUST.phone,CUST.profile_image,CUST.profile_image_qr,
										    CUST.customer_id 
								     FROM customer AS CUST 
								     INNER JOIN chats AS CHT ON (CUST.customer_id = CHT.from_user) 
								     WHERE type='0' AND to_user='$user_id' 
								     GROUP BY CUST.customer_id");
		if(!empty($result) && !empty($result = $result->result())){
			$respArr['status'] = 1;
			$respArr['data'] = $result;
		}
		return $respArr;
	}

	public function recent_chats($data){
		$respArr = array('status'=>0,'code'=>'918','message'=>'No Request for you');
		$user_id = $this->auth_token_get($data['auth_token']);
		$result = $this->db->query("SELECT from_user,to_user,type FROM chats WHERE (from_user=$user_id OR to_user=$user_id) AND type IN('0','1')")->result_array();
		$custData = array();
		if(!empty($result)){
			foreach ($result as $key => $value) {
				if($value['type'] == 0){
					continue;
				}
				$fromUsrId = '';
				if($value['to_user'] == $user_id) {
					$fromUsrId = $value['from_user'];
				} else if ($value['from_user'] == $user_id) {
					$fromUsrId = $value['to_user'];
				} else {
				 	continue;
				}
				$sql = "SELECT CUST.name,CUST.phone,CUST.profile_image,CUST.profile_image_qr,
							   CUST.customer_id,CUST.fcm_token
						FROM customer AS CUST
						WHERE CUST.customer_id='$fromUsrId' AND CUST.enable_chat='1' 
						GROUP BY CUST.customer_id";
				$cust = $this->db->query($sql);
				if(!empty($cust) && !empty($cust = $cust->row_array())){
					$custData[] = $cust; 
				}
			}
			$respArr['status'] = 1;
			$respArr['data'] = $custData;
		}
		return $respArr;
	}

 	public function getCountry() {
 		try {
 			$rs = $this->db->query("SELECT * FROM country WHERE status = 1 ORDER BY country_name")->result();
 			if(count($rs) > 0) {
 				$res = array('status'=>'success','data'=>$rs);
 			} else {
 				$res = array('status'=>'error','message'=>'No records found','code'=>'ER13');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>'error','message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

	public function getCountryData($user_id){
		$ctryData = '';
		if(!empty($user_id)){
			$sql = "SELECT CTRY.* FROM customer AS CUST 
		      	    INNER JOIN country AS CTRY ON (CTRY.country_id=CUST.country_id)
		      	    WHERE CUST.customer_id='$user_id'";
			$ctryData = $this->db->query($sql)->row_array();
		}

		if(empty($ctryData)){
			$ctryData = $this->db->query("SELECT * FROM country WHERE language_code='EN'")->row_array();
		}
		return $ctryData;
	}

	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;
			
			$countryData = $this->getCountryData($user_id);
			$lang = $countryData['language_code'];

			$promDetails = langTranslator($promoData['promocode_id'],'PROMO',$lang);
			$datas['discounted_price'] = $tot_cost;
			$datas['terms_and_conditions'] = $promDetails['promocode_tc'];
			$datas['description'] = $promDetails['promocode_desc'];
			$respArr['status'] = 1;
			$respArr['data'] = $datas;
			return $respArr;
		}else{
			$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
		}
	}

    public 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 createGuestUser(){
		$res = array('status'=>0,'message'=>'Something went wrong','code'=>'ER10');
		$status = $this->db->insert('users',array('display_name'=>'Guest','user_type'=>'6'));
		if(!$status || empty($guest_id = $this->db->insert_id())){ 
			return $res; 
		}
		$guestInfo = array('customer_id'=>$guest_id,'name'=>'Guest','phone_verified'=>'1');
		$status = $this->db->insert('customer',$guestInfo);
		if(!$status){ 
			return $res; 
		}
		$auth_token = md5(microtime().rand());
		$this->generateAuth($guest_id,$auth_token);

		return array('status'=>'success','data'=>array('auth_token'=>$auth_token));
	}

	public function update_user_visibility($data){
		$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
	 			$status = $this->db->update('customer',array('enable_chat'=>$data['visible']),
	 										array('customer_id'=>$user_id));

	 			$res = array('status'=>1);
		 	} 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 update_user_location($data){
 		$res = array('status'=>0,'message'=>'Ohh No!! Something Went South!!','code'=>'ER06');
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0){
 				$this->db->update('customer',array('cust_lat'=>$data['latitude'],'cust_lng'=>$data['longitude']),array('customer_id'=>$user_id));
 				$res = array('status'=>1);
 			}else{
 				$res = array('status'=>0,'message'=>'User Authentication Error','code'=>'ER06');
 			}
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something Went South','code'=>'ER06');
 		}
 		return $res;
 	}

 	public function get_nearby_users($data){
 		$res = array('status'=>'error','message'=>'Ohh No!! Something Went South!!','code'=>'ER06');
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0){
 				$sql = "SELECT CUST.customer_id AS user_id,CUST.name,CUST.profile_image AS user_image,CUST.cust_lat AS latitude,CUST.cust_lng AS longitude, (((acos(sin((".$data['latitude']."*pi()/180)) * sin((CUST.cust_lat*pi()/180)) + cos((".$data['latitude']."*pi()/180)) * cos((CUST.cust_lat*pi()/180)) * cos(((".$data['longitude']." - CUST.cust_lng)*pi()/180))))*180/pi())*60*1.1515) as distance 
		 				FROM customer AS CUST 
		 				INNER JOIN users AS USR ON (USR.id = CUST.customer_id) 
		 				WHERE USR.user_type='3' AND USR.status='1' AND CUST.enable_chat='1'
		 				HAVING distance < 5";
		 		$result = $this->db->query($sql);
		 		if(!empty($result) && !empty($result = $result->result_array())){
		 			$res = array('status'=>'success','data'=>$result);	
		 		} else {
		 			$res = array('status'=>'error','message'=>'No Data Found','code'=>'ER12');	
		 		}
 			}else{
 				$res = array('status'=>'error','message'=>'Invalid User','code'=>'ER010');
 			}
 		}catch(Exception $e){
 			$res = array('status'=>'error','message'=>'Ohh No!! Something Went South','code'=>'ER08');
 		}
 		return $res;
 	}
}
?>
