<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ride extends CI_Controller {

	public function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->model('Ride_model');
		$this->load->model('Company_model');
		$this->load->model('Customer_model');
		
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}
	}

	function import_ride(){
		$this->load->model('Broker_model');
		$this->load->model('Driver_model');
		$this->load->model('Vehicle_model');
		$this->load->model('Company_model');

		$template['page'] = 'Ride/add_transport';

		$template['menu'] = "Ride Management";
		$template['sub_menu'] = "Create/Import Rides";

		$template['page_desc'] = "Create/Import Ride data";
		$template['page_title'] = "Create/Import Ride";

		$company_id = ($this->session->userdata['user_type'] != 1)?$this->session->userdata['id']:'';

		$template['trip_type'] = $this->Ride_model->getTripType();
		$template['driver_data'] = $this->Driver_model->getDriver();
		$template['broker_data'] = $this->Broker_model->getBroker('','',$company_id);
		$template['company_data'] = $this->Company_model->getCompany();
		$template['vehicle_data'] = $this->Vehicle_model->getVehicleType();
		$template['appointment_reason'] = $this->Ride_model->getAppReason();


		$this->load->view('template',$template);
	}

	function excelMapping(){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_FILES) || empty($_FILES) || !isset($_FILES['import_file']) || 
		   empty($_FILES['import_file']) || !isset($_POST) || empty($_POST) || !isset($_POST['broker_id']) || 
		   empty($_POST['broker_id']) || !isset($_POST['company_id']) || empty($_POST['company_id'])){
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/import_ride'));
		}

		$fileType = '';
		$importedFile = '';

        $this->load->library('upload');
		$config = set_upload_all_files("assets/uploads/upload_files");
		$config['file_name'] = 'importFile'.date('dmyhis').$_FILES['import_file']['name'];
        $this->upload->initialize($config);

        $fileData = explode('.',$_FILES['import_file']['name']);
        if($this->upload->do_upload('import_file') && !empty($fileData) && 
           isset($fileData[1]) && !empty($fileData[1])){
			$fileType = strtolower($fileData[1]);
            $upload_data = $this->upload->data();
            $importedFile = $config['upload_path']."/".$upload_data['file_name'];
        } else {
        	$flashMsg['message'] = $this->upload->display_errors();
        	$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/import_ride'));
        }

		$importData = '';
		switch($fileType){
			case 'csv':
				$importData = $this->getImportDataCSV($importedFile,0);
				break;
			case 'xls':
			case 'xlsx':
				$importData = $this->getImportDataExcel($importedFile,0);
				break;
		}

		if(empty($importData) || !isset($importData['status']) ||  $importData['status'] == 3 || 
		   $importData['status'] == 4 || ($importData['status'] == 1 && empty($importData['headerArr']))){
			$this->session->set_flashdata('message',$flashMsg);
		    redirect(base_url('Ride/import_ride'));
		}
		if ($importData['status'] == 2){
			$flashMsg['message'] = "Please Choose a vaild file..!";
			$this->session->set_flashdata('message',$flashMsg);
	    	redirect(base_url('Ride/import_ride'));
		}

		$template['fileType'] = $fileType;
		$template['headerArr'] = $importData['headerArr'];
		$template['broker_id'] = $_POST['broker_id'];
		$template['company_id'] = $_POST['company_id'];
		$template['import_file'] = $importedFile;

		$template['page'] = 'Ride/excel_mapping';

		$template['menu'] = "Excel Import Manager";
		$template['sub_menu'] = "Excel Field Mapping";

		$template['page_title'] = "Ride Management";
		$template['page_desc'] = "Excel Field Mapping";
		
		$this->load->view('template',$template);
	}

	function getImportDataCSV($importedFile = '', $headerRetFlag = 0, $headerOrder = array(), $data = array()){

		$header = 0;
		$insertArr = array(); 
		$headerArr = array();
		$insertData = array();
		$customerPh = array();
     	$retData = array('status'=>0);

     	if($headerRetFlag == 1 && (!isset($data['broker_id']) || !isset($data['company_id']) || 
     	   empty($data['broker_id']) || empty($data['company_id']))){
     		$retData['status'] = 0;
			return $retData;
     	}
		if (empty($importedFile) || !file_exists($importedFile) || 
			($handle=fopen($importedFile, "r")) === FALSE) {
			$retData['status'] = 2;
			return $retData;
		}
		if($headerRetFlag == 1 && empty($headerOrder)){
			$retData['status'] = 4;
			return $retData;
		}

		while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
			$colCnt = 0;
			$rowArr = array();
			$customerId = '';
			foreach($row as $col){
				if($header == 0){
					$col = str_replace(' ','_',$col);
					$col = preg_replace('/[^A-Za-z0-9\_\/]/', '', $col);
					$headerArr[] = $col;
				}else{ 
					if(isset($headerOrder[$colCnt]) && isset($headerArr[$headerOrder[$colCnt]])){
						if($headerArr[$headerOrder[$colCnt]] == 'Appointment_Date'){
							$col = date('d-m-Y',strtotime($col));
						}
						if($headerArr[$headerOrder[$colCnt]] == 'Appointment_Time'){
							$last = substr($col,-2);
							$col = str_replace($last,":".$last,$col);
							$col = (!empty($col) && $col != ':0')?date('G:i',strtotime($col)):'0:00';
						}
						$rowArr[$headerArr[$headerOrder[$colCnt]]] = $col;
					} else {
						if($headerArr[$colCnt] == 'Appointment_Date'){
							$col = date('d-m-Y',strtotime($col));
						}
						if($headerArr[$colCnt] == 'Appointment_Time'){
							$last = substr($col,-2);
							$col = str_replace($last,":".$last,$col);
							$col = (!empty($col) && $col != ':0')?date('G:i',strtotime($col)):'0:00';
						}
						$rowArr[$headerArr[$colCnt]] = $col;
					}
					$colCnt++;
				}
			}
			if(!empty($headerArr) && $headerRetFlag == 0){
				$retData['status'] = 1;
				$retData['headerArr'] = $headerArr;
				return $retData;
			}
			if($header != 0){
				if(!isset($headerOrder['0']) || !isset($headerOrder['1']) ||!isset($headerOrder['2'])|| 
				   !isset($headerOrder['4']) || !isset($headerOrder['5']) ||!isset($headerOrder['7'])|| 
				   !isset($headerOrder['8']) || !isset($headerOrder['10']) ||!isset($headerOrder['11'])|| 
				   !isset($headerOrder['12']) || !isset($headerOrder['13']) ||!isset($headerOrder['14'])|| 
				   !isset($headerOrder['22']) || !isset($headerOrder['23']) ||!isset($headerOrder['28'])){
					continue;
				}
				if(!in_array($row[$headerOrder['5']],$customerPh)){
					$customerData = $this->Customer_model->getCustomer(array('phone'=>$row[$headerOrder['5']]));
					if(empty($customerData)){
						$custData = array(
								 		   'age'=>$row[$headerOrder['4']],'phone'=>$row[$headerOrder['5']],
								 		   'last_name'=>$row[$headerOrder['1']],'status'=>'1',
								 		   'first_name'=>$row[$headerOrder['2']]
										  );
						$customerId = $this->Customer_model->createCustomer($custData,1);
						if(empty($customerId)){
							continue;
						}
					} else {
						$customerId = $customerData->customer_id;
					}
					$customerPh[$customerId] = $row[$headerOrder['5']];
				} else {
					$customerId = array_search($row[$headerOrder['5']],$customerPh);
				}
				$time = '0:00';
				if(!empty($row[$headerOrder['10']])){
					$last = substr($row[$headerOrder['10']], -2);
					$time = str_replace($last,":".$last,$row[$headerOrder['10']]);
					$time = (!empty($time))?date('G:i',strtotime($time)):'0:00';
				}
				$date_time = (!empty($row[8]))?date('d-m-Y',strtotime($row[$headerOrder['8']])).' '.$time:'';
				$tripBidStatus = (isset($headerOrder['37']) && isset($row[$headerOrder['37']]))?
												  $row[$headerOrder['37']]:'';

				$insertData = array(
								'broker_id'       => $data['broker_id'],
								'company_id'      => $data['company_id'],
								'customer_id'     => $customerId,

								'age'		  	  => $row[$headerOrder['4']],
								'phone'		  	  => $row[$headerOrder['5']],
								'trip_no'	 	  => $row[$headerOrder['7']],
								'trip_cost'	  	  => $row[$headerOrder['22']],
								'trip_type'  	  => $row[$headerOrder['14']],
								'medical_no'      => $row[$headerOrder['0']],
								'reason_code'  	  => $row[$headerOrder['11']],
								'trip_status'	  => $row[$headerOrder['12']],
								'vehicle_type'	  => $row[$headerOrder['13']],
								'patient_name'    => $row[$headerOrder['2']].' '.$row[$headerOrder['1']],
								'drop_location'	  => $row[$headerOrder['28']],
								'pickup_location' => $row[$headerOrder['23']],
								'trip_bid_status' => $tripBidStatus,
								'data'		      => json_encode($rowArr)
							);
				$insertData['appointment_time'] = strtotime($date_time);
				$insertArr[] = $insertData;
			}
			$header = 1;
		}
		fclose($handle);

		if(empty($insertArr)){
			$retData['status'] = 3;
		} else {
			$retData['status'] = 1;
			$retData['insertData'] = $insertArr;
		}
		return $retData;
	}

	function getImportDataExcel($importedFile = '', $headerRetFlag = 0, $headerOrder = array(), $data = array()){
		$header = 0;
		$insertArr = array(); 
		$headerArr = array();
		$insertData = array();
		$customerPh = array();
		$custData = array();
     	$retData = array('status'=>0);

     	if($headerRetFlag == 1 && (!isset($data['broker_id']) || !isset($data['company_id']) || 
     	   empty($data['broker_id']) || empty($data['company_id']))){
     		$retData['status'] = 0;
			return $retData;
     	}
		if (empty($importedFile) || !file_exists($importedFile)){
			$retData['status'] = 2;
			return $retData;
		}
		$reader = new SpreadsheetReader($importedFile);
		if (empty($reader) || count($reader->sheets()) < 1){
			$retData['status'] = 3;
			return $retData;
		}
		if($headerRetFlag == 1 && empty($headerOrder)){
			$retData['status'] = 4;
			return $retData;
		}

		for($i=0; $i < count($reader->sheets()); $i++){
	        $reader->ChangeSheet($i);
	        foreach ($reader as $row){
				$colCnt = 0;
				$rowArr = array();
				$customerId = '';
				foreach($row as $col){
					if($header == 0){
						$col = str_replace(' ','_',$col);
						$col = preg_replace('/[^A-Za-z0-9\_\/]/', '', $col);
						$headerArr[] = $col;
					}else{ 
						if(isset($headerOrder[$colCnt]) && isset($headerArr[$headerOrder[$colCnt]])){
							if($headerArr[$headerOrder[$colCnt]] == 'Appointment_Date'){
								$col = date('d-m-Y',strtotime($col));
							}
							if($headerArr[$headerOrder[$colCnt]] == 'Appointment_Time'){
								$last = substr($col,-2);
								$col = str_replace($last,":".$last,$col);
								$col = (!empty($col) && $col != ':0')?date('G:i',strtotime($col)):'0:00';
							}
							$rowArr[$headerArr[$headerOrder[$colCnt]]] = $col;
						} else {
							if($headerArr[$colCnt] == 'Appointment_Date'){
								$col = date('d-m-Y',strtotime($col));
							}
							if($headerArr[$colCnt] == 'Appointment_Time'){
								$last = substr($col,-2);
								$col = str_replace($last,":".$last,$col);
								$col = (!empty($col) && $col != ':0')?date('G:i',strtotime($col)):'0:00';
							}
							$rowArr[$headerArr[$colCnt]] = $col;
						}
						$colCnt++;
					}
				}
				if(!empty($headerArr) && $headerRetFlag == 0){
					$retData['status'] = 1;
					$retData['headerArr'] = $headerArr;
					return $retData;
				}
				if($header != 0){
					if(!isset($headerOrder['0'])||!isset($headerOrder['1'])||!isset($headerOrder['2'])|| 
					   !isset($headerOrder['4'])||!isset($headerOrder['5'])||!isset($headerOrder['7']) || 
					   !isset($headerOrder['8'])||!isset($headerOrder['10'])||!isset($headerOrder['11'])|| 
					   !isset($headerOrder['12'])||!isset($headerOrder['13'])||!isset($headerOrder['14'])||
					   !isset($headerOrder['22'])||!isset($headerOrder['23'])||!isset($headerOrder['28'])){
						continue;
					}
					if(!in_array($row[$headerOrder['5']],$customerPh)){
						$customerData=$this->Customer_model->getCustomer(array('phone'=>$row[$headerOrder['5']]));
						if(empty($customerData)){
							$custData = array('age'=>$row[$headerOrder['4']],
									 		  'phone'=>$row[$headerOrder['5']],
									 		  'last_name'=>$row[$headerOrder['1']],
									 		  'first_name'=>$row[$headerOrder['2']],
									 	      'status'=>'1');

							$customerId = $this->Customer_model->createCustomer($custData,1);
							if(empty($customerId)){
								continue;
							}
						} else {
							$customerId = $customerData->customer_id;
						}
						$customerPh[$customerId] = $row[$headerOrder['5']];
					} else {
						$customerId = array_search($row[$headerOrder['5']],$customerPh);
					}
					$time = '0:00';
					if(!empty($row[$headerOrder['10']])){
						$last = substr($row[$headerOrder['10']], -2);
						$time = str_replace($last,":".$last,$row[$headerOrder['10']]);
						$time = (!empty($time))?date('G:i',strtotime($time)):'0:00';
					}
					$date_time = (!empty($row[8]))?date('d-m-Y',strtotime($row[$headerOrder['8']])).' '.$time:'';
					$tripBidStatus = (isset($headerOrder['37']) && isset($row[$headerOrder['37']]))?
													  $row[$headerOrder['37']]:'';

					$insertData = array(
									'broker_id'       => $data['broker_id'],
									'company_id'      => $data['company_id'],
									'customer_id'     => $customerId,

									'age'		  	  => $row[$headerOrder['4']],
									'phone'		  	  => $row[$headerOrder['5']],
									'trip_no'	 	  => $row[$headerOrder['7']],
									'trip_cost'	  	  => $row[$headerOrder['22']],
									'trip_type'  	  => $row[$headerOrder['14']],
									'medical_no'      => $row[$headerOrder['0']],
									'reason_code'  	  => $row[$headerOrder['11']],
									'trip_status'	  => $row[$headerOrder['12']],
									'vehicle_type'	  => $row[$headerOrder['13']],
									'patient_name'    => $row[$headerOrder['2']].' '.$row[$headerOrder['1']],
									'drop_location'	  => $row[$headerOrder['28']],
									'pickup_location' => $row[$headerOrder['23']],
									'trip_bid_status' => $tripBidStatus,
									'data'		      => json_encode($rowArr)
								);
					$insertData['appointment_time'] = strtotime($date_time);
					$insertArr[] = $insertData;
				}
				$header = 1;
	     	}
		}

		if(empty($insertArr)){
			$retData['status'] = 3;
		} else {
			$retData['status'] = 1;
			$retData['insertData'] = $insertArr;
		}
		return $retData;
	}

	function import(){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST) || 
		   !isset($_POST['broker_id']) || empty($_POST['broker_id']) || 
		   !isset($_POST['file_type']) || empty($_POST['file_type']) || 
		   !isset($_POST['company_id']) || empty($_POST['company_id']) || 
		   !isset($_POST['import_file']) || empty($_POST['import_file']) ||
		   !isset($_POST['header_order']) || empty($_POST['header_order'])){
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/import_ride'));
		}
		$data = array('broker_id'=>$_POST['broker_id'],'company_id'=>$_POST['company_id']);
		switch($_POST['file_type']){
			case 'csv':
				$respStatus = $this->getImportDataCSV($_POST['import_file'],1,$_POST['header_order'],$data);
				break;
			case 'xls':
			case 'xlsx':
				$respStatus = $this->getImportDataExcel($_POST['import_file'],1,$_POST['header_order'],$data);
				break;
		}

		if(!empty($respStatus) && isset($respStatus['status']) && $respStatus['status'] != ''){
			if($respStatus['status'] == 1){
				$status = $this->Ride_model->uploadRides($respStatus['insertData']);
				if($status){
					$flashMsg['class'] = "success";
					$flashMsg['message'] = "Upload Scuccessfull";
					$this->session->set_flashdata('message',$flashMsg);

					unlink($_POST['import_file']);
				} else {
					$respStatus['status'] = '3';
				}
				unset($respStatus['insertData']);
			}
		} else {
			$respStatus['status'] = '0';
		}
		echo json_encode($respStatus);exit;
	}

	function create_ride(){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(!isset($_POST) || empty($_POST)){
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/import_ride'));
		}
		if($err == 0 && (!isset($_POST['medical_no']) || empty($_POST['medical_no']))){
			$err = 1;
			$errMsg = 'Medical Number';
		}else if($err == 0 && (!isset($_POST['age']) || empty($_POST['age']))){
			$err = 1;
			$errMsg = 'Age';
		}else if($err == 0 && (!isset($_POST['appointment_date']) || empty($_POST['appointment_date']))){
			$err = 1;
			$errMsg = 'Appointment date';
		}else if($err == 0 && (!isset($_POST['trip_cost']) || empty($_POST['trip_cost']))){
			$err = 1;
			$errMsg = 'Trip Cost';
		}else if($err == 0 && (!isset($_POST['vehicle_type']) || empty($_POST['vehicle_type']))){
			$err = 1;
			$errMsg = 'Vehicle Type';
		}else if($err == 0 && (!isset($_POST['first_name']) || empty($_POST['first_name']))){
			$err = 1;
			$errMsg = 'Name';
		}else if($err == 0 && (!isset($_POST['phone']) || empty($_POST['phone']))){
			$err = 1;
			$errMsg = 'Phone Number';
		}else if($err == 0 && (!isset($_POST['appointment_time']) || empty($_POST['appointment_time']))){
			$err = 1;
			$errMsg = 'Appointment Time';
		}else if($err == 0 && (!isset($_POST['pickup_location']) || empty($_POST['pickup_location']))){
			$err = 1;
			$errMsg = 'Pickup Location';
		}else if($err == 0 && (!isset($_POST['trip_type']) || empty($_POST['trip_type']))){
			$err = 1;
			$errMsg = 'Trip Type';
		}else if($err == 0 && (!isset($_POST['last_name']) || empty($_POST['last_name']))){
			$err = 1;
			$errMsg = 'Name';
		}else if($err == 0 && (!isset($_POST['reason_code']) || empty($_POST['reason_code']))){
			$err = 1;
			$errMsg = 'Reason';
		}else if($err == 0 && (!isset($_POST['drop_location']) || empty($_POST['drop_location']))){
			$err = 1;
			$errMsg = 'Drop Location';
		}
		if(!isset($_POST['driver_id']) || empty($_POST['driver_id'])){
			unset($_POST['driver_id']);
		}
		if($err == 1){
			$flashMsg['message'] = $errMsg." is mandatory";
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/import_ride'));
		}
		$data['Medicaid_Number'] = $_POST['medical_no'];
		$data['Members_First_Name'] = $_POST['first_name'];
		$data['Members_Last_Name'] = $_POST['last_name'];
		$data['Members_Age'] = $_POST['age'];

		$data['Drop_Location'] = $_POST['drop_location'];
		$data['Pickup_Location'] = $_POST['pickup_location'];

		$data["Appointment_Date"] = (!empty($_POST['appointment_date']))?
										date('d-m-y',strtotime($_POST['appointment_date'])):'';
		$data["Appointment_Time"] = (!empty($_POST['appointment_time']))?
										date('G:i',strtotime($_POST['appointment_time'])):'';

		$data['Vehicle_Type'] = $_POST['vehicle_type'];
		$data['Trip_Type'] = $_POST['trip_type'];
		$data['Trip_Cost'] = $_POST['trip_cost'];
		$data['Trip_Reason_Code'] = $_POST['reason_code'];

		$data['Pregnant_Flag'] = (isset($_POST['pregnant_flag']))?1:0;
		$data['Attendant_Flag'] = (isset($_POST['attendant_flag']))?1:0;
		$data['Wheelchair_Flag'] = (isset($_POST['wheelchair_flag']))?1:0;
		$data['Crutches_/_Walker_/_Cane_Flag'] = (isset($_POST['c_w_c_flag']))?1:0;

		$data['Members_Date_of_Birth'] = $data['Members_Phone_Number'] = $data['Members_Alt_Phone'] = 
		$data['Trip_Number'] = $data['Pickup_Zip_Code'] = $data['Trip_Status'] = $data['Pickup_City'] = 
		$data['Number_of_Car_Seats_Required'] = $data['Number_of_Additional_Passengers'] = 
		$data['Additional_Passengers_With_Appointments'] =  $data['Trip_Mileage'] = 
		$data['Delivery_City'] = $data['Confirmation_Number'] = $data['Copay'] =
		$data['Pickup_State'] = $data['Delivery_Zip_Code'] = $data['Delivery_Name'] = 
		$data['Trip_Status_Date'] = $data['Delivery_State'] = $data['Appointment_Day_of_Week'] = 
		$data['Delivery_Phone_Number'] = $data['Special_Needs'] = $data['Inst_\/_Directions'] = 
		$data['Return_Time'] = $data['Trip_Bid_Status'] = $data['Date_Trip_Bid_Status_Was_Changed'] = '';
		
		$_POST['patient_name'] = $_POST['first_name'].' '.$_POST['last_name'];
		$date_time = (!empty($_POST['appointment_date']))?$_POST['appointment_date']:'';
		$date_time .= (!empty($_POST['appointment_time']))?' '.$_POST['appointment_time']:'';
		$_POST['appointment_time'] = strtotime($date_time);

		//Manage Coustomer
		$customerData = $this->Customer_model->getCustomer(array('phone'=>$_POST['phone']));
		if(empty($customerData)){
			$custData = array('age'=>$_POST['age'],'phone'=>$_POST['phone'],'status'=>'1',
		 		  		  	  'first_name'=>$_POST['first_name'],'last_name'=>$_POST['last_name']);

			$_POST['customer_id'] = $this->Customer_model->createCustomer($custData,1);
			if(empty($_POST['customer_id'])){
				$this->session->set_flashdata('message',$flashMsg);
				redirect(base_url('Ride/import_ride'));
			}
		} else {
			$_POST['customer_id'] = $customerData->customer_id;
		}

		unset($_POST['first_name']);
		unset($_POST['last_name']);
		unset($_POST['c_w_c_flag']);
		unset($_POST['pregnant_flag']);
		unset($_POST['attendant_flag']);
		unset($_POST['wheelchair_flag']);
		unset($_POST['appointment_date']);
		$_POST['data'] = json_encode($data);
		$status = $this->Ride_model->create_ride($_POST);
		if($status){
			$flashMsg['class'] = "success";
			$flashMsg['message'] = "Upload Scuccessfull";
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/view_rides'));
		}
		$this->session->set_flashdata('message',$flashMsg);
		redirect(base_url('Ride/import_ride'));
	}

	function view_rides(){
		$this->load->model('Driver_model');
		$this->load->model('Broker_model');
		$template['page'] = 'Ride/view_rides';

		$template['menu'] = "Ride Management";
		$template['sub_menu'] = "View Rides";

		$template['page_desc'] = "View Rides Details";
		$template['page_title'] = "View Rides";

		$broker_id = (isset($_POST['broker_id']))?$_POST['broker_id']:'';
		$company_id = $this->session->userdata['id'];

		$company_data = '';
		if($this->session->userdata['user_type'] == 1){
			$company_id = '';
			$broker_id = (!isset($_POST['company_id']) || 
						  empty($company_id = $_POST['company_id']))?'':$broker_id;

			$company_data = $this->Company_model->getCompany();
		}
		$template['broker_id'] = $broker_id;
		$template['company_id'] = $company_id;
		
		$template['company_data'] = $company_data;
		$template['broker_data'] = (!empty($company_id))?
										  $this->Broker_model->getBroker('','',$company_id):'';
        $template['drivers_data'] = $this->Driver_model->getDriver('','1',$company_id);

		$template['ride_data'] = $this->Ride_model->getRideData('',$company_id,$broker_id);

		$this->load->view('template',$template);
	}

	function changeStatus($ride_id = '',$status = '1'){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($ride_id)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$ride_id = decode_param($ride_id);
		$status = $this->Ride_model->changeStatus($ride_id,$status);
		if(!$status){
			$this->session->set_flashdata('message',$flashMsg);
		}
		redirect(base_url('Ride/view_rides'));
	}

	function view($ride_id = ''){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($ride_id)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$ride_id = decode_param($ride_id);

		$template['page'] = 'Ride/view';

		$template['menu'] = "Ride Management";
		$template['sub_menu'] = "View Ride Details";

		$template['page_desc'] = "View Ride Details";
		$template['page_title'] = "Ride Details";

		$ride_data = $this->Ride_model->getRideData($ride_id);
		if(empty($ride_data) || !isset($ride_data->data) || empty($ride_data->data)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
        $template['data'] = $ride_data;
		$template['ride_data'] = json_decode($ride_data->data,true);
		$this->load->view('template',$template);
	}

	function assign_driver($ride_id = ''){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($ride_id) || $this->session->userdata['user_type'] == 1){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$ride_id 	= decode_param($ride_id);
		$company_id = $this->session->userdata['id'];
		$ride_data 	= $this->Ride_model->getRideData($ride_id);

		if(empty($ride_data->pickup_location)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}

	    $locData 	= file_get_contents("https://maps.google.com/maps/api/geocode/json?address=".
						urlencode($ride_data->pickup_location).
						"&sensor=false&key=".$this->session->userdata['settings']['google_api_key']);
	    $loc_data 	= json_decode($locData);

	    if(empty($loc_data)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
	    $lat = $loc_data->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
	    $lng = $loc_data->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

	    if(empty($lat) || empty($lng)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$rideArr = array('lat'=>$lat,'lng'=>$lng,'vehicle_id'=>$ride_data->vehicle_id,
						 'ride_id'=>$ride_data->transport_id,'status'=>$ride_data->status);
		$driver_list = $this->Ride_model->getNearByRiders($company_id,$rideArr);

	    if(empty($driver_list)){
	    	$flashMsg['message'] = 'No Driver Found';
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$template['page'] 			= 'Ride/assign_driver';

		$template['menu'] 			= "Ride Management";
		$template['sub_menu'] 		= "Assign Driver";

		$template['page_desc'] 		= "Assign Driver to ride";
		$template['page_title'] 	= "Assign Driver";

		$template['ride_id']		= $ride_id;
		$template['ride_data'] 		= $ride_data;
		$template['company_id'] 	= $company_id;
		$template['pickup_lat'] 	= $lat;
		$template['pickup_lng'] 	= $lng;
		$template['driver_list'] 	= $driver_list;

		$this->load->view('template',$template);
	}

	function assignRide($ride_id = '',$driver_id = '',$mode = 0){
		$flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
		if(empty($ride_id) || empty($driver_id)){
			$this->session->set_flashdata('message',$flashMsg);
        	redirect(base_url('Ride/view_rides'));
		}
		$ride_id 	= decode_param($ride_id);
		$driver_id 	= decode_param($driver_id);

		$status 	= $this->Ride_model->assignRide($ride_id,$driver_id,$mode);
		if($status){
			$flashMsg['class'] = "success";
			$flashMsg['message'] = "Driver Assigned";
			$this->session->set_flashdata('message',$flashMsg);
			redirect(base_url('Ride/view_rides'));
		}
		$this->session->set_flashdata('message',$flashMsg);
		redirect(base_url('Ride/assign_driver/'.encode_param($ride_id)));
	}

	function changeSchuduleStatus(){
		ini_set("memory_limit", "-1");
		set_time_limit(0);

		$result = array('status'=>'0');
		if(!isset($_POST) || empty($_POST) || 
		   !isset($_POST['transport_id']) || empty($_POST['transport_id']) || 
		   !isset($_POST['is_scheduled']) || $_POST['is_scheduled'] == ''){
			echo json_encode($result);exit;
		}

		$drivers = (isset($_POST['drivers']) && !empty($_POST['drivers']))?$_POST['drivers']:'';
		$ride_ids = $_POST['transport_id'];
		$no_driver = (isset($_POST['no_driver']) && $_POST['no_driver'] == '1')?'1':'0';
		$is_scheduled = ($_POST['is_scheduled'] == 1)?0:1;

		$succArr = array();
		if(is_array($ride_ids)){
			foreach ($ride_ids AS $ride_id) {
				$status = $this->changeScheduler($ride_id,$is_scheduled,$drivers,$no_driver);
				if($status == 1){
					$succArr[] = $ride_id;
				}
				$result['status'] = '1';
				$result['succArr'] = $succArr;
			}
		} else {
			$status = $this->changeScheduler($ride_ids,$is_scheduled,$drivers,$no_driver);
			if($status == 1){
				$result['status'] = '1';
				$result['succArr'] = array($ride_ids);
			}
		}
		echo json_encode($result);exit;
	}

	function changeScheduler($ride_id = '', $is_scheduled = '0', $drivers = array(), $no_driver = '0'){
		$status = '0';
		if(empty($ride_id)){
		  	return $status;
		}
		if($is_scheduled == 1){
		  	$ride_data = $this->Ride_model->getRideData($ride_id);

		  	if(empty($ride_data))
		  		return $status;
		  	$pickup_location = $ride_data->pickup_location;
		  	$appointment_time = $ride_data->appointment_time;

	    	if(empty($pickup_location) || empty($appointment_time))
	    		return $status;
	 	  	$pickupLocData = getLatLngFromLocation($pickup_location);

	        if(empty($pickupLocData))
	        	return $status;
	        $status = $this->Ride_model->autoAssignDriver($ride_id,$appointment_time,
										 array('lat'=>$pickupLocData['lat'],'lng'=>$pickupLocData['lng']),
										 $drivers,$no_driver);
			if(!$status){
				return $status;
			} 
	    }
		$status = $this->Ride_model->changeSchuduleStatus($ride_id,$is_scheduled);
		return $status;
	}

	function scheduled_rides(){
		if($this->session->userdata['user_type'] == 1){
			redirect(base_url());
		}
		$this->load->model('Broker_model');
		$template['page'] = 'Ride/scheduled_rides';

		$template['page_title'] = "Scheduled Rides";
		$template['page_desc'] = "View Scheduled Ride";

		$template['menu'] = "Ride Management";
		$template['sub_menu'] = "View Scheduled Rides";

		$condArr = array();
		if(isset($_POST) && isset($_POST['search_date']) && !empty($_POST['search_date'])){
			$srtDateTime = strtotime($_POST['search_date']);
			$endDateTime = strtotime($_POST['search_date'].' 23:59');

			$condArr[] = " AND (TD.appointment_time>'$srtDateTime' AND TD.appointment_time<'$endDateTime') ";
		}
		$company_id = ($this->session->userdata['user_type'] != 1)?$this->session->userdata['id']:'';
		$template['ride_data'] = $this->Ride_model->getRideData('',$company_id,'',1,$condArr);

		$this->load->view('template',$template);		
	}
}
?>
