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

class Drivers extends CI_Controller
{

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

	public function index()
	{
		// Get all cities for filtering
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		// Get filter parameters
		$filterCity = $this->input->get('filter_city');
		$filterStatus = $this->input->get('filter_status'); // active/inactive
		$filterAvailability = $this->input->get('filter_availability'); // online/offline
		
		// Get all drivers
		$allDrivers = $this->drivers_model->getall_drivers();
		
		// Apply filters
		$filteredDrivers = array();
		foreach ($allDrivers['user'] as $driverId => $driver) {
			// Filter by city
			if ($filterCity && (!isset($driver['cityId']) || $driver['cityId'] != $filterCity)) {
				continue;
			}
			
			// Filter by status (active/inactive)
			if ($filterStatus) {
				$isActive = isset($driver['isActive']) ? $driver['isActive'] : true;
				$isApproved = isset($driver['isApproved']) ? $driver['isApproved'] : false;
				
				if ($filterStatus == 'active' && (!($isApproved && $isActive))) {
					continue;
				}
				if ($filterStatus == 'inactive' && ($isApproved && $isActive)) {
					continue;
				}
			}
			
			// Filter by availability (online/offline)
			if ($filterAvailability) {
				$isOnline = isset($driver['isOnline']) ? $driver['isOnline'] : false;
				if ($filterAvailability == 'online' && !$isOnline) {
					continue;
				}
				if ($filterAvailability == 'offline' && $isOnline) {
					continue;
				}
			}
			
			$filteredDrivers[$driverId] = $driver;
		}
		
		// Enhance driver data with city names
		$data['driverslist'] = $this->enhanceDriverData($filteredDrivers, $allCities);
		$data['filterCity'] = $filterCity;
		$data['filterStatus'] = $filterStatus;
		$data['filterAvailability'] = $filterAvailability;
		
		$this->template->template_render('drivers/drivers_management', $data);
	}
	
	private function enhanceDriverData($drivers, $cities)
	{
		foreach ($drivers as $driverId => &$driver) {
			// Add city name
			if (isset($driver['cityId']) && isset($cities[$driver['cityId']])) {
				$driver['cityName'] = isset($cities[$driver['cityId']]['cityName']) ? $cities[$driver['cityId']]['cityName'] : 'Unknown';
			} else {
				$driver['cityName'] = 'Not Assigned';
			}
		}
		return $drivers;
	}
	
	public function approveddrivers()
	{
		// Get all cities for filtering
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		// Get filter parameters
		$filterCity = $this->input->get('filter_city');
		$filterStatus = $this->input->get('filter_status');
		$filterAvailability = $this->input->get('filter_availability');
		
		// Get approved drivers
		$allDrivers = $this->drivers_model->getallapproved_drivers();
		
		// Apply filters
		$filteredDrivers = array();
		foreach ($allDrivers as $driverId => $driver) {
			if ($filterCity && (!isset($driver['cityId']) || $driver['cityId'] != $filterCity)) {
				continue;
			}
			if ($filterStatus) {
				$isActive = isset($driver['isActive']) ? $driver['isActive'] : true;
				if ($filterStatus == 'active' && !$isActive) continue;
				if ($filterStatus == 'inactive' && $isActive) continue;
			}
			if ($filterAvailability) {
				$isOnline = isset($driver['isOnline']) ? $driver['isOnline'] : false;
				if ($filterAvailability == 'online' && !$isOnline) continue;
				if ($filterAvailability == 'offline' && $isOnline) continue;
			}
			$filteredDrivers[$driverId] = $driver;
		}
		
		$data['driverslist'] = $this->enhanceDriverData($filteredDrivers, $allCities);
		$data['filterCity'] = $filterCity;
		$data['filterStatus'] = $filterStatus;
		$data['filterAvailability'] = $filterAvailability;
		
		$this->template->template_render('drivers/drivers_management', $data);
	}
	
	public function adddrivers()
	{
		// Get all cities for assignment
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		$this->template->template_render('drivers/drivers_add', $data);
	}
	public function per_kmm()
	{
		$this->template->template_render('per_km');
	}

	public function driverratings()
	{
		$this->template->template_render('driver_ratings');
	}
	

