<?php 

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

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

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

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

 	function register($data) {
 		try{
 			$email = $data['email_id'];
 			$phone = preg_replace('/\D/', '', $data['phone']);
 			$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_id'] && $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_id']){
 					$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 {
 				$unique_id = uniqid().time();
 				$temp_password = $data['password'];
	 			$data['password'] = md5($data['password']);

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

	 			if($id) {
	 				if(strpos($data['phone'],'+') === true){
	 					$data['phone'] = str_replace('+','',$data['phone']);
	 				}
	 				if(strpos($data['phone'],'966') !== true){
	 					$data['phone'] = '966'.$data['phone'];
	 				}

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

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

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

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


	 				$res = array('status'=>1,'data'=>'');

	 				// $this->db->select('customer.name,customer.dob,customer.phone,customer.email,customer.profile_image AS image,customer.gender,users.id AS userId, customer.city');
		 			// $this->db->where('users.id',$id);
			 		// $this->db->from('users');
			 		// $this->db->join('customer','customer.customer_id = users.id');
			 		// $result = $this->db->get()->row();
			 		// if($result){
			 		// 	$result->dob = (!empty($result->dob))?date("m/d/Y",$result->dob/1000):'';
			 		// 	$result->auth_token = md5(microtime().rand());
			 		// 	$this->generateAuth($result->userId,$result->auth_token);
			 		// 	$res = array('status'=>1,'data'=>$result,'message'=>'An activation Email has been set to your mail id');
			 		// } else {
			 		// 	$res = array('status'=>0,'message'=>'No record found','code'=>'ER13');
			 		// }
	 			} else {
	 				$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 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->subject($subject);
        $ci->email->message($message);
        $ci->email->set_mailtype('html');
        if($attach != null) {
          $ci->email->attach($attach);
        }
        return $ci->email->send();
 	}

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

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

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

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

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

 		return $res;
 	}

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

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

 		return $res;
 	}

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

 		return $res;
 	}

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

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

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

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

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

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

 	function bookedlist($data) {
 		try {
 			$per_page = 10;
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$sql = "SELECT id FROM booking 
 						WHERE customer_id='$user_id' AND status IN (0,1,2) 
 						GROUP BY booking.id";
 				$count = $this->db->query($sql)->num_rows();
				
 				if($count > 0) {
 					$page = 1;
 					if(isset($data['page'])) {
 						$page = $data['page']; 						
 					}
 					$page_limit = ($page - 1) * $per_page;

 					if($count > $page_limit) {
 						$sql = "SELECT booking.id AS book_id,booking.event_id,booking.bookId AS bookingCode,
 									   booking.qrcode,booking.no_of_ticket,booking.amount,venue.location,
 									   booking.status AS book_status,event_gallery.media_url,
 									   venue.id AS venue_id,event_date_time.date AS event_date,
 									   event_date_time.time AS event_time 
 								FROM booking 
 								JOIN events ON booking.event_id=events.event_id 
 								JOIN event_date_time ON booking.event_date_id=event_date_time.id 
 								JOIN venue ON venue.id=events.venue_id 
 								LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id AND 
 														   event_gallery.media_type=0 
 								WHERE customer_id='$user_id' AND booking.status IN(0,1,2) 
 								GROUP BY booking.id ORDER BY booking.id DESC LIMIT 10";
 						$result = $this->db->query($sql)->result_array();

 						if(!empty($result)){
 							foreach ($result AS $key => $data) {
 								$eData  = langTranslator($data['event_id'],'EVT');
			 					$result[$key] = array_merge($result[$key],$eData);
			 					$vData  = langTranslator($data['venue_id'],'VEN');
			 					$result[$key] = array_merge($result[$key],$vData);
 							}
 						}
 						
 						$meta = array('total_pages'=>ceil($count/$per_page),'total'=>$count,
 									  'current_page'=>$page,'per_page'=>$per_page);

 						$response = array('data'=>$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 bookingdetails($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {
 				$result = $this->db->select('booking.id AS book_id,booking.event_id,booking.bookId AS bookingCode,booking.qrcode,booking.no_of_ticket,booking.amount,booking.status AS book_status,events.event_name_en,events.event_name_ar,events.event_description_en,events.event_description_ar,event_gallery.media_url,venue.location,customer.name AS customer_name,customer.profile_image,venue.venue_name_en,venue.venue_name_ar,venue.location_lat AS lat,venue.location_lng AS lng, booking.ticket_details')->where('booking.bookId',$data['bookingCode'])->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')->join('customer','customer.customer_id = booking.customer_id')->get()->row();
 				if(count($result)>0){
 					$res = array('status'=>1,'data'=>$result);
 				} 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 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 confirm($data) {
 		try {
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) { 
 				$res_count=$this->db->where('bookId',$data['bookingCode'])->get('booking')->num_rows();
 				if($res_count > 0) {
					$sql = "SELECT booking.id AS book_id,booking.event_id,booking.bookId AS bookingCode,
								   booking.qrcode,booking.no_of_ticket,booking.amount,venue.id AS venue_id,
								   booking.status AS book_status,event_gallery.media_url,venue.location,
								   customer.name AS customer_name,customer.profile_image,
								   booking.ticket_details,event_date_time.time,event_date_time.date,
								   venue.location_lat AS lat,venue.location_lng AS lng
						    FROM booking 
						    JOIN events ON booking.event_id=events.event_id 
						    JOIN event_date_time ON booking.event_date_id=event_date_time.id 
						    JOIN venue ON venue.id=events.venue_id 
						    LEFT JOIN event_gallery ON events.event_id=event_gallery.event_id 
						    JOIN customer ON customer.customer_id=booking.customer_id 
						    WHERE booking.bookId='".$data['bookingCode']."'";
				    $result = $this->db->query($sql)->row_array();

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

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

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

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

    function imageResize($path,$size){
        $this->load->library('image_lib');
        $config['width']          = $size['width'];
        $config['height']         = $size['height'];
        $config['new_image']      = $path;
        $config['source_image']   = $path;
        $config['create_thumb']   = FALSE;
        $config['image_library']  = 'gd2';
        $config['maintain_ratio'] = TRUE;
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        $this->image_lib->resize();
    }

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

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

 	function tempbooking($data) {
 		try{
 			$user_id = $this->auth_token_get($data['auth_token']);
 			if($user_id > 0) {

 				$post_data = $data;
 				$status = (isset($post_data['has_payment']) && $post_data['has_payment'] == 0)?'1':'3';

 				$post_data['status'] 			= $status;
				$post_data['bookId'] 			= 'TO'.date('ymd').str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
				$post_data['qrcode'] 			= genQRcode($post_data['bookId']);
 				$post_data['customer_id'] 		= $user_id;
				$post_data['booking_date'] 		= date('Y-m-d H:i:s');
 				$post_data['ticket_details'] 	= json_encode($post_data['ticket_details']);

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

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

				$rs = $this->db->insert('booking', $post_data);
				if($rs){
					if(!empty($promocodeData)){
						$this->db->insert('promocode_used',$promocodeData);
					}
		 			$res = array('status'=>1,'data'=>array('user_id'=>$user_id,
		 						 'bookingCode'=>$post_data['bookId']));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 	function discover($data) {

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

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

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


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

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

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

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

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

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

					$dates = explode(',', $rs->date_time);
					$time_spec = array();
					$latlng = array('lat'=>$rs->lat, 'lng'=>$rs->lng);
					foreach ($dates as $rss) {
						$timeArray = explode('#', $rss);

						$sTime = $timeArray[1].' '.$timeArray[2];
						$cTime = date("Y-m-d H:i", strtotime('+15 minutes'));

						if($cTime < $sTime){ 
							$time_spec[$timeArray[1]][] = array("id"=>$timeArray[0],
																"time"=>$timeArray[2]);
						}
					}
					$media_url = explode(',', $rs->media_url);
					
					$tagArr  = array();
					$resData = array();

					$resData['latlng'] = $latlng;
					$resData['event_id'] = $rs->event_id;
					$resData['event_rate'] = $rate;
					$resData['event_urls'] = $media_url;
					$resData['fav_status'] = $rs->fav_status;
					$resData['event_price'] = $price;
					$resData['has_payment'] = $rs->has_payment;
					$resData['event_times'] = $time_spec;
					$resData['max_booking'] = $rs->max_booking-$bookedCount;
					$resData['show_layout'] = $rs->show_layout;
					$resData['seat_pricing'] = $rs->seat_pricing;
					$resData['venue_location'] = $rs->location;
					$resData['event_attendees'] = $atte;
					$resData['event_layout_url'] = $rs->layout;
					$resData['event_price_layout'] = $event_layout;

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

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

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

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

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

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

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

			$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(isset($data['venue_id']) && !empty($data['venue_id'])) {
				$where .= " AND locality.id ='".$data['venue_id']."'";
			}

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

          		$this->db->update('booking',array('status'=>'1'),array('bookId'=>$book_id));
          		$this->db->update('event_invites',array('status'=>'1'),array('book_id'=>$book_id));
          		$this->db->update('promocode_used',array('status'=>'1'),array('booking_id'=>$book_id));

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

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

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

				    if(isset($template['booking_sms']) && !empty($template['booking_sms'])){
				        $msgContent = str_replace(
				        				array('{:event_name}','{:booking_id}','{:time}'),
		    						    array($bkData['event_name'],$trBook['booking_id'],$showTime),
		    						    $template['booking_sms']);
				    }
				    $this->sendSMS($bkData['phone'],$msgContent);
			    }
 			}
 			$res = array('status'=>1);
 		}catch(Exception $e){
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		}
 		return $res; 
 	}

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

 	public function save_organizer($data){
 		try{
	 		$userNameChk = $this->db->query("SELECT * FROM users 
 									     	 WHERE user_type='2' AND status!='2' AND 
 									     		   username='".$data['email_id']."'");
	 		if(!empty($userNameChk) && $userNameChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Username Already Exist','code'=>'ER07');
	 			return $res;
	 		}

	 		$emailChk = $this->db->query("SELECT * FROM provider AS PRV 
	 									  INNER JOIN users AS USR ON (USR.id=PRV.provider_id)
									      WHERE USR.user_type='2' AND USR.status!='2' AND 
									      		PRV.email='".$data['email_id']."'");
	 		if(!empty($emailChk) && $emailChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Email Id Already Exist','code'=>'ER08');
	 			return $res;
	 		}

	 		$phoneChk = $this->db->query("SELECT * FROM provider AS PRV 
	 									  INNER JOIN users AS USR ON (USR.id=PRV.provider_id)
										  WHERE USR.user_type='2' AND USR.status!='2' AND 
										  	    PRV.phone='".$data['phone']."'");
	 		if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
	 			$res = array('status'=>0,'message'=>'Phone Number Already Exist','code'=>'ER09');
	 			return $res;
	 		}
 			
			$this->db->insert('users',array('username'=>$data['email_id'],'display_name'=>$data['name'],
							  'password'=>md5($data['password']),'user_type'=>'2','status'=>'0'));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  /*================ START : Checker API ================*/

 	public function checker_login($data){
 		try{
 			$this->db->where('status',1);
	 		$this->db->where('password',md5($data['password']));
	 		$this->db->where('username',$data['email']);
	 		$this->db->from('checker');
	 		$result = $this->db->get()->row();
	 		if($result){
	 			$res = array('status'=>1,'data'=>array('checker_id'=>$result->id));
	 		} else {
	 			$res = array('status'=>0,'message'=>'Invalid Email Id / Password','code'=>'ER05');
	 		}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;	
 	}

 	function checkerbookingdetails($data) {
 		try {
 			$count = $this->db->get_where('checker',array('id'=>$data['checker_id']))->num_rows();
			if($count > 0){
				$result = $this->db
				->select('booking.id AS book_id,booking.bookId,customer.name AS customer_name,
						  booking.status,booking.no_of_ticket,booking.qrcode,
						  booking.ticket_details,event_date_time.date AS booking_date')
				->where('booking.bookId',$data['qr_pin'])
				->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', 'LEFT')
				->join('customer','customer.customer_id = booking.customer_id')
				->join('host_categories', 'venue.host_cat_id = host_categories.host_cat_id')
				->group_by('booking.bookId')->get()->row();
				if(count($result)>0){
					$result->seat_class = '';
					if(!empty($ticketDetls = json_decode($result->ticket_details))){
						if(is_array($ticketDetls) && isset($ticketDetls[0]) && isset($ticketDetls[0]->color)){
							$result->seat_class = $ticketDetls[0]->color;	
						} else if (isset($ticketDetls->color)){
							$result->seat_class = $ticketDetls->color;	
						}
					}
					$this->db->insert('checker_bookings',
								array('checker_id'=>$data['checker_id'],'booking_id'=>$data['qr_pin'],
								      'checked_time'=>date('Y-m-d H:i:s')));

					$res = array('status'=>1,'data'=>$result);
				} else {
					$res = array('status'=>0,'message'=>'Invalid booking code','code'=>'ER24');
				}
			}else{
				$res = array('status'=>0,'message'=>'Checker Doesnot Exist','code'=>'ER24');
			}		
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

 	function getCheckerBookList($data) {
 		try {
 			$checker_id = $data['checker_id'];
 			$count = $this->db->get_where('checker',array('id'=>$checker_id,'status'=>'1'))->num_rows();
			if($count > 0){
 				$sql = "SELECT BOOK.bookId AS booking_id 
					    FROM checker_bookings AS CBOOK
					    INNER JOIN checker AS CHK ON (CHK.id=$checker_id)
					    INNER JOIN booking AS BOOK ON (BOOK.bookId=CBOOK.booking_id)
					    INNER JOIN events AS EVT ON (EVT.event_id=BOOK.event_id)
					    WHERE EVT.provider_id=CHK.provider_id AND BOOK.status='1'";
					    pr($sql);
 				$count = $this->db->query($sql)->num_rows();

 				if($count > 0) {
 					$perPage = 10;
 					$page = (isset($data['page']))?$data['page']:1;
 					$limit = ($page - 1) * $perPage;
 					$meta = array('total_pages'=>ceil($count/$perPage),'total'=>$count,
								  'current_page'=>$page,'per_page'=>$perPage);
 					if($count > $limit) {

						$sql = "SELECT TEVT.event_name,TCAT.category_name,CUST.name,EDATE.date,
									   EDATE.time,BOOK.amount,BOOK.bookId AS booking_id 
							    FROM checker_bookings AS CBOOK
				    			INNER JOIN checker AS CHK ON (CHK.id=CBOOK.checker_id)
							    INNER JOIN booking AS BOOK ON (BOOK.bookId=CBOOK.booking_id)
							    INNER JOIN events AS EVT ON (EVT.event_id=BOOK.event_id AND 
					    							 		 EVT.provider_id=CHK.provider_id)
							    INNER JOIN event_date_time AS EDATE ON (EDATE.event_id=EVT.event_id)
							    INNER JOIN event_category AS CAT ON (CAT.cat_id=EVT.category_id)
							    INNER JOIN customer AS CUST ON (CUST.customer_id=BOOK.customer_id)
							    INNER JOIN translator_event AS TEVT ON (TEVT.event_id=EVT.event_id)
							    INNER JOIN translator_category AS TCAT ON (TCAT.category_id=CAT.cat_id)
							    WHERE CBOOK.checker_id='$checker_id' AND TEVT.language_code='EN' AND 
							    	  TCAT.language_code='EN' AND BOOK.status='1'";
						$result = $this->db->query($sql)->result();
						
						$resp = array('data'=>$result,'meta'=>$meta);
 						$res = array('status'=>1,'message'=>'Successfully','data'=>$resp);
					} else {
						$resp = array('data'=>[],'meta'=>$meta);
						$res = array('status'=>1,'message'=>'No More Data Found','data'=>$resp);
					}
				} else {
					$res = array('status'=>0,'message'=>'No Record Found','code'=>'ER24');
				}
			} else {
				$res = array('status'=>0,'message'=>'Checker Doesnot Exist','code'=>'ER25');
			}		
 		} catch(Exception $e) {
 			$res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}
} ?>
