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

class Trips extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->model('trips_model');
		$this->load->model('customer_model');
		$this->load->model('common');
		$this->load->model('drivers_model');
		$this->load->model('vehicle_model');
		$this->load->helper(array('form', 'url', 'string'));
		$this->load->library('form_validation');
		$this->load->library('session');
	}



	public function emergecy()
	{
		$data['customerlist'] = $this->customer_model->getall_emergency();
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		//	exit;
		$this->template->template_render('emergecy', $data);
	}
	public function deleteSchudele($id)
	{
		$response = $this->common->deletedatamodel("ScheduledRides", $id);
		$this->session->set_flashdata('successmessage', 'Notification Deleted');
		redirect('trips/schtrips');
	}
	public function deleteEmergency($id)
	{
		$response = $this->common->deletedatamodel("Emergency", $id);
		$this->session->set_flashdata('successmessage', 'Notification Deleted');
		redirect('trips/emergecy');
	}

	public function reademergency()
	{
		$adminstatus = array();
		$soundstatus = array();
		// $adminstatus = $this->common->readdatafromcollectionwhereclause("Emergency","adminStatus","==","0");
		// $soundstatus= $this->common->readdatafromcollectionwhereclause("Emergency","soundStatus","==","0");

		// foreach($soundstatus as $sk=>$val){
		// 	$l['soundStatus']="1";
		// 	$this->common->updatedatamodel("Emergency",$sk,$l);
		// }

		// $data['adminstatus']=count($adminstatus);
		// $data['soundStatus']=count($soundstatus);
		$data['sic'] = true;
		echo json_encode($data);
	}


	public function bookingreport()
	{
		$filter = $this->input->post('booking_from');
		redirect(base_url() . 'trips/index/' . $filter);
	}

	public function index($date = "")
	{
		if ($date == "") {
			$data['checkdate'] = date("Y-m-d");
			$date1 = date("Y-m-d 00:00:00");
			$date2 = date("Y-m-d 23:59:59");
		} else {
			$data['checkdate'] = $date;
			$date1 = date($date . " 00:00:00");
			$date2 = date($date . " 23:59:59");
		}
		$data["trips"] = $this->common->readdatafromcollectionbetween("Bookings", "bookingDate", ">", strtotime($date1) * 1000, "bookingDate", "<", strtotime($date2) * 1000);

		//		$data = $this->trips_model->getall_trips();
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		$data["tripsData"] = array();
		foreach ($data["trips"] as $tripId => $tripDetails) {
			$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
			$customerData = "";
			if (isset($tripDetails["userId"])) {
				$customerData = $this->customer_model->get_customerdetails($tripDetails["userId"]);
			}

			//$driverData = $this->customer_model->get_customerdetails($tripDetails["driverId"]);
			//$vehicleData = $this->vehicle_model->get_vehicleByDriver($tripDetails["driverId"]);
			$data["tripsData"][$tripId]["customerDetails"] = $customerData;
			//	$data["tripsData"][$tripId]["driverDetails"] = $driverData;
			//$data["tripsData"][$tripId]["vehicleDetails"] = $vehicleData;
		}
		// array_reverse($data["tripsData"]);
		$this->template->template_render('trips_management', $data);
	}

	public function schtrips()
	{
		$data['customerlist'] = $this->customer_model->getall_sch();
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		// /	exit;

		$this->template->template_render('schtrip', $data);
	}
	public function addtrips()
	{
		$data['userslist'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "==", "user");
		$data['rides'] = $this->common->readdatafromcollectionwhereclause("Prices");

		$this->template->template_render('trips_add', $data);
	}
	public function inserttrips()
	{
		$testxss = xssclean($_POST);
		if ($testxss) {
			$response = $this->trips_model->add_trips($this->input->post());
			$bookingemail = $this->input->post('bookingemail');
			if (isset($bookingemail)) {
				$this->sendtripemail($this->input->post());
			}
			if ($response) {
				$this->session->set_flashdata('successmessage', 'New trip added successfully..');
			} else {
				$this->session->set_flashdata('warningmessage', 'Unexpected error..Try again');
			}
			redirect('trips');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('trips');
		}
	}

	public function inserttripdata()
	{
		$cURLConnection = curl_init();

		curl_setopt($cURLConnection, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . $this->input->post("pickuplat") . '%2C' . $this->input->post("pickuplng") . '&destinations=' . $this->input->post("destinationlat") . '%2C' . $this->input->post("destinationlng") . '&key=AIzaSyC16Tbzkes6aBNrdQBsIACs-UwyHrG07k4');
		curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($cURLConnection);
		curl_close($cURLConnection);

		$jsonArrayResponse = json_decode($response);
		$distance = $jsonArrayResponse->rows[0]->elements[0]->distance->text;
		$distancevalue = $jsonArrayResponse->rows[0]->elements[0]->distance->value / 1000;
		$duration = $jsonArrayResponse->rows[0]->elements[0]->duration->text;
		$durationvalue = $jsonArrayResponse->rows[0]->elements[0]->duration->value / 60;

		$car = $this->common->readdatadocument("Prices", $this->input->post('carType'));
		$data['discountPrice']=$car['finalDiscount'];		
		$price = $car['initialFee'] + ($car['pricePerKm'] * $distancevalue) + ($car['pricePerMin'] * $durationvalue);
		$data['finalDiscount'] =$price-($price*$car['finalDiscount']/100) ;
		$data['bookingDate'] = strtotime(date($this->input->post('pickupDate'))) * 1000;
		$data['carType'] = $car['carType'];
		$data['distance'] = $distance;
		$data['id'] = (string)time();
		$data['price'] = number_format(round($price), 0, '.', '');
		$data['pricesId'] = $this->input->post('carType');
		$data['rideType'] = "single";
		$data['status'] = "booked";
		$data['time'] = $duration;
		$data['userId'] = $this->input->post('userId');

		$data['tripDetail']['destinations'][0]['lat'] = (float) $this->input->post('destinationlat');
		$data['tripDetail']['destinations'][0]['lng'] = (float) $this->input->post('destinationlng');
		$data['tripDetail']['destinations'][0]['address'] = $this->input->post('destinationaddress');
		$data['tripDetail']['destinations'][0]['status'] = "0";
		$data['tripDetail']['pickUp']['lat'] = (float) $this->input->post('pickuplat');
		$data['tripDetail']['pickUp']['lng'] = (float) $this->input->post('pickuplng');
		$data['tripDetail']['pickUp']['address'] = $this->input->post('pickupaddress');
		$data['tripDetail']['pickUp']['status'] = "0";

		$this->common->adddatamodel("Bookings", $data['id'], $data);
		redirect('trips');
		// exit;
	}

	public function edittrip()
	{
		$data['customerlist'] = $this->trips_model->getall_customer();
		$data['vechiclelist'] = $this->trips_model->getall_vechicle();
		$data['driverlist'] = $this->trips_model->getall_driverlist();
		$t_id = $this->uri->segment(3);
		$data['tripdetails'] = $this->trips_model->get_tripdetails($t_id);

		$this->template->template_render('trips_add', $data);
	}

	public function updatetrips()
	{
		$testxss = xssclean($_POST);
		if ($testxss) {
			$response = $this->trips_model->update_trips($this->input->post());
			if ($response) {
				$this->session->set_flashdata('successmessage', 'New trip added successfully..');
			} else {
				$this->session->set_flashdata('warningmessage', 'Unexpected error..Try again');
			}
			redirect('trips');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Your input are not allowed.Please try again');
			redirect('trips');
		}
	}

	public function details($id)
	{
		$data["tripData"] = $this->common->readdatadocument("Bookings", $id);
		$data["customerData"] = $this->customer_model->get_customerdetails($data["tripData"]["userId"]);
		if (!empty($data["tripData"]["driverId"])) {
			$data["driverData"] = $this->customer_model->get_customerdetails($data["tripData"]["driverId"]);
			$data["vehicleData"] = $this->vehicle_model->get_vehicleByDriver($data["tripData"]["driverId"]);
		}
		$this->template->template_render('trips_details', $data);
	}

	public function scheduledDetails($id)
	{
		$data["tripData"] = $this->common->readdatadocument("ScheduledRides", $id);
		$data["customerData"] = $this->customer_model->get_customerdetails($data["tripData"]["userId"]);
		$this->template->template_render('scheduled_details', $data);
	}

	public function invoice()
	{
		$data = array();
		$b_id = $this->uri->segment(3);
		$tripdetails = $this->trips_model->get_tripdetails($b_id);
		if (isset($tripdetails[0]['t_id'])) {
			$customerdetails = $this->customer_model->get_customerdetails($tripdetails[0]['t_customer_id']);
			$driverdetails = $this->drivers_model->get_driverdetails($tripdetails[0]['t_driver']);
			$data['paymentdetails'] = $this->trips_model->get_paymentdetails($tripdetails[0]['t_id']);
			$data['tripdetails'] = $tripdetails[0];
			$data['customerdetails'] = (isset($customerdetails[0]['c_id'])) ? $customerdetails[0] : '';
			$data['driverdetails'] =  (isset($driverdetails[0]['d_id'])) ? $driverdetails[0] : '';
		}
		$this->load->view('invoice', $data);
	}
	public function trippayment()
	{
		$pyment = $this->input->post();
		$this->db->insert('trip_payments', $pyment);
		if ($this->db->insert_id()) {
			$addincome = array('ie_v_id' => $this->input->post('tp_v_id'), 'ie_date' => date('Y-m-d'), 'ie_type' => 'income', 'ie_description' => 'payment from trip and ' . $this->input->post('tp_notes'), 'ie_amount' => $this->input->post('tp_amount'), 'ie_created_date' => date('Y-m-d'));
			$this->db->insert('incomeexpense', $addincome);
			redirect('trips/details/' . $pyment['tp_trip_id']);
		} else {
			$this->session->set_flashdata('warningmessage', 'Error!. Please try again');
			redirect('trips/details/' . $pyment['tp_trip_id']);
		}
	}
	public function trippayment_delete()
	{
		$tp_id = $this->uri->segment(3);
		$response = $this->db->delete('trip_payments', array('tp_id' => $tp_id));
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Payment record deleted successfully..');
		} else {
			$this->session->set_flashdata('warningmessage', 'Unexpected error..Try again');
		}
		redirect('trips/details/' . $this->uri->segment(4));
	}
	public function addtripexpense()
	{
		$addtripexpense = $this->input->post();
		$trip_id = $addtripexpense['addtripexpense_trip_id'];
		unset($addtripexpense['addtripexpense_trip_id']);
		$response =  $this->db->insert('incomeexpense', $addtripexpense);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Expense added successfully..');
		} else {
			$this->session->set_flashdata('warningmessage', 'Unexpected error..Try again');
		}
		redirect('trips/details/' . $trip_id);
	}
	public function sendtripemail($data)
	{
		$this->load->model('email_model');
		$gettemplate = $this->db->select('*')->from('email_template')->where('et_name', 'booking')->get()->result_array();
		if (!empty($gettemplate)) {
			$emailcontent = $gettemplate[0]['et_body'];
			$value = '<b>Trip Details :</b><br><br> ' . $data['t_trip_fromlocation'] . ' <br><b>to</b><br> ' . $data['t_trip_tolocation'] . ' <br>on<br> ' . $data['t_start_date'];
			$body = str_replace('{{bookingdetails}}', $value, $emailcontent);
			$custemail = $this->db->select('*')->from('customers')->where('c_id', $data['t_customer_id'])->get()->row()->c_email;
			$email = $this->email_model->sendemail($custemail, $gettemplate[0]['et_subject'], $body);
		}
	}
	public function sendtracking()
	{
		$this->load->model('email_model');
		$custemail = urldecode($_GET['email']);
		$url = base_url() . 'triptracking/' . $_GET['trackingcode'];
		$gettemplate = $this->db->select('*')->from('email_template')->where('et_name', 'tracking')->get()->result_array();
		if (!empty($gettemplate)) {
			$emailcontent = $gettemplate[0]['et_body'];
			$body = str_replace('{{url}}', $url, $emailcontent);
			$email = $this->email_model->sendemail($custemail, $gettemplate[0]['et_subject'], $body);
			if ($email) {
				$this->session->set_flashdata('successmessage', 'Email sent successfully..');
			} else {
				$this->session->set_flashdata('warningmessage', 'Unexpected error..Try again');
			}
			redirect('trips/details/' . $_GET['t_id']);
		}
	}
}
