<?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 = $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;
					$message    = "<html>
									<body>
									  Hi,\n\r Welcome to TimeOut. \r\n Please Verify your E-mail for the username: ".$email_id.". User the following link verify your account ".$reset_link.".
									</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->cc('epocnova@gmail.com');
        $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;

	 			$message = "<html>
	 							<body>
	 								<p>Please use mentioned link for reset your password: ".$url."</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->select('id,name,name_ar,region_icon AS image')->where('status',1)->get('region')->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 category() {
 		try {
 			$rs = $this->db->select('cat_id,category,category_ar,category_description,
 									 category_image,category_image_ar,category_banner')
 						   ->where('status',1)->get('event_category')->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 AS locality_id,region_id,locality,locality_ar')
 						   ->get_where('locality',$cond)->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 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,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'=>$rs->event_name,
							'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) {
 				$count = $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,events.event_name_ar,events.event_discription,events.event_discription_ar,event_gallery.media_url,venue.location,event_date_time.date AS event_date,event_date_time.time AS event_time')->where('customer_id',$user_id)->where_in('booking.status',array(0,1,2))->from('booking')->join('events','booking.event_id = events.event_id')->join('event_date_time','booking.event_date_id = event_date_time.id')->join('venue', 'venue.id = events.venue_id')->join('event_gallery', 'events.event_id = event_gallery.event_id AND event_gallery.media_type = 0', 'LEFT')->group_by('booking.id')->get()->num_rows();
 				
 				if($count > 0) {

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

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

 					if($count > $page_limit) {
 						$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,events.event_name_ar,events.event_discription,events.event_discription_ar,event_gallery.media_url,venue.location,event_date_time.date AS event_date,event_date_time.time AS event_time')->where('customer_id',$user_id)->where_in('booking.status',array(0,1,2))->from('booking')->join('events','booking.event_id = events.event_id')->join('event_date_time','booking.event_date_id = event_date_time.id')->join('venue', 'venue.id = events.venue_id')->join('event_gallery', 'events.event_id = event_gallery.event_id AND event_gallery.media_type = 0', 'LEFT')->group_by('booking.id')->order_by('booking.id','DESC')->limit($per_page,$page_limit)->get()->result();

 						$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,events.event_discription,event_gallery.media_url,venue.location,customer.name AS customer_name,customer.profile_image,venue.venue_name,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) {
 					// $rs = $this->db->where('bookId',$data['bookingCode'])->update('booking',array('status'=>1));
 					// if($rs) {
 						$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,events.event_name_ar,events.event_discription,event_gallery.media_url,venue.location,customer.name AS customer_name,customer.profile_image,venue.venue_name,venue.venue_name_ar,venue.location_lat AS lat,venue.location_lng AS lng, booking.ticket_details,event_date_time.date,event_date_time.time')->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', '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'=>'Confirm submission failed','code'=>'ER26');
 					// }
 				} 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;	
 	}

 	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']);
		 		$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']);
		 		}
		 		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'=>'ER31');	
					}
		 		} 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.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'=>'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';
 				unset($post_data['auth_token'],$post_data['has_payment']);
 				$post_data['customer_id'] = $user_id;
 				$post_data['ticket_details'] = json_encode($post_data['ticket_details']);
 				$post_data['status'] = $status;
 				$code = 'TO';
				$ymd = date('ymd');
				$squence = rand(1111,9999);
				$squence = str_pad($squence,4,0,STR_PAD_LEFT);
				$post_data['bookId'] = $code.$ymd.$squence;
				$post_data['qrcode'] = genQRcode($post_data['bookId']);
				$post_data['booking_date'] = date('Y-m-d H:i:s');
				$rs = $this->db->insert('booking', $post_data);
				if($rs){
		 			$res = array('status'=>1,
		 						 'data'=>array('user_id'=>$user_id,
		 						 			   'bookingCode'=>$post_data['bookId']));
		 		} else {
		 			$res = array('status'=>0,'message'=>'Seat booking failed','code'=>'ER37');
		 		}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
 			} 			
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

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

 	function 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']."'";
 			}
 			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");
 						$result = $this->db->query("SELECT events.event_id, events.event_name,events.event_name_ar,events.event_discription AS event_description,venue.location,venue.venue_name, events.event_discription_ar,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,`event_gallery`.`media_url`,favourite.status AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag,GROUP_CONCAT(DISTINCT tags.tag_name_ar) AS tag_ar,  GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time
 							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 
 							LEFT JOIN tags on tags.tag_id = event_tags.tag_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();

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

								$tags = !empty($rs->tag) ? explode(',', $rs->tag) : '';
								$tags_ar = !empty($rs->tag_ar) ? explode(',', $rs->tag_ar) : '';
								$resData = array(
									'event_name'=>$rs->event_name,
									'event_name_ar'=>$rs->event_name_ar,
									'event_description'=>$rs->event_description,
									'event_description_ar'=>$rs->event_discription_ar,
									'venue_name'=>$rs->venue_name,
									'venue_location'=>$rs->location,
									'media_url'=>$rs->media_url,
									'fav_status'=>$rs->fav_status,
									'price'=>$price,
									'event_id'=>$rs->event_id,
									'attendees'=>$atte,
									'rate'=>$rate,
									'tag'=>$tags,
									'tag_ar'=>$tags_ar
								);
								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");
			$result = $this->db->query("SELECT events.event_id, events.event_name,events.event_name_ar,events.event_discription AS event_description,events.event_discription_ar,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,`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 event_date_time ON events.event_id = event_date_time.event_id AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d') 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 WHERE events.status = 1 AND events.category_id = ".$cat_id." AND venue.region_id = ".$city_id." GROUP BY events.event_id")->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 = array(
						'event_name'=>$rs->event_name,
						'event_name_ar'=>$rs->event_name_ar,
						'event_description'=>$rs->event_description,
						'event_description_ar'=>$rs->event_discription_ar,
						'media_url'=>$rs->media_url,
						'price'=>$price,
						'event_id'=>$rs->event_id
					);
					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;
 			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");
			$result = $this->db->query("SELECT events.has_payment,events.event_id,events.event_name,
				events.event_name_ar,events.event_discription AS event_description,events.event_discription_ar,events.seat_pricing, events.custom_seat_layout, events.seat_pricing, venue.layout, venue.layout_details,venue.venue_name,venue.venue_name_ar,venue.venue_details,venue.location,venue.location_lat AS lat,venue.location_lng AS lng, GROUP_CONCAT(DISTINCT `event_gallery`.`media_url`) AS media_url,favourite.status AS fav_status, events.max_booking, host_categories.show_layout, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag, GROUP_CONCAT(DISTINCT tags.tag_name_ar) AS tag_ar, GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time 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.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 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();

			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]);
						}
					}
					$tags = !empty($rs->tag) ? explode(',', $rs->tag): '';
					$tags_ar = !empty($rs->tag_ar) ? explode(',', $rs->tag_ar) : '';
					$media_url = explode(',', $rs->media_url);
					
					$resData = array(
						'latlng' => $latlng,
						'event_id' => $rs->event_id,
						'event_rate' => $rate,
						'event_name' => $rs->event_name,
						'event_name_ar' => $rs->event_name_ar,
						'event_tags' => $tags,
						'event_tags_ar' => $tags_ar,
						'event_urls' => $media_url,
						'fav_status' => $rs->fav_status,
						'venue_name' => $rs->venue_name,
						'venue_name_ar' => $rs->venue_name_ar,
						'event_price' => $price,
						'has_payment' => $rs->has_payment,
						'event_times' => $time_spec,
						'max_booking' => $rs->max_booking-$bookedCount,
						'show_layout' => $rs->show_layout,
						'seat_pricing' => $rs->seat_pricing,
						'venue_details' => $rs->venue_details,
						'venue_location' => $rs->location,
						'event_attendees' => $atte,
						'event_layout_url' => $rs->layout,
						'event_description' => $rs->event_description,
						'event_description_ar' => $rs->event_discription_ar,
						'event_price_layout' => $event_layout
					);
					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;
 			$user_id = (!isset($data['auth_token']) || empty($data['auth_token']))?'':$this->auth_token_get($data['auth_token']); 			
 			//if($user_id > 0) {
 				$where = '';

 				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;
 						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;
 					}
 					// $where = ' AND events.venue_id='.$data['venue_id'];
 				}

 				$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,events.event_name,venue.venue_name,venue.location, events.event_name_ar,events.event_discription AS event_description,events.event_discription_ar,events.seat_pricing,
 							    events.custom_seat_layout, venue.layout, venue.layout_details,
 							    event_gallery.media_url,favourite.status AS fav_status,
 							    GROUP_CONCAT(DISTINCT tags.tag_name) AS tag,
 							    GROUP_CONCAT(DISTINCT tags.tag_name_ar) AS tag_ar, 
 							    GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time 
 							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 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 
 							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'];
							}

							$tags = !empty($rs->tag)? explode(',', $rs->tag) : '';
							$tags_ar = !empty($rs->tag_ar)? explode(',', $rs->tag_ar) : '';
							$resData = array(
								'event_name'=>$rs->event_name,
								'event_name_ar'=>$rs->event_name_ar,
								'event_description'=>$rs->event_description,
								'event_description_ar'=>$rs->event_discription_ar,
								'venue_name'=>$rs->venue_name,
								'venue_location'=>$rs->location,
								'media_url'=>$rs->media_url,
								'fav_status'=>$rs->fav_status,
								'price'=>$price,
								'event_id'=>$rs->event_id,
								'attendees'=>$atte,
								'rate'=>$rate,
								'tag'=>$tags,
								'tag_ar'=>$tags_ar
							);
							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 searchEvent($data) {
 		$str = urldecode(strtolower($data['str']));

 		$event = $this->db->select('event_name,event_id')->from('events')
 						  ->where("event_name LIKE '%$str%'")->where('status',1)->limit(5)->get();
 		$region = $this->db->select('id,name')->from('region')->where("name LIKE '%$str%'")
 		                   ->where('status',1)->limit(5)->get();
 		$response = array('events'=>$event->result(), 'cityList'=>$region->result());
 		$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{
 			$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();

          		$this->db->update('booking',array('status'=>'1'),
          									array('bookId'=>$trBook['booking_id']));
 			}
 			$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{
 			$cms = $this->db->get('privacy_policy')->row_array();
 			if($cms){
 				$language['ar'] = array(
 										'faq'=>$cms['faq_ar'],
 										'instruction'=>$cms['instruction_ar'],
 										'privacy_policy'=>$cms['privacy_policy_ar'],
 										'terms_and_conditions'=>$cms['terms_and_conditions_ar']);
 				$language['en'] = array(
 										'faq'=>$cms['faq_en'],
 										'instruction'=>$cms['instruction_en'],
 										'privacy_policy'=>$cms['privacy_policy_en'],
 										'terms_and_conditions'=>$cms['terms_and_conditions_en']);
 				$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 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;
 	}

	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 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)){
				$cust = $cust->row_array();
				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;
	}
 }
?>
