<?php 

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

 	function login($data){
 		try{
 			$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, IF(customer.city = '','false','true') AS is_location_updated");
 			$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');
	 		$result = $this->db->get()->row();
	 		if($result){
	 			$auth_token = md5(microtime().rand());
	 			$resultArray = array(
 						'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,
 						
 						);
	 			$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 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{
 			$res_count = $this->db->where('email',$data['email'])->or_where('phone',$data['phone'])->get('customer')->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']
	 								 );
	 				$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) { 
 			$settingsDetails = $this->db->query("SELECT faq,contact_number FROM privacy_policy")->row_array();
 			$userDetails = $this->db->query("SELECT customer.name AS name, customer.profile_image AS profile_photo,(CASE customer.gender WHEN 1 THEN '0' WHEN 2 THEN '1' ELSE '3' END) AS gender, customer.email, customer.dob, customer.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) {
 				$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.category_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 LEFT JOIN events ON events.venue_id = venue.id GROUP BY events.category_id HAVING distance < ".$radius." AND venue.status = '1'")->result_array();

	 					$otherV = '';
	 					foreach($res as $key => $value){
	 						if ($otherV) $otherV .= ',';
	 						$otherV .= $value['category_id'];
	 					}
	 				$where = ' AND events.category_id IN ('.$otherV.')';
 				}

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

 				/******************* FILTER *****************************************/

 				if(isset($data['filters'])){

 					$filtersElement = json_decode($data['filters'], true);
		 	 		$locality_id = $filtersElement['cities'];
		 	 		$dateId = $filtersElement['date'];
		 	 		$categoryId = $filtersElement['category'];

		 	 		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 WHERE events.status = 1 $where GROUP BY events.event_id")->num_rows();

 				if($count > 0) {

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

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

 					if($count > $page_limit) {

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

 				$result = $this->db->query("SELECT events.event_id AS event_id, events.event_name AS name,`event_gallery`.`media_url` AS image, COUNT(booking.id) AS attendees, event_category.category, AVG(review.rate) AS rating, venue.location, IF(favourite.status = 1, 'true','false') AS is_favorite, IF(events.provider_id = 1,'true','false') AS is_editors_choice, events.avg_price AS rate 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 LEFT 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")->result();

 				$cityName = $this->db->select('city')->where('customer_id', $user_id)->get('customer')->row();

 				$meta = array('total_pages'=>ceil($count/$per_page),
	 									  'total'=>$count,
	 									  'current_page'=>$page,
	 									  'per_page'=>$per_page
	 									 );
 				
				if(count($result)>0){
					$resultData = array();	
					$resultData['city_name'] = $cityName->city;				
					$resultData['events'] = $result;
					$response = array('data'=>$resultData,'meta'=>$meta);
					$res = array('status'=>1,'data'=>$response);
				 
				}else {
					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
				}
				} else {
 						$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 					}}else {
					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
				}
				} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res; 		
 	}


 	function event($data) {

 		try {
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$event_id = $data['event_id'];
 				$this->db->query("SET SESSION group_concat_max_len = 20000");
 				$rs = $this->db->query("SELECT events.event_id, AVG(review.rate) AS rate, MAX(booking.id) AS attendees, events.event_name,events.event_discription AS event_description,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_details 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 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 WHERE 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;
							}
							$event_layout = json_decode($event_layout);
							$event_layouts = array();
							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
                								);
								array_push($event_layouts, $priceLayout);

							}

							$dates = explode(',', $rs->date_time);

							
							$time_spec = array();
							$data_array = array();

							foreach ($dates as $rss) {
								list($id,$date,$time) = explode('#', $rss);
								$data_array[$date][] = array('id'=>$id, 'time'=>$time);
								$time_spec[] = array('id'=>$id, 'date'=>$date, 'time'=>$time);
							}
							$date_list = array();
							foreach ($data_array as $key => $value) {
								$date_list[] = array('date'=>$key, 'time'=>$value);
							}
	
							$tags = explode(',', $rs->tag);
							$media_url = explode(',', $rs->media_url);	
							$resData = array(
								'event_id'=>$rs->event_id,
								'name'=>$rs->event_name,
								'description'=>$rs->event_description,
								'rating'=>$rs->rate,
								'total_attendees'=>$rs->attendees,
								'layout_image'=>$rs->layout,
								'is_favorite'=>$rs->is_favorite === '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'=>$rs->address_name,
								'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 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 = '';
 				}

 			$result = $this->db->query("SELECT events.venue_id AS region_id,event_category.cat_id AS category_id, event_category.category AS category_name, event_category.category_image AS category_image, 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'=>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 add_favorites($data) {
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 			
	 			$favoriteList = array('user_id'=>$user_id, 'event_id'=>$data['event_id'], 'is_favorite'=>$data['is_favorite']);
	 			$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) { 
 			$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($data['city_id']!=''){
	 				$re = $this->db->select('name')->where('id', $data['city_id'])->where('status', 1)->get('region')->row();	
	 				$cityName = $re->name;
					
				}else{
					$radius = 25;
					$data = $this->db->query("SELECT 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();
					
					$cityName = $data[0]['name'];
				}
				$this->db->where('customer_id', $user_id);
				$id = $this->db->update('customer', array('city' => $cityName));
	 			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 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 id = ".$bookingId." ")->row();
 			$res = json_decode($ticketDetails->ticket_details);
 			$kk['ticket_rate'] = "$res->total_price";
 			$settingsDetails = $this->db->query("SELECT contact_number FROM privacy_policy")->row_array();
 			$result = $this->db->query("SELECT booking.qrcode, events.event_discription AS instruction,events.event_id,events.event_name, `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.venue_name AS address_name, venue.venue_details 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.id = ".$bookingId." AND booking.customer_id = ".$user_id."")->row_array();
				if(count($result)>0 && count($settingsDetails)>0){
					$resultData = array();					
					$resultData = array_merge($settingsDetails, $result,$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['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;
 				unset($post_data['auth_token']);
 				$post_data['customer_id'] = $user_id;
 				$post_data['ticket_details'] = json_encode($post_data['ticket_details']);
 				$post_data['qrcode'] = $this->generateQR($post_data);
 				$post_data['status'] = 1;
 				$code = 'TO';
				$ymd = date('ymd');
				$squence = rand(1111,9999);
				$squence = str_pad($squence,4,0,STR_PAD_LEFT);
				$post_data['bookId'] = $code.$ymd.$squence;
				$rs = $this->db->insert('booking', $post_data);
				$id = $this->db->insert_id();
				if($id){
		 			$res = array('status'=>1,'data'=>array('bookingCode'=>"$id"));
		 		} 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['bookingCode'])->where('status',1)->get('booking')->num_rows();
 				if($res_count > 0) {
 					$rs = $this->db->where('bookId',$data['bookingCode'])->update('booking',array('status'=>0));
 					if($rs) {
 						$res = array('status'=>1,'data'=>null);
 					} else {
 						$res = array('status'=>0,'message'=>'Cancel submission failed','code'=>'ER25');
 					}
 				} else {
 					$res = array('status'=>0,'message'=>'Invalid 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
 				);
 				$result = $this->db->select("events.event_id,event_gallery.media_url,COUNT(booking.id) AS attendees,
 					event_category.category,events.event_name,AVG(review.rate) 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','RIGHT')->join('events', 'events.event_id = favourite.event_id')->join('booking', 'booking.event_id = events.event_id')->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'];
						}
						$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);
					//print_r($res);exit();
				} else {
					$res = array('status'=>0,'message'=>'No favourites yet!','code'=>'ER22');
				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

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


 	 	function bookedlist($data) {
 		try {
 			$per_page = 10;
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$count = $this->db->select('booking.id')->where('booking.customer_id',$user_id)->get('booking')->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) {
 						$result = $this->db->select('booking.id 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)->where('booking.status!=',3)->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')->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'=>0,'message'=>'No records found','code'=>'ER13');
 					}
 				} else {
 					$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
 				} 				
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}





 	function get_settings($data) {
 		try {
			
			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
 		$settingsDetails = $this->db->query("SELECT privacy_policy,terms_and_conditions,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? 1: 0,
 						'email_status'=>$resultData['email_status'] === 1? 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) { 
 			$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, events.event_name, `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." 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) { 

 			$locality = $this->db->select('id AS city_id,locality AS city_name')->where('status',1)->get('locality')->result();
 			
 			$category = $this->db->select('cat_id AS category_id,category AS category,category_image')->where('status',1)->get('event_category')->result();
 			
			$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"]];

			if(!EMPTY($locality)) {
				$locality = $locality;
			}else{
				$locality = 'null';
			}
			if(!EMPTY($category)) {
				$category = $category;
			}else{
				$category = 'null';
			}
				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; 		
 	}
 }
 ?>