	public function view_driver_info($id)
	{
		$this->data['driverdetails'] = $this->drivers_model->get_driverdetails($id);
		$this->data['vehicledetails'] = $this->vehicle_model->get_vehicleByDriver($id);
		$this->data["driverId"] = $id;
		
		// Get city information if assigned
		if (isset($this->data['driverdetails']['cityId'])) {
			$city = $this->common->readdatadocument("Cities", $this->data['driverdetails']['cityId']);
			$this->data['city'] = $city;
		}
		
		$this->template->template_render('view_vehicle', $this->data);
	}
	
	public function viewdriver($id)
	{
		$driver = $this->drivers_model->get_driverdetails($id);
		if (!$driver) {
			$this->session->set_flashdata('warningmessage', 'Driver not found');
			redirect('drivers');
		}
		
		$data['driver'] = $driver;
		$data['driverId'] = $id;
		
		// Get vehicle details
		$data['vehicle'] = $this->vehicle_model->get_vehicleByDriver($id);
		
		// Get city information if assigned
		if (isset($driver['cityId'])) {
			$city = $this->common->readdatadocument("Cities", $driver['cityId']);
			$data['city'] = $city;
		}
		
		$this->template->template_render('drivers/driver_view', $data);
	}

	public function edit_driver_info($id)
	{
		$this->data['driverdetails'] = $this->drivers_model->get_driverdetails($id);
		$this->data['vehicledetails'] = $this->common->readdatadocument("Vehicles", $id);
		$this->data['id'] = $id;
		
		
		// Get all cities for assignment
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$this->data['cities'] = $allCities;
	
		$this->template->template_render('drivers/edit_driver_info', $this->data);
	}

	public function approveDriver($id)
	{
		$data = array(
			"isApproved" => true,
			"isActive" => true,
			"verificationStatus" => "approved",
			"verificationDate" => time() * 1000,
			"rejectionReason" => null
		);
		$response = $this->common->updatedatamodel("Users", $id, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Driver/Rider Approved');	
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to approve driver/rider');
		}
		redirect('drivers');
	}

