<?php 
class Ride_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
	}

	function getAppReason(){
		$reason = $this->db->get_where('appointment_reason', array('status'=>'1'));
		if(!empty($reason)){
			return $reason->result();
		}
		return;
	}

	function getTripType(){
		$tripType = $this->db->get_where('trip_type', array('status'=>'1'));
		if(!empty($tripType)){
			return $tripType->result();
		}
		return;
	}

	function uploadRides($insertArr = array(),$custInsrData = array()){
		if(empty($insertArr)){
			return 0;
		}
		$status = $this->db->insert_batch('transport_details',$insertArr);
		if(!empty($custInsrData)){
			foreach ($custInsrData AS $custData) {
				$this->db->insert('customers',$custData);
			}
		}
		return ($status)?1:0;
	}

	function create_ride($data = array()){
		if(empty($data)){
			return 0;
		}
		$status = $this->db->insert('transport_details',$data);
		return ($status)?1:0;
	}

	function getRideData($ride_id = '',$company_id = '',$broker_id = '',$scheduled = '',$condArr = array()){
		$cond = (!empty($ride_id))?" AND TD.transport_id = '$ride_id'":"";
		$cond .= ($broker_id != '')?" AND TD.broker_id = '$broker_id'":"";
		$cond .= (!empty($company_id))?" AND TD.company_id = '$company_id'":"";

		if($scheduled != ''){
			$cond .= " AND TD.is_scheduled = '$scheduled'";
		}

		if(!empty($condArr)){
			$cond .= implode(' ', $condArr);
		}

		$sql = "SELECT TD.*,CONCAT(DV.first_name,' ',DV.last_name) AS assigned_driver_name,BK.broker_name,
					   AR.reason,VH.vehicle_id,VH.vehicle_type,TT.trip_type,TS.trip_status
				FROM transport_details AS TD
				LEFT JOIN brokers AS BK ON (TD.broker_id = BK.broker_id)
				LEFT JOIN drivers AS DV ON (DV.driver_id = TD.assigned_driver)
				LEFT JOIN trip_type AS TT ON (TT.trip_id = TD.trip_type)
				LEFT JOIN trip_status AS TS ON (TS.trip_status_id = TD.trip_status)
				LEFT JOIN vehicle_types AS VH ON (VH.vehicle_id = TD.vehicle_type)
				LEFT JOIN appointment_reason AS AR ON (AR.reason_id = TD.reason_code)
				WHERE TD.status != '2' ".$cond."
				ORDER BY TD.transport_id DESC";
		$ride_data = $this->db->query($sql);
		if(empty($ride_data)){
			return;
		}
		return (!empty($ride_id))?$ride_data->row():$ride_data->result();
	}

 	function changeStatus($ride_id = '', $status = '0'){
 		if(empty($ride_id)){
 			return 0;
 		}
 		$status = $this->db->update('transport_details',array('status'=>$status), array('transport_id'=>$ride_id));
 		return $status;
 	}

 	function getNearByRiders($company_id = '',$ride_data = array()){
 		if(empty($company_id) || empty($ride_data)){
 			return 0;
 		}
 		$sql = "SELECT DRV.*,3956*2*ASIN(SQRT(POWER(SIN((".$ride_data['lat']."-DRV.lat_driver)*pi()/180/2),
 							 2)+COS(".$ride_data['lat']."*pi()/180)*COS(DRV.lat_driver*pi()/180)*
 						     POWER(SIN((".$ride_data['lng']."-DRV.lng_driver)*pi()/180/2),2))) AS distance
    			FROM drivers AS DRV 
    			LEFT JOIN ride_status AS RS ON (RS.ride_id = '".$ride_data['ride_id']."' AND 
    											RS.driver_id <> DRV.driver_id)
                WHERE DRV.status = '1' AND DRV.company_id = '$company_id' AND 
                	  DRV.vehicle_id = '".$ride_data['vehicle_id']."' AND 
                      DRV.lat_driver IS NOT NULL AND DRV.lng_driver IS NOT NULL 
                GROUP BY DRV.driver_id
                ORDER BY distance ASC";
        $data = $this->db->query($sql);
        if(empty($data)){
 			return 0;
 		}
 		return $data->result_array();
 	}

 	function assignRide($ride_id = '',$driver_id = '',$mode = '0'){
 		if(empty($ride_id) || empty($driver_id)){
 			return 0;
 		}
 		if($mode == 0){
 			$status = $this->db->insert('ride_status',array('ride_id'=>$ride_id,'driver_id'=>$driver_id,'status'=>'0'));
	 		if($status){
	 			$status = $this->db->update('transport_details',array('assigned_driver'=>$driver_id,'status'=>'3'),array('transport_id'=>$ride_id,'status'=>'1'));
	 			if(!$status){
	 				$this->db->delete('ride_status',array('ride_id'=>$ride_id,'driver_id'=>$driver_id));
	 			}
	 		}
 		} else {
 			$status = $this->db->update('transport_details',array('assigned_driver'=>$driver_id,'status'=>'8'),array('transport_id'=>$ride_id));
 		}
 		
 		return ($status)?1:0;
 	}

 	function changeSchuduleStatus($ride_id = '',$is_scheduled = '0'){
 		if(empty($ride_id)){
 			return;
 		}

 		$upArr = array('is_scheduled'=>$is_scheduled);
 		if($is_scheduled == 0){
 			$upArr['status'] = '0';
 			$upArr['assigned_driver'] = '0';
 			$upArr['driver_assign_status'] = NULL;

 			$this->deleteAssignedRider($ride_id);
 		}
 		$status = $this->db->update('transport_details',$upArr,array('transport_id'=>$ride_id));
 		
 		return $status;
 	}

 	function deleteAssignedRider($ride_id = ''){
 		if(empty($ride_id)){
 			return;
 		}
 		$this->db->delete('ride_status',array('ride_id'=>$ride_id));
 	}

 	function autoAssignDriver($ride_id = '', $appointment_time = '', $pickupLoc = array(),
 							  $drivers = array(), $no_driver = '0'){
 		if(empty($ride_id)){
 			return;
 		}

 		if(!empty($drivers) && !empty($appointment_time) && !empty($pickupLoc) && 
 		   isset($pickupLoc['lat']) && !$pickupLoc['lat'] == '' &&
 		   isset($pickupLoc['lng']) && !$pickupLoc['lng'] == ''){

	 		$time = date("G:i",$appointment_time);
	 		$date = date("d-m-Y",$appointment_time);

	 		$endTime = date("G:i",strtotime($time) + 60 * 60);
	 		$startTime = date("G:i",strtotime($time) - 90 * 60);

	 		$endDateTime = strtotime($date.' '.$endTime);
	 		$startDateTime = strtotime($date.' '.$startTime);

	 		$sql = "SELECT GROUP_CONCAT(TD.assigned_driver) AS assigned_drivers
	 				FROM transport_details AS TD 
	 				INNER JOIN drivers AS DRV ON (DRV.driver_id = TD.assigned_driver)
	 				WHERE TD.driver_assign_status='0' AND TD.assigned_driver<>'0' AND TD.is_scheduled='1' AND 
	 					  TD.appointment_time>$startDateTime AND TD.appointment_time<$endDateTime AND 
	 					  TD.status IN (4,5,8) AND TD.assigned_driver IN (".implode(",",$drivers).")";

		  	$prvDrivers = $this->db->query($sql);

		  	$driverCond = '';
		  	if(!empty($prvDrivers) && $prvDrivers->num_rows() > 0 && 
		  	   !empty($prvDrivers = $prvDrivers->row_array()) && isset($prvDrivers['assigned_drivers']) && 
		  	   !empty($prvDrivers['assigned_drivers'])){
		  		$prvDrivers = explode(',',$prvDrivers['assigned_drivers']);

		  		$drivers = array_diff($drivers,$prvDrivers);
		  	}

		  	if(!empty($drivers)){
		 		$sql = "SELECT DRV.driver_id,3956*2*ASIN(SQRT(POWER(SIN((".$pickupLoc['lat']."-DRV.active_loc_lat)*
	 					   pi()/180/2),2)+COS(".$pickupLoc['lat']."*pi()/180)*COS(DRV.active_loc_lat*pi()/180)*
					       POWER(SIN((".$pickupLoc['lng']."-DRV.active_loc_lng)*pi()/180/2),2))) AS distance
		 				FROM drivers AS DRV 
						WHERE DRV.status = 1 AND DRV.driver_id IN (".implode(",",$drivers).")
						ORDER BY distance 
						LIMIT 0,1";
		    	$driverData = $this->db->query($sql);

			    if(!empty($driverData) && $driverData->num_rows() > 0 && 
			       !empty($nearByDriver = $driverData->row_array())){
			    	$driver_id = $nearByDriver['driver_id'];

			    	$status = $this->db->update('transport_details',
				    							array('driver_assign_status'=>'0',
				    								  'assigned_driver'=>$driver_id,'status'=>'3'),
				    							array('transport_id'=>$ride_id));
			    	return $status;
			    }
		  	}
	  	}
	    $assignStatus = ($no_driver == '1')?'2':'1';
    	$status = $this->db->update('transport_details',
		    						array('driver_assign_status'=>$assignStatus,'status'=>'3'),
								    array('transport_id'=>$ride_id));	
	    return $status;
 	}
}
?>
