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

class Orders extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->model('trips_model');
		$this->load->model('common');
		$this->load->model('customer_model');
		$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');
		define('API_ACCESS_KEY1', 'AAAAEI7iwCQ:APA91bHaCcxS_zPq_PFeb2Ow5zI8WnWTzK-C6GXsoVkifHlTo-prD3xyr1Q8I7eVAcvMORfX7JxhhBWwSKDj9rU1BeBo9do6d5fD6YXDS-BXLBMR_IWbcgnDZCB1o73Mw-lN-nMc-3td');
	}



	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 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);

		echo json_encode($data);
	}

	//canceled
	public function canceled()
	{
		$check = ['cancelled', 'disputed'];
		$s["trips"] = $this->common->readdatafromcollectionwhereclause("Bookings", "status", "in", $check);;

		$data["tripsData"] = array();
		foreach ($s["trips"] as $tripId => $tripDetails) {
			$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
			$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;
		}
		// 	echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		$data['pageheadingtitle'] = "Canceled Bookings";
		$data['pageheadingtitlre2']="Canceled Bookings";
		$this->template->template_render('trips_management', $data);
	}

public function Rent(){
	$check = ['driverAccepted', 'rideStarted', 'booked', 'driverDriverReached'];
	$s["trips"] = $this->common->readdatafromcollectionwhereclause("RentCar", "status", "in", $check);;

	$data["tripsData"] = array();
	foreach ($s["trips"] as $tripId => $tripDetails) {
		$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
		$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;
	}
	$data['pageheadingtitle'] = "Rent Mangement";
	$this->template->template_render('rent_management', $data);
}



	public function index()
	{
	//	$check = ['driverAccepted', 'rideStarted', 'booked', 'driverDriverReached'];
		$s["trips"] = $this->common->readdatafromcollectionwhereclause("Orders");;



		$this->template->template_render('orders_management', $s);
	}
	public function completeride()
	{
		$starttime="";
		$endtime="";
		$startdate="";
		$enddate="";
		if(($this->input->get('startdate') !=NULL)){
 		$startdate=$this->input->get('startdate');	
 			$startdate=date($startdate." 00:00:00");

		}
	   if(($this->input->get('enddate') !=NULL)){
	 	$enddate=$this->input->get('enddate');	
	 	$enddate=date($enddate." 23:59:59");
	
		}
	if($startdate =="" || $enddate==""){
		$startdate=date("Y-m-d 00:00:00");
		$enddate=date("Y-m-d 23:59:59");


	}

 	 $starttime=strtotime($startdate)*1000;
  	$endtime=strtotime($enddate)*1000;



		$check = ['rideCompleted', 'rated'];
	//	$s["trips"] = $this->common->readdatafromcollectionwhereclause("Bookings", "status", "in", $check);;
//readdatafromcollectionbetween
$s["trips"] = array();

    $s["trips"] = $this->common->readdatafromcollection3whereclause("Bookings", "status", "in", $check, "bookingDate", ">=", $starttime, "bookingDate", "<=", $endtime);;
	
	

		$data["tripsData"] = array();
		foreach ($s["trips"] as $tripId => $tripDetails) {
			$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
			$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;
		}
		// 	echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		$data['pageheadingtitle'] = "Completed  Bookings " .$startdate .' - '.$enddate;
		$data['pageheadingtitlre2']="Completed  Bookings ";

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

	public function addtrips()
	{
		$data = $this->trips_model->getscheduled_trips();
		// echo "<pre>";
		// print_r($data);
		// echo "</pre>";
		$data["tripsData"] = array();
		foreach ($data["trips"] as $tripId => $tripDetails) {
			$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
			$customerData = $this->customer_model->get_customerdetails($tripDetails["userId"]);
			$data["tripsData"][$tripId]["customerDetails"] = $customerData;
		}
		$this->template->template_render('trips_add', $data);
	}
	function send_notification($token_id, $title, $body, $id, $type)
	{

		$icon = base_url('uploads/logo.png');

		$finalPostArray = array(
			'registration_ids' => $token_id,
			'notification' => array(
				'body' => $body,
				'title' => $title,
				"image" => $icon
			),
			"data" => array(
				"click_action" => "FLUTTER_NOTIFICATION_CLICK",
				"type" => $type,
				"id" => $id,
				"sound" => "default",
				"vibrate" => 1
			)
		);




		$headers = array(
			'Authorization: key=' . API_ACCESS_KEY1,
			'Content-Type: application/json'
		);
		#Send Reponse To FireBase Server	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($finalPostArray));
		$result['mystatus'] = curl_exec($ch);
		curl_close($ch);
		#Echo Result Of FireBase Server
		$result['firbasestatus'] = $fields;
		return $result;
	}
	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 edittrip()
	{
		$data['driverlist'] = $this->drivers_model->getall_drivers()['user'];
		$data['id'] = $this->uri->segment(3);
		$data['tripdetails'] = $this->common->readdatadocument("Bookings", $data['id']);
		$this->template->template_render('editTrip', $data);
	}
	public function canceltripbyadmin($id)
	{
		$token = array();
		$data["tripData"] = $this->common->readdatadocument("Bookings", $id);
		$data["customerData"] = $this->customer_model->get_customerdetails($data["tripData"]["userId"]);
		if (!empty($data["customerData"])) {
			if (isset($data["customerData"]["token"])) {
				array_push($token, $data["customerData"]["token"]);
			}
		}

		if (!empty($data["tripData"]["driverId"])) {
			$data["driverData"] = $this->customer_model->get_customerdetails($data["tripData"]["driverId"]);
			if (!empty($data["driverData"])) {
				if (isset($data["driverData"]["token"])) {
					array_push($token, $data["customerData"]["token"]);
				}
			}
		}

		$dat['notification'] = $this->send_notification($token, "Trip Cancel", "Trip has been Canceled by admin", $id, "cancelledtrip");


		$da['status'] = 'cancelled';
		$this->common->updatedatamodel("Bookings", $id, $da);
		redirect('trips');
	}


	public function markasdisputed($id){
		$da['orderStatus'] = 'dispute';
		$this->common->updatedatamodel("Orders", $id, $da);
		redirect('Orders/vieworder/'.$id);
	}
	public function updatetripdata($id)
	{
		if ($this->input->post('driverId') != "" && $this->input->post('driverId') != NULL)
			$data['driverId'] = $this->input->post('driverId');
		if ($data['driverId'] != $this->input->post('old_driver')) {
			$data['status'] = 'driverAccepted';
		}



		$data['pickupDate'] = strtotime(date($this->input->post('pickupDate'))) * 1000;
		$data['destinations']['lat'] = (float) $this->input->post('destinationlat');
		$data['destinations']['lng'] = (float) $this->input->post('destinationlng');
		$data['destinations']['address'] = $this->input->post('destinationaddress');
		$data['pickUp']['lat'] = (float) $this->input->post('pickuplat');
		$data['pickUp']['lng'] = (float) $this->input->post('pickuplng');
		$data['pickUp']['address'] = $this->input->post('pickupaddress');
		$data['carType'] = $this->input->post('carType');
		$data['driverNotes'] = $this->input->post('driverNotes');
		$distance = $this->distance($data['pickUp']['lat'], $data['pickUp']['lng'], $data['destinations']['lat'], $data['destinations']['lng'], "M");
		$data['distance'] = $distance . " mile";

		$packages = $this->common->readdatadocument("Settings", "Prices");

		if ($data['carType'] == "") {
			$data['carType'] = "iRide";
		}
		$price = round($packages[$data['carType']]['costOfVehicle'] + $packages[$data['carType']]['initialFee'] + ($packages[$data['carType']]['pricePerMile'] * $distance), 2);
		$data['price'] = number_format($price, 2, '.', '');

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


	public function vieworder($id)
	{
		$data['order_id']=$id;
		$data["orderdetail"] = $this->common->readdatadocument("Orders", $id);
		
		$this->template->template_render('orderdetail', $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']);
		}
	}

	public function distance($lat1, $lon1, $lat2, $lon2, $unit)
	{
		if (($lat1 == $lat2) && ($lon1 == $lon2)) {
			return 0;
		} else {
			$theta = $lon1 - $lon2;
			$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
			$dist = acos($dist);
			$dist = rad2deg($dist);
			$miles = $dist * 60 * 1.1515;
			$unit = strtoupper($unit);

			if ($unit == "K") {
				return ($miles * 1.609344);
			} else if ($unit == "N") {
				return ($miles * 0.8684);
			} else {
				return $miles;
			}
		}
	}
}