	public function rejectDriver($id)
	{
		$rejectionReason = $this->input->post('rejectionReason');
		if (empty($rejectionReason) && !$this->input->is_ajax_request()) {
			// If not AJAX and no reason provided, show form
			$driver = $this->common->readdatadocument('Users', $id);
			if (empty($driver)) {
				$this->session->set_flashdata('warningmessage', 'Driver/Rider not found');
				redirect('drivers');
				return;
			}
			$data['driver'] = $driver;
			$data['driverId'] = $id;
			$this->template->template_render('reject_driver', $data);
			return;
		}
		
		$data = array(
			"isApproved" => false,
			"isActive" => false,
			"verificationStatus" => "rejected",
			"verificationDate" => time() * 1000,
			"rejectionReason" => $rejectionReason ? trim($rejectionReason) : 'No reason provided'
		);
		$response = $this->common->updatedatamodel("Users", $id, $data);
		
		if ($this->input->is_ajax_request()) {
			if ($response) {
				echo json_encode(array('success' => true, 'message' => 'Driver/Rider rejected successfully'));
			} else {
				echo json_encode(array('success' => false, 'message' => 'Failed to reject driver/rider'));
			}
			return;
		}
		
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Driver/Rider Rejected');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to reject driver/rider');
		}
		redirect('drivers');
	}

	public function suspendDriver($id)
	{
		$data["isVerified"] = "suspended";
		$data["isApproved"] = FALSE;
		$data["isActive"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Driver Suspended');
		redirect('drivers');
	}
	
	public function activateDriver($id)
	{
		$data["isActive"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Driver Activated');
		redirect('drivers');
	}
	
	public function deactivateDriver($id)
	{
		$data["isActive"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Driver Deactivated');
		redirect('drivers');
	}
	
	public function setDriverOnline($id)
	{
		$data["isOnline"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array('success' => true, 'message' => 'Driver set to online'));
		} else {
			$this->session->set_flashdata('successmessage', 'Driver set to online');
			redirect('drivers');
		}
	}
	
	public function setDriverOffline($id)
	{
		$data["isOnline"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		if ($this->input->is_ajax_request()) {
			echo json_encode(array('success' => true, 'message' => 'Driver set to offline'));
		} else {
			$this->session->set_flashdata('successmessage', 'Driver set to offline');
			redirect('drivers');
		}
	}

	public function deleteDriver($id)
	{
		$response = $this->drivers_model->delete_driver($id);
		if(!$response){
			$this->session->set_flashdata('warningmessage', 'Something went wrong while deleting auth.');
			redirect('drivers');
		}
		$response = $this->common->deletedatamodel("Users", $id);
		$this->session->set_flashdata('successmessage', 'Driver Deleted');
		redirect('drivers');
	}

	public function Driveraccountinfo()
	{
		$this->template->template_render('driveraccountinformation');
	}



	public function insertdriver()
	{
		$this->form_validation->set_rules('licenseno', 'License Number', 'required|trim|is_unique[vehicles.v_registration_no]');
		$this->form_validation->set_message('is_unique', '%s is already exist');
		$this->form_validation->set_rules('name', 'Name', 'required|trim');
		$this->form_validation->set_rules('mobile', 'Mobile', 'required|trim');
		$this->form_validation->set_rules('address', 'Address', 'required|trim');
		$this->form_validation->set_rules('age', 'Age', 'required|trim');
		$this->form_validation->set_rules('licenseno', 'License Number', 'required|trim');
		$this->form_validation->set_rules('license_expdate', 'License Exp Date', 'required|trim');
		$this->form_validation->set_rules('total_exp', 'Total Experiance', 'required|trim');
		$this->form_validation->set_rules('doj', 'Date of Joining', 'required|trim');
		$testxss = xssclean($_POST);
		// print_r($_POST);
		// exit;

		foreach ($_POST as $key => $val) {
			if (strpos($key, "d_") === 0) {
				$name = substr($key, 2);
				$data["driver"][$name] = $val;
			}
		}

		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		// Handle vehicle data - only the required fields
		$data["vehicle"]['make'] = $this->input->post('v_make');
		$data["vehicle"]['model'] = $this->input->post('v_model');
		$data["vehicle"]['color'] = $this->input->post('v_color');
		$data["vehicle"]['tagNumber'] = $this->input->post('v_tagNumber');
		$data["vehicle"]['drivingLicense'] = $this->input->post('v_drivingLicense');

		// Handle driving license front image upload
		if (isset($_FILES['v_drivingFrontUrl']) && $_FILES['v_drivingFrontUrl']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_drivingFrontUrl']['tmp_name']),
				[
					'name' => "Vehicles/drivingFront_" . rand() . time() . "_" . $_FILES['v_drivingFrontUrl']['name'],
				]
			);
			$data["vehicle"]['drivingFrontUrl'] = $uploadedFile->info()['mediaLink'];
		}

		// Handle driving license back image upload
		if (isset($_FILES['v_drivingBackUrl']) && $_FILES['v_drivingBackUrl']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_drivingBackUrl']['tmp_name']),
				[
					'name' => "Vehicles/drivingBack_" . rand() . time() . "_" . $_FILES['v_drivingBackUrl']['name'],
				]
			);
			$data["vehicle"]['drivingBackUrl'] = $uploadedFile->info()['mediaLink'];
		}

		$data["driver"]["userRole"] = "driver";
		
		// Add city assignment if provided
		if ($this->input->post('cityId')) {
			$data["driver"]["cityId"] = $this->input->post('cityId');
		}
		
		// Set default status
		if (!$this->input->post('isApproved')) {
			$data["driver"]["isApproved"] = false;
		} else {
			$data["driver"]["isApproved"] = true;
			$data["driver"]["isActive"] = true;
		}
		
		// Set default online status
		$data["driver"]["isOnline"] = false;

		$response = $this->drivers_model->add_drivers($data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'New driver added successfully..');
			redirect('drivers');
		} else {
			$errormsg = 'Error! User Already Exists.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('drivers/adddrivers');
		}
	}
	public function updatevahicladata($userid)
	{
		$da = $this->input->post();
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		if ($_FILES['drivingFront']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['drivingFront']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['drivingFront']['name'],
				]
			);

			$da["drivingFrontUrl"] = $uploadedFile->info()['mediaLink'];
		}
	
		if ($_FILES['drivingBack']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['drivingBack']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['drivingBack']['name'],
				]
			);

			$da["drivingBackUrl"] = $uploadedFile->info()['mediaLink'];
		}
		
		$da["id"] = $userid;
		// Check if vehicle document exists
		$existingVehicle = $this->common->readdatadocument("Vehicles", $userid);
		
		if (empty($existingVehicle)) {
			// Document doesn't exist, create new one
			$flag = $this->common->adddatamodel("Vehicles", $userid, $da);
		} else {
			// Document exists, update it
			$flag = $this->common->updatedatamodel("Vehicles", $userid, $da);
		}

		redirect('drivers/edit_driver_info/' . $userid);
	}	

	public function updatedriverdata($id)
	{
		$da = $this->input->post();
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		if ($_FILES['imagefile']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['imagefile']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['imagefile']['name'],
				]
			);

			$da["image"] = $uploadedFile->info()['mediaLink'];
		}
		
		// Handle city assignment
		if ($this->input->post('cityId')) {
			$da["cityId"] = $this->input->post('cityId');
		}
		
		// Handle status fields
		if ($this->input->post('isApproved') !== null) {
			$da["isApproved"] = $this->input->post('isApproved') == '1' ? true : false;
		}
		if ($this->input->post('isActive') !== null) {
			$da["isActive"] = $this->input->post('isActive') == '1' ? true : false;
		}
		if ($this->input->post('isOnline') !== null) {
			$da["isOnline"] = $this->input->post('isOnline') == '1' ? true : false;
		}
	
		if ($da['newpassword'] != "") {
			$da['password'] = $da['newpassword'];
			$da['newpassword'] = "";
			$flag = $this->customer_model->update_customerpassword($id, $da['password']);

			if ($flag) {
				$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
				$this->session->set_flashdata('successmessage', 'Driver has been updated successfully');
			} else {
				$this->session->set_flashdata('warningmessage', 'Something error Please try later');
			}
		} else {
			$data["promotions"] = $this->common->updatedatamodel("Users", $id, $da);
			$this->session->set_flashdata('successmessage', 'Driver has been updated successfully');
		}

		redirect('drivers/edit_driver_info/' . $id);
	}


	public function updatedriver()
	{
		foreach ($_POST as $key => $val) {
			if (strpos($key, "d_") === 0) {
				$name = substr($key, 2);
				$data["driver"][$name] = $val;
			}
		}
// echo "<pre>";
// print_r($this->input->post());
// echo "</pre>";
// print_r($data["driver"]);
if($data["driver"]['newpassword'] != ""){
	
	$data["driver"]['password']=$data["driver"]['newpassword'];
	$data["driver"]['newpassword']="";
	 $flag=$this->customer_model->update_customerpassword($data["driver"]['id'],$data["driver"]['password']);




	if($flag){
			
		
		
	}else{
$this->session->set_flashdata('warningmessage', 'Usome thing error Please try later');
redirect('drivers');
		//redirect('customer/editcustomer/'.$id);
	}

	
}

// echo "<pre>";
// print_r($data['driver']);
// echo "</pre>";
// exit;
		$firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

		if ($_FILES['v_proofOfInsurance']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_proofOfInsurance']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_proofOfInsurance']['name'],
				]
			);

			$data["vehicle"]['insuranceUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_proofOfRegistration']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_proofOfRegistration']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_proofOfRegistration']['name'],
				]
			);

			$data["vehicle"]['registrationUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_frontPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_frontPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_frontPicture']['name'],
				]
			);

			$data["vehicle"]['frontCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_leftPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_leftPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_leftPicture']['name'],
				]
			);

			$data["vehicle"]['leftCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_license']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_license']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_license']['name'],
				]
			);

			$data["vehicle"]['licenseUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_rightPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_rightPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_rightPicture']['name'],
				]
			);

			$data["vehicle"]['rightCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_rearPicture']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_rearPicture']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_rearPicture']['name'],
				]
			);

			$data["vehicle"]['rearCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_frontInterior']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_frontInterior']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_frontInterior']['name'],
				]
			);

			$data["vehicle"]['frontInCarUrl'] = $uploadedFile->info()['mediaLink'];
		}
		if ($_FILES['v_backInterior']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['v_backInterior']['tmp_name']),
				[
					'name' => "vehicleImage" . rand() . time() . $_FILES['v_backInterior']['name'],
				]
			);

			$data["vehicle"]['backInCarUrl'] = $uploadedFile->info()['mediaLink'];
		}

		foreach ($_POST as $key => $val) {
			if (strpos($key, "v_") === 0) {
				$name = substr($key, 2);
				$data["vehicle"][$name] = $val;
			}
		}

		$response = $this->common->updatedatamodel("Users", $data["driver"]["id"], $data["driver"]);
		$response = $this->common->updatedatamodel("Vehicle", $data["vehicle"]["id"], $data["vehicle"]);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Data Edited successfully..');
			redirect('drivers');
		} else {
			$errormsg = 'Seomething went wrong.';
			$this->session->set_flashdata('warningmessage', $errormsg);
			redirect('drivers');
		}
	}
}
