<?php 

class Webservice_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
	}
	
	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{
			$this->db->select("region.id AS city_id,region.name AS city,
							   customer.name AS user_name,customer.phone,
							   customer.email,customer.profile_image AS profile_photo,
							   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");
			$this->db->where('users.status',1);
			$this->db->where('users.password',md5($data['password']));
			$this->db->where('customer.email',$data['email']);
			$this->db->from('users');
			$this->db->join('customer','customer.customer_id=users.id');
			$this->db->join('region','region.id=customer.city','left');
			$result = $this->db->get()->row();
			if($result){
				$auth_token = md5(microtime().rand());
				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,
					'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('language'=>$data['language']),
											 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('language' => $data['language']));
				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";
			$res_count = $this->db->where('email',$data['email'])->or_where('phone',$data['phone'])->get('customer')->result();
			if(count($res_count) > 0) {
				foreach ($res_count as $rs) {
					if($rs->email == $data['email']) {
						$is_email_available = "false";
					}
					if($rs->phone == $data['phone']) {
						$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 = $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($res_count->phone == $data['phone']) {
					$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'],
						'language'=>$data['language']
					);
					$this->db->insert('customer', $customer_data);
					$subject = "New account created successfully";
					$email_id = $data['email'];
					$message = "Hi,\n\r Welcome to TimeOut.\r\n Please use username: ".$email_id." and Password: ".$temp_password." for access your account";
					$this->send_mail($subject,$email_id,$message);
					$this->db->select("customer.name AS user_name,customer.phone,customer.email,customer.profile_image AS profile_photo,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,
							'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) { 
				
				$lang = $this->getUserLang($user_id);
				$field = 'faq_en';
				if($lang == 'ar'){
					$field = 'faq_ar';
				}

				$settingsDetails = $this->db->query("SELECT $field AS faq,contact_number FROM privacy_policy")->row_array();
				$userDetails = $this->db->query("SELECT customer.name AS name, customer.profile_image AS profile_photo,customer.gender AS gender, customer.email, customer.dob, customer.profile_city AS city_name, users.notification_status, users.email_status FROM customer INNER JOIN users ON users.id = customer.customer_id WHERE customer.customer_id = ".$user_id." AND users.status = 1 ")->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) {

				$lang = $this->getUserLang($user_id);
				$cityField = "region.name AS city";
				if($lang == 'ar') {
					$cityField = 'region.name_ar AS city';
				}
				$sql = "SELECT $cityField 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)){
					$cityName['city'] = 'null';
				}

				$where = '';
				$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
				/******************* CATEGORY *********************/

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

				/******************* END CATEGORY *********************/

				/******************* LATITUDE AND LONGITUDE *********************/

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

				/******************* END LATITUDE AND LONGITUDE ***/
				/******************* CITY ID *********************/
				if(isset($data['city_id'])) {
					$where = ' AND venue.region_id = '.$data['city_id'];
				}
				/******************* END CITY ID *********************/
				/******************* FILTER ***************************/

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

		 	 		//$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";	 	 		

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


 				// $count = $this->db->query("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 $where GROUP BY events.event_id")->num_rows();

				}
				/******************* END FILTER *********************/

				/******************* PAGINATION *********************/

				$count = $this->db->query("SELECT events.event_id 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 WHERE events.status = 1 $where GROUP BY events.event_id")->num_rows();
 				//echo "hai";exit();
				if($count > 0) {

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

					if($lang == 'ar') {
						$cat_field = 'event_category.category_ar';
					} else {
						$cat_field = 'event_category.category';
					}
					// End
					$page_limit = ($page - 1)*$per_page;

					if($count > $page_limit) {

						/******************* END PAGINATION *********************/

						$result = $this->db->query("SELECT events.seat_pricing,events.custom_seat_layout,venue.location_lat AS latitude,venue.location_lng AS longitude,venue.layout,venue.layout_details,events.event_id AS event_id, events.event_name AS name,events.event_name_ar AS name_ar,`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, $cat_field AS category, CAST(AVG (review.rate) AS DECIMAL (12,1)) AS rating, venue.venue_name, 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 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 ".$where." GROUP BY events.event_id LIMIT ". $page_limit.", ".$per_page)->result();	

						$response = array();
						foreach ($result as $key=>$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(
								'id' => "$key",
								'event_id'=>$rs->event_id,
								'image'=>$rs->image,
								'attendees'=>(!empty($rs->attendees))?$rs->attendees:'0',
								'category'=>$rs->category,
								'name'=>($lang == 'en')?$rs->name:$rs->name_ar,
								'rating'=>(!empty($rs->rating))?$rs->rating:'0',
								'location'=>$rs->venue_name.', '.$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

							);
							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'));
				$this->db->query("SET SESSION group_concat_max_len = 20000");
				$rs = $this->db->query("SELECT IF(host_categories.show_layout = 0,'false','true') AS is_layout,IF(events.has_payment = 0,'false','true') AS is_payment_required,IF(favourite.is_favorite = 1,'true','false') AS is_favorite,events.event_id, CAST(AVG (review.rate) AS DECIMAL (12,1)) AS rate, (SELECT SUM(no_of_ticket) FROM booking WHERE event_id = events.event_id AND status IN (1,2)) AS attendees, events.event_name,events.event_name_ar,events.event_discription AS event_description,events.event_discription_ar,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,venue.venue_name,venue.venue_details,venue.location,venue.location_lat AS lat,venue.location_lng AS lng,venue.venue_name AS address_name,venue.venue_name_ar AS address_name_ar,venue.location AS address, GROUP_CONCAT(DISTINCT `event_gallery`.`media_url`) AS media_url,IF(favourite.status = 1,'true','false') AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag, GROUP_CONCAT(DISTINCT tags.tag_name_ar) AS tag_ar, GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time, events.max_booking 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 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 LEFT JOIN tags on tags.tag_id = event_tags.tag_id LEFT JOIN review ON events.event_id = review.event_id INNER JOIN host_categories ON venue.host_cat_id = host_categories.host_cat_id WHERE event_date_time.date>='".date('Y-m-d')."' AND events.event_id = ".$event_id." GROUP BY events.event_id, event_date_time.event_id")->row();
				if(count($rs)>0){
					$resultData = array();
					$event_layout = '';
					$colorData = array();
					$booking = $this->db->where('event_id',$event_id)->select('ticket_details')->get('booking')->result();
					if(count($booking) > 0){
						foreach ($booking as $row) {
							$priceData[] = json_decode($row->ticket_details);
							if(count($priceData) > 0){
								foreach ($priceData as $value) {
								//	$colorData[$value->color] = isset($colorData[$value->color]) ? + $colorData[$value->color] + $value->no_ticket: $value->no_ticket;
								}
							}
						}
					}

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

					$bookedCount = 0;
	 				$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'];
					}


					$event_layout = json_decode($event_layout);
					$event_layouts = array();
					if(is_array($event_layout)){
						foreach ($event_layout as $value) {
							if(isset($colorData[$value->color])) {
								$avaliable = $value->capacity - $colorData[$value->color];
							} else {
								$avaliable = $value->capacity;
							}
							$priceLayout = array('class_name' => $value->color,
								'rate'=>$value->price,
								'total_tickets'=>$value->capacity,
								'available_tickets'=>$avaliable,
								"max_ticket"=>$rs->max_booking-$bookedCount
							);
							array_push($event_layouts, $priceLayout);

						}
					} else {
						$event_layouts[] = array('class_name' => null,
							'rate'=>$event_layout->price,
							'total_tickets'=>null,
							'available_tickets'=>null,
							"max_ticket"=>$rs->max_booking-$bookedCount
						);
					}

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

					$lang = $this->getUserLang($user_id);

					if($rs->is_layout && !empty($pData = json_decode($rs->seat_pricing, TRUE))){
						if($lang == 'en'){
							$rs->event_description .= '<p>'.$pData['price_details'].' '.'(SAR '.$pData['price'].')'.'</p>';
						}
						if($lang == 'ar'){
							$rs->event_discription_ar .= '<p>'.$pData['price_details_ar'].' '.'(SAR '.$pData['price'].')'.'</p>';
						}
					}
					$tags = ($lang == 'en')? explode(',', $rs->tag) : explode(',', $rs->tag_ar);
					$media_url = explode(',', $rs->media_url);	
					$resData = array(
						'event_id'=>$rs->event_id,
						'name'=>($lang == 'en')?$rs->event_name:$rs->event_name_ar,
						'description'=>($lang == 'en')?$rs->event_description:$rs->event_discription_ar,
						'rating'=>$rs->rate,
						'total_attendees'=>$rs->attendees == ''? '0': $rs->attendees,
						'layout_image'=>$rs->layout,
						'is_favorite'=>$rs->is_favorite === 'true'? true: false,
						'is_payment_required'=>$rs->is_payment_required === 'true'? true: false,
						'is_layout'=>$rs->is_layout === 'true'? 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'=>($lang == 'en')?$rs->address_name:$rs->address_name_ar,
						'address'=>$rs->address,
						'longitude'=>$rs->lng
					);

					$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 getUserLang($user_id){
		$lang = $this->db->select('language')->where('customer_id',$user_id)->get('customer')->row();
		return $lang->language;
	}

	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('no-reply@nuvento.com', 'TimeOut');
		$ci->email->to($email);
		$ci->email->cc('epocnova@gmail.com');
		$ci->email->subject($subject);
		$ci->email->message($message);
		if($attach!=null) {
			$ci->email->attach($attach);
		}
		return $ci->email->send();
	}

	function get_category_list($data) {
		try {

			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) { 
				if(isset($data['query'])) {
					$where = ' AND event_category.category LIKE '."'%".$data['query'].'%'."'";
				} else {
					$where = '';
				}
				$lang = $this->db->select('language')->where('customer_id', $user_id)->get('customer')->row();

				if($lang->language == 'ar') {
					$cat_field = 'event_category.category_ar AS category_name';
					$cat_field .= ',event_category.category_image_ar AS category_image';
				} else {
					$cat_field = 'event_category.category AS category_name';
					$cat_field .= ',event_category.category_image AS category_image';
				}

				$result = $this->db->query("SELECT events.venue_id AS region_id,event_category.cat_id AS category_id, $cat_field,event_category.category_description AS category_description FROM event_category LEFT JOIN events ON events.category_id = event_category.cat_id WHERE event_category.status = 1 ".$where." GROUP BY event_category.cat_id")->result();

				if(count($result)>0){
					$resultData = array();					
					$resultData['category'] = $result;
					$res = array('status'=>1,'data'=>$resultData);
				} 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) { 
			// language
				$lang = $this->db->select('language')->where('customer_id', $user_id)->get('customer')->row();
				if($lang->language == 'ar') {
					$region_name = 'region.name_ar';
				} else {
					$region_name = 'region.name';
				}
			// End
				$result = $this->db->query("SELECT region.id AS city_id, $region_name AS city_name, region.region_icon AS city_image FROM region WHERE region.status = 1 GROUP BY region.name")->result();
				if(count($result)>0){
					$resultData = array();					
					$resultData['cities'] = $result;
					$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 update_city($data) {
		try{
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				if(isset($data['city_id']) && !empty($data['city_id'])){
					$re = $this->db->select('name')->where('id', $data['city_id'])->where('status', 1)->get('region')->row();	
					$cityName = $re->name;
					$cityId = $data['city_id'];

				}else{
					$radius = 25;
					$data = $this->db->query("SELECT id,name,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  HAVING distance < ".$radius." AND status = '1' ORDER BY distance ASC LIMIT 1")->result_array();

					if(!empty($data)){
						$cityId = $data[0]['id'];
						$cityName = $data[0]['name'];
					}
					
				}
				if(!empty($cityId)){
					$this->db->where('customer_id', $user_id);
					$this->db->update('customer', array('city' => $cityId));

					$resultArray = array('city_id'=>$cityId,'city_name'=>$cityName);
					$res = array('status'=>1, 'data'=>$resultArray);
				}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) { 
				$bookingId = $data['booking_id'];
				$ticketDetails = $this->db->query("SELECT ticket_details FROM booking WHERE bookId = '$bookingId'")->row();
				$res = json_decode($ticketDetails->ticket_details);
				if(!empty($res)){
					$kk['ticket_rate'] = "$res->price";
				}
				$settingsDetails = $this->db->query("SELECT instruction_en AS instruction,contact_number FROM privacy_policy")->row_array();
				$lang = $this->getUserLang($user_id);
				
				if($lang == 'en'){
					$cat_filed = 'events.event_name AS event_name';
					$cat_filed .= ',venue.venue_name AS address_name';
				}else{
					$cat_filed = 'events.event_name_ar AS event_name';
					$cat_filed .= ',venue.venue_name_ar AS address_name';
				}
				
				$result = $this->db->query("SELECT booking.qrcode,events.event_id,events.has_payment AS is_payment_required,$cat_filed, `event_gallery`.`media_url` AS event_image,event_date_time.date, booking.bookId AS ticket_id,event_date_time.time,venue.location_lat AS latitude, venue.location_lng AS longitude,venue.location AS address, booking.amount AS total_rate, booking.no_of_ticket AS ticket_count, customer.name AS profile_name, customer.profile_image AS profile_photo 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 = '$bookingId' AND booking.customer_id = ".$user_id."")->row_array();
				if(count($result)>0 && count($settingsDetails)>0){
					$result['is_payment_required'] = ($result['is_payment_required'] == 1) ? true: false;
					$resultData = array();					
					$resultData = array_merge($settingsDetails, $result,!empty($kk)?$kk:[]);
					$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']);
			$img_error = 0;
			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'])){
					$img=$data['file']['name']; 
					$expbanner = explode('.',$img);
					$img_ext = strtolower($expbanner[1]);				 
					$rand = rand(10000,99999);
					$encname = time().$rand;
					if($img_ext=='png' || $img_ext=='jpeg' || $img_ext == 'jpg' || $img_ext == 'gif'){
						$bannername = $encname.'.'.$img_ext;
						$imagePath="./assets/uploads/".$bannername;
						$post_data['profile_image'] = "assets/uploads/".$bannername;
						move_uploaded_file($data['file']["tmp_name"],$imagePath); 
						$state = $this->db->where('customer_id',$user_id)->update('customer',$post_data);
						if($state){
							$img_error = 1;
						} else {
							$res = array('status'=>0,'message'=>'Profile update failed','code'=>'ER32');
						}
					} else {
						$res = array('status'=>0,'message'=>'Invalid Image type','code'=>'ER41');	
					}
				} else {
					$state = $this->db->where('customer_id',$user_id)->update('customer',$post_data);
					if($state){
						$img_error = 1;	
					} else {
						$res = array('status'=>0,'message'=>'Profile update failed','code'=>'ER32');
					}
				}

				if($img_error == 1) {
					$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',$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;
				$post_data['customer_id'] = $user_id;
				$post_data['ticket_details'] = json_encode($post_data['ticket_details']);
				$post_data['status'] = (isset($post_data['has_payment']) && $post_data['has_payment'] == 0)?'1':'3';
 				unset($post_data['auth_token'],$post_data['has_payment']);
				$code = 'TO';
				$ymd = date('ymd');
				$squence = rand(1111,9999);
				$squence = str_pad($squence,4,0,STR_PAD_LEFT);
				$post_data['bookId'] = $code.$ymd.$squence;
				$post_data['qrcode'] = genQRcode($post_data['bookId']);
				$post_data['booking_date'] = date('Y-m-d H:i:s');
				$rs = $this->db->insert('booking', $post_data);
				$id = $this->db->insert_id();
				if($id){
					$res = array('status'=>1,'data'=>array('bookingCode'=>$post_data['bookId']));
				} 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) { 
				$res_count = $this->db->where('bookId',$data['booking_id'])->where('status',1)->get('booking')->num_rows();
				if($res_count > 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 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;
	} 	


	function favouritelist($data) {
		try {
			$user_id = $this->auth_token_get($data['auth_token']);
			if($user_id > 0) {
				$where = array(
					'favourite.status'=>1,
					'favourite.is_favorite'=>1,
					'favourite.user_id'=>$user_id,
					'events.status'=>1
				);
				$lang = $this->db->select('language')->where('customer_id', $user_id)->get('customer')->row();

				if($lang->language == 'ar') {
					$cat_field = 'event_category.category_ar AS category';
					$cat_field .= ',events.event_name_ar AS event_name';
				} else {
					$cat_field = 'event_category.category AS category';
					$cat_field .= ',events.event_name AS event_name';
				}
				$result = $this->db->select("events.event_id,event_gallery.media_url,(SELECT COUNT(booking.id) FROM booking WHERE booking.event_id = events.event_id) AS attendees,
					$cat_field,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")->where($where)->from('favourite')->join('review', 'review.event_id = favourite.event_id','LEFT')->join('events', 'events.event_id = favourite.event_id')->join('booking', 'booking.event_id = events.event_id','LEFT')->join('venue', 'venue.id = events.venue_id')->join('event_category', 'events.category_id = event_category.cat_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'];
						}
						$lang = $this->getUserLang($user_id);
						$resData = array(
							'event_id'=>$rs->event_id,
							'image'=>$rs->media_url,
							'attendees'=>$rs->attendees,
							'category'=>$rs->category,
							'name'=>$rs->event_name,
							'rating'=>$rs->rating,
							'location'=>$rs->location,
							'rate'=>$price,
							'location'=>$rs->location,
							'is_favorite'=>$rs->is_favorite === 'true'? true: false,
							'is_editors_choice'=>$rs->is_editors_choice === 'true'? true: false
						);
						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->getUserLang($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 id FROM booking AS BOK
 					INNER JOIN events AS EVT ON (EVT.event_id=BOK.event_id)
 					WHERE BOK.customer_id='$user_id' AND BOK.status IN (0,1,2) AND 
 						  EVT.status='1'")->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->getUserLang($user_id);
						if($lang == 'en'){
							$event_name = 'events.event_name AS event_name';
						}else{
							$event_name = 'events.event_name_ar AS event_name';
						}
						$result = $this->db->select("booking.bookId AS booking_id,booking.event_id,$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, events.has_payment")->where('booking.customer_id',$user_id)->where_in('booking.status',array(0,1,2))->from('booking')->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')->group_by('booking.id')->order_by('booking.id','DESC')->limit($per_page,$page_limit)->get()->result_array();

						// $data_arr = array();

						// foreach ($result as $value) {
						// 	$data_arr[] = $value;
						// 	$bookList = array_slice($data_arr, $page_limit, $per_page, false);
						// }

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

				$lang = $this->getUserLang($user_id);
				$fields = 'privacy_policy_en AS privacy_policy,
						   terms_and_conditions_en AS terms_and_conditions,';
				if($lang == 'ar'){
					$fields = 'privacy_policy_ar AS privacy_policy,
							   terms_and_conditions_ar AS terms_and_conditions,';
				}

				$settingsDetails = $this->db->query("SELECT $fields contact_number FROM privacy_policy")
											->row_array();

				$notificationDetails = $this->db->query("SELECT notification_status, email_status 
														 FROM users WHERE id = ".$user_id."")
												->row_array();
				if(count($settingsDetails)>0 && count($notificationDetails)>0){
					$resultData = array_merge($settingsDetails, $notificationDetails);
					$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 {
			$res_count = $this->db->select('customer.customer_id')->where('users.status=',1)->where('customer.phone',$data['phone'])->from('customer')->join('users','customer.customer_id = users.id')->get()->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 = '';
				$lang = $this->getUserLang($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->query("SELECT IF(review.event_id = '','false','true') AS is_last_booking_rated, booking.id AS booking_id, events.event_id AS event_id,$cat_field, `event_gallery`.`media_url` AS event_image,UNIX_TIMESTAMP(event_date_time.date) AS date, booking.amount AS amount 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 LEFT JOIN review ON review.event_id = booking.event_id WHERE booking.customer_id = ".$user_id." AND booking.status='2' ORDER BY booking.id DESC LIMIT 1")->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) { 
				$lang = $this->db->select('language')->where('customer_id', $user_id)->get('customer')->row();
				if($lang->language == 'ar') {
					$loc_field = 'locality.locality_ar AS city_name';

					$cat_field = 'event_category.category_ar AS category';
					$cat_field .= ',event_category.category_image_ar AS category_image';

					$dateArray = [["date_id"=>'كل الأيام',"date"=>"1"],["date_id"=>'اليوم',"date"=>"2"],["date_id"=>'غدا',"date"=>"3"],["date_id"=>'هذا الاسبوع',"date"=>"4"],["date_id"=>'عطلة نهاية الاسبوع',"date"=>"5"],["date_id"=>'في وقت لاحق',"date"=>"6"]];
				} else {
					$loc_field = 'locality.locality AS city_name';

					$cat_field = 'event_category.category AS category';
					$cat_field .= ',event_category.category_image AS category_image';

					$dateArray = [["date_id"=>"All Days","date"=>"1"],["date_id"=>"Today","date"=>"2"],["date_id"=>"Tomorrow","date"=>"3"],["date_id"=>"This week","date"=>"4"],["date_id"=>"Weekend","date"=>"5"],["date_id"=>"Later","date"=>"6"]];
				}

				$sql = "SELECT locality.id AS city_id, $loc_field FROM locality
						INNER JOIN customer ON customer.city=locality.region_id
						WHERE customer.customer_id='$user_id' AND locality.status='1'";
				$locality = $this->db->query($sql)->result();

				$category = $this->db->query("SELECT cat_id AS category_id, $cat_field 
											  FROM event_category WHERE status = 1")->result();
				

				if(!EMPTY($locality)) {
					$locality = $locality;
				}else{
					$locality = array();
				}
				if(!EMPTY($category)) {
					$category = $category;
				}else{
					$category = array();
				}
				if(isset($dateArray)){
					$resultData = array();					
					$resData = array(
						'cities'=>$locality,
						'categories'=>$category,
						'dates'=>$dateArray
					);
					$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 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']));
				
				$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
						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 event_gallery AS IMG ON 
							  (IMG.event_id=EVT.event_id AND IMG.media_type=0)
						WHERE (EVT.event_name LIKE '%$str%' OR 
							  EVT.event_name_ar LIKE '%$str%') AND
					  		  EDATE.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND EVT.status='1' AND 
					  		  VEN.status='1' AND IMG.status='1' AND EDATE.status='1'
			  		    GROUP BY EVT.event_id";
				$resCount = $this->db->query($sql)->result();

			  	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) {

					$lang = $this->getUserLang($user_id);
					if($lang == 'en') $event_name = 'events.event_name AS event_name';
					else $event_name = 'events.event_name_ar AS event_name';

					$limit = $page_limit.','.$per_page;

					$this->db->query("SET SESSION group_concat_max_len = 20000");
					$sql = "SELECT EVT.event_id,EVT.event_name,VEN.location,
								   IMG.media_url AS event_image,
								   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)
							INNER JOIN event_gallery AS IMG ON 
								  (IMG.event_id=EVT.event_id AND IMG.media_type=0)
							WHERE (EVT.event_name LIKE '%$str%' OR 
								  EVT.event_name_ar LIKE '%$str%') AND
						  		  EDATE.date>=DATE_FORMAT(NOW(),'%Y-%m-%d') AND EVT.status='1' AND 
						  		  VEN.status='1' AND IMG.status='1' AND EDATE.status='1'
						  	GROUP BY EVT.event_id
						  	ORDER BY EVT.event_id DESC
						  	LIMIT $limit";
				  	$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]);
							}
						} else {
							unset($result[$key]);
						}
						unset($result[$key]->date_time);
					}
					
					$res = array('status'=>1,'data'=>array('events'=>$result,'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;
	}
}
?>



