<?php 

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

 	public function login($data){
 		try{
 			$this->db->select('customer.name,customer.phone,customer.email,customer.profile_image AS image,customer.gender,users.id AS userId, customer.city');
 			$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){
	 			$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'=>'Invalid username / Password','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{
 			$res_count = $this->db->where('email',$data['email_id'])->or_where('phone',$data['phone'])->get('customer')->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 {
 				$temp_password = $data['password'];
	 			$data['password'] = md5($data['password']);

	 			$user_data = array(
	 								'password'=>$data['password'],
	 							    'display_name'=>'Customer',
	 							    'user_type'=> 3
	 							);
	 			$this->db->insert('users',$user_data);
	 			$id = $this->db->insert_id();
	 			if($id) {
	 				$customer_data = array(
	 									'customer_id'=>$id,
	 									'phone'=>$data['phone'],
	 									'email'=>$data['email_id']
	 								 );
	 				$this->db->insert('customer', $customer_data);

	 				$subject = "New account created successfully";
	 				$email_id = $data['email_id'];
	 				$message = "Hi,\n\r Welcome to TimeOut.\r\n Please use username: ".$email_id." and Password: ".$temp_password." for access your account";
	 				$this->send_mail($subject,$email_id,$message);
	 				$this->db->select('customer.name,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->auth_token = md5(microtime().rand());
			 			$this->generateAuth($result->userId,$result->auth_token);
			 			$res = array('status'=>1,'data'=>$result);
			 		} 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);
        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 = 'http://techlabz.in/client/timeout/changepassword/'.$unique_id;
	 			$message = "Please use mentioned link for reset your password: ".$url;
	 			$email = $data['email_id'];
	 			$result = $this->send_mail($subject,$email,$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')->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_description,category_image')->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() {
 		try {
 			$rs = $this->db->select('id AS locality_id,venue_id,locality')->where('status',1)->get('locality')->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')->where('customer_id',$user_id)->get('booking')->num_rows();
 				if($count > 0) {

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

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

 					if($count > $page_limit) {
 						$result = $this->db->select('booking.id AS 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')->where('customer_id',$user_id)->where('booking.status!=',3)->from('booking')->join('events','booking.event_id = events.event_id')->join('event_date_time','booking.event_date_id = event_date_time.id')->join('venue', 'venue.id = events.venue_id')->join('event_gallery', 'events.event_id = event_gallery.event_id AND event_gallery.media_type = 0', 'LEFT')->limit($per_page,$page_limit)->get()->result();
 						$meta = array('total_pages'=>ceil($count/$per_page),
 									  'total'=>$count,
 									  'current_page'=>$page,
 									  'per_page'=>$per_page
 									 );
 						$response = array('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_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'=>'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.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']);
		 		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.phone,customer.email,customer.profile_image AS image,customer.gender,users.id AS userId, customer.city');
		 			$this->db->where('users.id',$user_id);
			 		$this->db->from('users');
			 		$this->db->join('customer','customer.customer_id = users.id');
			 		$result = $this->db->get()->row();
			 		if($result){
			 			$res = array('status'=>1,'data'=>$result);
			 		} else {
			 			$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
			 		}
		 		}
		 		
		 	} else {
		 		$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
		 	} 
		} 
		catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

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

 				$post_data = $data;
 				unset($post_data['auth_token']);
 				$post_data['customer_id'] = $user_id;
 				$post_data['ticket_details'] = json_encode($post_data['ticket_details']);
 				$post_data['qrcode'] = $this->generateQR($post_data);
 				$post_data['status'] = 3;
 				$code = 'TO';
				$ymd = date('ymd');
				$squence = rand(1111,9999);
				$squence = str_pad($squence,4,0,STR_PAD_LEFT);
				$post_data['bookId'] = $code.$ymd.$squence;
				$rs = $this->db->insert('booking', $post_data);
				if($rs){
		 			$res = array('status'=>1,'data'=>array('bookingCode'=>$post_data['bookId']));
		 		} else {
		 			$res = array('status'=>0,'message'=>'Seat booking failed','code'=>'ER37');
		 		}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');	
 			} 			
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}

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

 	function recommend($data) {

 		try {
 			$per_page = 10;
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$count = $this->db->query("SELECT events.event_id 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') WHERE events.status = 1 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) {
 				$result = $this->db->query("SELECT events.event_id, AVG(review.rate) AS rate, MAX(booking.id) AS attendees, events.event_name,events.event_discription AS event_description,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,`event_gallery`.`media_url`,favourite.status AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag 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 LEFT JOIN booking on booking.event_id = events.event_id LEFT JOIN favourite ON favourite.event_id = events.event_id AND favourite.user_id = ".$user_id." AND favourite.status = 1 LEFT JOIN event_tags ON events.event_id = event_tags.event_id LEFT JOIN tags on tags.tag_id = event_tags.tag_id LEFT JOIN review ON events.event_id = review.event_id WHERE events.status = 1 GROUP BY events.event_id ORDER BY attendees DESC LIMIT ". $page_limit.", ".$per_page)->result();
					if(count($result)>0){
						$resultData = 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'];
							}

							$tags = explode(',', $rs->tag);
							$resData = array(
								'event_name'=>$rs->event_name,
								'event_description'=>$rs->event_description,
								'media_url'=>$rs->media_url,
								'fav_status'=>$rs->fav_status,
								'price'=>$price,
								'event_id'=>$rs->event_id,
								'attendees'=>$rs->attendees,
								'rate'=>$rs->rate,
								'tag'=>$tags
							);
							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 {
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$cat_id = $data['cat_id'];
 				$category = $this->db->where('cat_id',$cat_id)->get('event_category')->row();
 				$result = $this->db->query("SELECT events.event_id, events.event_name,events.event_discription AS event_description,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,`event_gallery`.`media_url` 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." GROUP BY events.event_id")->result();
				if(count($result)>0){
					$resultData = 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,
							'event_description'=>$rs->event_description,
							'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');
				}
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

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


 	function event($data) {

 		try {
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$event_id = $data['event_id'];
 				$result = $this->db->query("SELECT events.event_id, AVG(review.rate) AS rate, MAX(booking.id) AS attendees, events.event_name,events.event_discription AS event_description,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,venue.venue_name,venue.venue_details,venue.location,venue.location_lat AS lat,venue.location_lng AS lng, GROUP_CONCAT(DISTINCT `event_gallery`.`media_url`) AS media_url,favourite.status AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag, GROUP_CONCAT(DISTINCT CONCAT_WS('#',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 booking on booking.event_id = events.event_id LEFT JOIN favourite ON favourite.event_id = events.event_id AND favourite.user_id = ".$user_id." AND favourite.status = 1 LEFT JOIN event_tags ON events.event_id = event_tags.event_id LEFT JOIN tags on tags.tag_id = event_tags.tag_id LEFT JOIN review ON events.event_id = review.event_id WHERE events.event_id = ".$event_id." GROUP BY events.event_id, event_date_time.event_id")->result();
					if(count($result)>0){
						$resultData = array();
						$event_layout = '';
						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'));
									$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) {
								list($date,$time) = explode('#', $rss);
								$time_spec[$date][] = $time;
							}
							$tags = explode(',', $rs->tag);
							$media_url = explode(',', $rs->media_url);
							
							$resData = array(
								'event_id'=>$rs->event_id,
								'event_name'=>$rs->event_name,
								'event_description'=>$rs->event_description,
								'event_rate'=>$rs->rate,
								'event_attendees'=>$rs->attendees,
								'event_price'=>$price,
								'event_urls'=>$media_url,
								'event_tags'=>$tags,
								'event_layout_url'=>$rs->layout,
								'event_price_layout'=>$event_layout,
								'event_times'=>$time_spec,
								'fav_status'=>$rs->fav_status,
								'event_id'=>$rs->event_id,
								'venue_name'=>$rs->venue_name,
								'venue_details'=>$rs->venue_details,
								'venue_location'=>$rs->location,
								'latlng'=>$latlng
							);
							array_push($resultData, $resData);
						}
						$res = array('status'=>1,'data'=>$resultData);
					} else {
						$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
					}
				
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

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

 	function search($data) {
 		try {
 			$per_page = 10;
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$where = '';
 				if(isset($data['venue_id'])) {
 					$where = ' AND events.venue_id='.$data['venue_id'];
 				}

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

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

 				if(isset($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";
 						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";
 						default:
 							$case = "AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d')";
 							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($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->query("SELECT events.event_id, AVG(review.rate) AS rate, MAX(booking.id) AS attendees, events.event_name,events.event_discription AS event_description,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,`event_gallery`.`media_url`,favourite.status AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag 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 `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 LEFT JOIN review ON events.event_id = review.event_id WHERE events.status = 1 $where GROUP BY events.event_id ORDER BY attendees DESC LIMIT ". $page_limit.", ".$per_page)->result();
					if(count($result)>0){
						$resultData = 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'];
							}

							$tags = explode(',', $rs->tag);
							$resData = array(
								'event_name'=>$rs->event_name,
								'event_description'=>$rs->event_description,
								'media_url'=>$rs->media_url,
								'fav_status'=>$rs->fav_status,
								'price'=>$price,
								'event_id'=>$rs->event_id,
								'attendees'=>$rs->attendees,
								'rate'=>$rs->rate,
								'tag'=>$tags
							);
							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; 		
 	}
 	
 }
?>