<?php 

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

 	function login($data){
 		try{
 			$this->db->select("customer.name AS user_name,customer.phone,customer.email,customer.profile_image AS profile_photo,users.id AS user_id, IF(customer.phone_verified = 0,'false','true') AS is_phone_verified");
 			$this->db->where('users.status',1);
	 		$this->db->where('users.password',md5($data['password']));
	 		$this->db->where('customer.email',$data['email']);
	 		$this->db->from('users');
	 		$this->db->join('customer','customer.customer_id = users.id');
	 		$result = $this->db->get()->row();
	 		if($result){
	 			$auth_token = md5(microtime().rand());
	 			$response = array('user'=>$result,'auth_token'=>$auth_token);
	 			$this->generateAuth($result->user_id,$auth_token);
	 			$res = array('status'=>1,'data'=>$response);
	 		} else {
	 			$res = array('status'=>0,'message'=>'Invalid username / Password','code'=>'ER05');
	 		}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;	
 	}


 	function availability($data) {
 		try{
 			$is_email_available = "true";
 			$is_phone_available = "true";
 			$res_count = $this->db->where('email',$data['email'])->or_where('phone',$data['phone'])->get('customer')->result();
 			if(count($res_count) > 0) {
 				foreach ($res_count as $rs) {
 					if($rs->email == $data['email']) {
 						$is_email_available = "false";
 					}

 					if($rs->phone == $data['phone']) {
 						$is_phone_available = "false";
 					}
 				}
 			}

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

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


 	function register($data) {
 		try{
 			$res_count = $this->db->where('email',$data['email'])->or_where('phone',$data['phone'])->get('customer')->row();
 			if(count($res_count) > 0) {
 				if($res_count->email == $data['email'] && $res_count->phone == $data['phone']){
 					$res = array('status'=>0,'message'=>'Already have an account with email id and phone no. Please login','code'=>'ER12');
 				} else if($res_count->email == $data['email']){
 					$res = array('status'=>0,'message'=>'Email id already exists','code'=>'ER09');
 				} else if($res_count->phone == $data['phone']) {
 					$res = array('status'=>0,'message'=>'Phone no already exists','code'=>'ER10');
 				}
 			} else {
 				$temp_password = $data['password'];
	 			$data['password'] = md5($data['password']);

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

	 				$subject = "New account created successfully";
	 				$email_id = $data['email'];
	 				$message = "Hi,\n\r Welcome to TimeOut.\r\n Please use username: ".$email_id." and Password: ".$temp_password." for access your account";
	 				$this->send_mail($subject,$email_id,$message);
	 				$this->db->select("customer.name AS user_name,customer.phone,customer.email,customer.profile_image AS profile_photo,users.id AS user_id, IF(customer.phone_verified = 0,'false','true') AS is_phone_verified");
		 			$this->db->where('users.id',$id);
			 		$this->db->from('users');
			 		$this->db->join('customer','customer.customer_id = users.id');
			 		$result = $this->db->get()->row();
			 		if($result){
			 			$auth_token = md5(microtime().rand());
			 			$this->generateAuth($result->user_id,$auth_token);
			 			$response = array('user'=>$result,'auth_token'=>$auth_token);
			 			$res = array('status'=>1,'data'=>$response);
			 		} else {
			 			$res = array('status'=>0,'message'=>'No record found','code'=>'ER13');
			 		}
	 			} else {
	 				$res = array('status'=>0,'message'=>'Registration failed please try again','code'=>'ER11');
	 			}	 			
		 	}
 		} catch(Exception $e) {
 			 $res = array('status'=>0,'message'=>'Ohh No!! Something went South!!','code'=>'ER06');
 		} 
 		return $res;
 	}


 	function discover($data) {

 		try {
 			if($data['auth_token']) {
 				$user_id = $this->auth_token_get($data['auth_token']); 
 			} else {
 				$user_id = 0;
 			}
 			if(isset($data['cat_id'])) {
 				$where = ' AND events.category_id = '.$data['cat_id'];
 			} else {
 				$where = '';
 			}
 				$result = $this->db->query("SELECT events.event_id AS event_id, events.event_name AS name,`event_gallery`.`media_url` AS image, COUNT(booking.id) AS attendees, event_category.category, AVG(review.rate) AS rating, venue.location, IF(favourite.status = 1, 'true','false') AS is_favorite, IF(events.provider_id = 1,'true','false') AS is_editors_choice, events.avg_price AS rate FROM events INNER JOIN event_date_time ON events.event_id = event_date_time.event_id AND event_date_time.date >= DATE_FORMAT(NOW(),'%Y-%m-%d') LEFT JOIN `event_gallery` ON `events`.`event_id` = `event_gallery`.`event_id` AND `event_gallery`.`media_type` = 0 LEFT JOIN booking ON booking.event_id = events.event_id LEFT JOIN event_category ON events.category_id = event_category.cat_id LEFT JOIN review ON review.event_id = events.event_id LEFT JOIN venue ON venue.id = events.venue_id LEFT JOIN favourite ON favourite.event_id = events.event_id AND favourite.user_id = ".$user_id." AND favourite.status = 1 WHERE events.status = 1 ".$where." GROUP BY events.event_id")->result();
				if(count($result)>0){
					$resultData = array();					
					$resultData['events'] = $result;
					$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 event($data) {

 		try {
 			$user_id = $this->auth_token_get($data['auth_token']); 			
 			if($user_id > 0) {
 				$event_id = $data['event_id'];
 				$this->db->query("SET SESSION group_concat_max_len = 20000");
 				$rs = $this->db->query("SELECT events.event_id, AVG(review.rate) AS rate, MAX(booking.id) AS attendees, events.event_name,events.event_discription AS event_description,events.seat_pricing, events.custom_seat_layout, venue.layout, venue.layout_details,venue.venue_name,venue.venue_details,venue.location,venue.location_lat AS lat,venue.location_lng AS lng, GROUP_CONCAT(DISTINCT `event_gallery`.`media_url`) AS media_url,IF(favourite.status = 1,'true','false') AS fav_status, GROUP_CONCAT(DISTINCT tags.tag_name) AS tag, GROUP_CONCAT(DISTINCT CONCAT_WS('#',event_date_time.id,event_date_time.date,event_date_time.time)) AS date_time, events.max_booking FROM events INNER JOIN event_date_time ON events.event_id = event_date_time.event_id INNER JOIN venue ON venue.id = events.venue_id LEFT JOIN `event_gallery` ON `events`.`event_id` = `event_gallery`.`event_id` AND `event_gallery`.`status` != 0 LEFT JOIN booking on booking.event_id = events.event_id LEFT JOIN favourite ON favourite.event_id = events.event_id AND favourite.user_id = ".$user_id." AND favourite.status = 1 LEFT JOIN event_tags ON events.event_id = event_tags.event_id LEFT JOIN tags on tags.tag_id = event_tags.tag_id LEFT JOIN review ON events.event_id = review.event_id WHERE events.event_id = ".$event_id." GROUP BY events.event_id, event_date_time.event_id")->row();
					if(count($rs)>0){
						$resultData = array();
						$event_layout = '';
						$colorData = array();
						$booking = $this->db->where('event_id',$event_id)->select('ticket_details')->get('booking')->result();
						if(count($booking) > 0){
							foreach ($booking as $row) {
								$priceData = json_decode($row->ticket_details);
								if(count($priceData) > 0){
									foreach ($priceData as $value) {
										$colorData[$value->color] = isset($colorData[$value->color]) ? + $colorData[$value->color] + $value->no_ticket: $value->no_ticket;
									}
								}
							}
						}


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

							}

							$dates = explode(',', $rs->date_time);
							$time_spec = array();
							foreach ($dates as $rss) {
								list($id,$date,$time) = explode('#', $rss);
								$time_spec[] = array('id'=>$id, 'date'=>$date, 'time'=>$time);
							}
							
							$tags = explode(',', $rs->tag);
							$media_url = explode(',', $rs->media_url);
							
							$resData = array(
								'event_id'=>$rs->event_id,
								'name'=>$rs->event_name,
								'description'=>$rs->event_description,
								'rating'=>$rs->rate,
								'total_attendees'=>$rs->attendees,
								'layout_image'=>$rs->layout,
								'is_favorite'=>$rs->fav_status,
								'photos'=>$media_url,
								'time'=>$time_spec[0]['time'],
								'date'=>$time_spec[0]['date'],
								'date_list'=>$time_spec,
								'classes'=>$event_layouts,
								'latitude'=>$rs->lat,
								'longitude'=>$rs->lng
							);
							/*array_push($resultData, $resData);
						}*/
						$res = array('status'=>1,'data'=>$resData);
					} else {
						$res = array('status'=>0,'message'=>'No records found','code'=>'ER13');
					}
				
 			} else {
 				$res = array('status'=>0,'message'=>'Invalid user','code'=>'ER19');
 			}
 			

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

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

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

 	function send_mail($subject,$email,$message,$attach=null) {
 		$ci =& get_instance(); 
		$ci->load->library('email');
        $ci->email->initialize(array(
          'protocol' => 'smtp',
          'smtp_host' => 'smtp.sendgrid.net',
          'smtp_user' => 'adarsh@techware.in',
          'smtp_pass' => 'Golden_123',
          'smtp_port' => 587,
          'crlf' => "\r\n",
          'newline' => "\r\n"
        ));
        
        $ci->email->from('no-reply@nuvento.com', 'TimeOut');
        $ci->email->to($email);
        $ci->email->cc('epocnova@gmail.com');
        $ci->email->subject($subject);
        $ci->email->message($message);
        if($attach!=null) {
          $ci->email->attach($attach);
        }
        return $ci->email->send();
 	}
 }