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

class Vendors extends CI_Controller
{

	function __construct()
	{
		parent::__construct();
		//$this->load->database();
		$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()
	{
		$vendorlist = $this->drivers_model->getall_vendor();
		
		// Apply filters
		$filterCity = $this->input->get('filter_city');
		$filterFulfillment = $this->input->get('filter_fulfillment');
		$filterStatus = $this->input->get('filter_status');
		
		// Filter vendors
		if ($filterCity) {
			$filtered = array();
			foreach ($vendorlist as $vendorId => $vendor) {
				if (isset($vendor['cityId']) && $vendor['cityId'] == $filterCity) {
					$filtered[$vendorId] = $vendor;
				}
			}
			$vendorlist = $filtered;
		}
		
		if ($filterFulfillment) {
			$filtered = array();
			foreach ($vendorlist as $vendorId => $vendor) {
				$fulfillmentType = isset($vendor['fulfillment_type']) ? $vendor['fulfillment_type'] : 'storefront_pickup';
				if ($fulfillmentType == $filterFulfillment) {
					$filtered[$vendorId] = $vendor;
				}
			}
			$vendorlist = $filtered;
		}
		
		if ($filterStatus) {
			$filtered = array();
			foreach ($vendorlist as $vendorId => $vendor) {
				$isApproved = isset($vendor['isApproved']) ? $vendor['isApproved'] : false;
				$isActive = isset($vendor['isActive']) ? $vendor['isActive'] : true;
				
				if ($filterStatus == 'active' && $isApproved && $isActive) {
					$filtered[$vendorId] = $vendor;
				} elseif ($filterStatus == 'inactive' && $isApproved && !$isActive) {
					$filtered[$vendorId] = $vendor;
				} elseif ($filterStatus == 'pending' && !$isApproved) {
					$filtered[$vendorId] = $vendor;
				}
			}
			$vendorlist = $filtered;
		}
		
		// Enhance vendor data with city and driver info
		$data['vendorlist'] = $this->enhanceVendorData($vendorlist);
		$data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['filterCity'] = $filterCity;
		$data['filterFulfillment'] = $filterFulfillment;
		$data['filterStatus'] = $filterStatus;
		
		$this->template->template_render('vendors_management', $data);
	}
	
	public function approvedVendor()
	{
		$vendorlist = $this->drivers_model->getall_approvedvendor();
		
		// Enhance vendor data with city and driver info
		$data['vendorlist'] = $this->enhanceVendorData($vendorlist);
		$data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['filterStatus'] = 'active';
		
		$this->template->template_render('vendors_management', $data);
	}
	
	/**
	 * View vendor details
	 */
	public function viewvendor()
	{
		$vendorId = $this->uri->segment(3);
		if (!$vendorId) {
			redirect(base_url('vendors'));
			return;
		}
		
		$vendor = $this->common->readdatadocument('Users', $vendorId);
		if (empty($vendor) || !isset($vendor['userRole']) || $vendor['userRole'] != 'vendor') {
			$this->session->set_flashdata('warningmessage', 'Vendor not found');
			redirect(base_url('vendors'));
			return;
		}
		
		// Get city information
		if (isset($vendor['cityId']) && !empty($vendor['cityId'])) {
			$data['city'] = $this->common->readdatadocument('Cities', $vendor['cityId']);
		}
		
		// Get assigned drivers
		$allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
		$assignedDrivers = array();
		foreach ($allDrivers as $driverId => $driver) {
			if (isset($driver['vendorId']) && $driver['vendorId'] == $vendorId) {
				$assignedDrivers[$driverId] = $driver;
			}
		}
		$data['assignedDrivers'] = $assignedDrivers;
		
		$data['vendor'] = $vendor;
		$data['vendorId'] = $vendorId;
		
		$this->template->template_render('vendor_view', $data);
	}
	
	/**
	 * Enhance vendor data with city and driver information
	 */
	private function enhanceVendorData($vendorlist)
	{
		$enhanced = array();
		
		foreach ($vendorlist as $vendorId => $vendor) {
			$enhanced[$vendorId] = $vendor;
			
			// Get city information
			if (isset($vendor['cityId']) && !empty($vendor['cityId'])) {
				$city = $this->common->readdatadocument('Cities', $vendor['cityId']);
				$enhanced[$vendorId]['cityName'] = isset($city['cityName']) ? $city['cityName'] : 'Not Assigned';
			} else {
				$enhanced[$vendorId]['cityName'] = 'Not Assigned';
			}
			
			// Get assigned drivers count
			$allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
			$assignedDrivers = 0;
			if (!empty($allDrivers)) {
				foreach ($allDrivers as $driverId => $driver) {
					if (isset($driver['vendorId']) && $driver['vendorId'] == $vendorId) {
						$assignedDrivers++;
					}
				}
			}
			$enhanced[$vendorId]['assignedDriversCount'] = $assignedDrivers;
		}
		
		return $enhanced;
	}
	
	/**
	 * Add new vendor
	 */
	public function addvendor()
	{
		$data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
		$allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
		$data['drivers'] = $allDrivers;
		$this->template->template_render('addvendor', $data);
	}
	
	/**
	 * Insert new vendor
	 */
	public function insertvendor()
	{
		$post = $this->input->post();
		$isAjax = $this->input->is_ajax_request();
		
		// Validation
		if (empty($post['email']) || empty($post['firstName'])) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Email and First Name are required.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Email and First Name are required.');
				redirect(base_url('vendors/addvendor'));
				return;
			}
		}
		
		// Check if email already exists
		$allUsers = $this->common->readdatafromcollectionwhereclause('Users');
		foreach ($allUsers as $userId => $user) {
			if (isset($user['email']) && strtolower($user['email']) === strtolower(trim($post['email']))) {
				if ($isAjax) {
					echo json_encode(array('success' => false, 'message' => 'Email already exists.'));
					return;
				} else {
					$this->session->set_flashdata('warningmessage', 'Email already exists.');
					redirect(base_url('vendors/addvendor'));
					return;
				}
			}
		}
		
		// Get city data for HQ coordinates (if needed for Cannabus inventory)
		$cityData = null;
		if (!empty($post['cityId'])) {
			$cityData = $this->common->readdatadocument('Cities', $post['cityId']);
		}
		
		// Handle latitude/longitude - ensure proper decimal parsing
		$latitude = null;
		$longitude = null;
		$fulfillmentType = isset($post['fulfillment_type']) ? trim($post['fulfillment_type']) : 'storefront_pickup';
		
		if ($fulfillmentType == 'cannabus_inventory') {
			// For Cannabus inventory, use city HQ coordinates or leave blank
			if (!empty($cityData) && isset($cityData['hqLatitude']) && isset($cityData['hqLongitude'])) {
				$latitude = floatval($cityData['hqLatitude']);
				$longitude = floatval($cityData['hqLongitude']);
			}
			// If no HQ coordinates, leave as null (won't affect distance calculation)
		} else {
			// For storefront vendors, require real location
			if (isset($post['latitude']) && !empty(trim($post['latitude']))) {
				$latValue = trim($post['latitude']);
				// Ensure it's a valid decimal number
				if (is_numeric($latValue)) {
					$latitude = floatval($latValue);
					// Validate range
					if ($latitude < -90 || $latitude > 90) {
						$latitude = null;
					}
				}
			}
			
			if (isset($post['longitude']) && !empty(trim($post['longitude']))) {
				$lngValue = trim($post['longitude']);
				// Ensure it's a valid decimal number
				if (is_numeric($lngValue)) {
					$longitude = floatval($lngValue);
					// Validate range
					if ($longitude < -180 || $longitude > 180) {
						$longitude = null;
					}
				}
			}
		}
		
		// Prepare vendor data
		$vendorData = array(
			'userRole' => 'vendor',
			'firstName' => trim($post['firstName']),
			'lastName' => isset($post['lastName']) ? trim($post['lastName']) : '',
			'email' => trim($post['email']),
			'phoneNumber' => isset($post['phoneNumber']) ? trim($post['phoneNumber']) : '',
			'address' => isset($post['vendorAddress']) ? trim($post['vendorAddress']) : (isset($post['address']) ? trim($post['address']) : ''),
			'shopName' => isset($post['shopName']) ? trim($post['shopName']) : '',
			'cityId' => isset($post['cityId']) ? trim($post['cityId']) : '',
			'fulfillment_type' => $fulfillmentType,
			'googlePlaceId' => isset($post['googlePlaceId']) ? trim($post['googlePlaceId']) : '',
			'isApproved' => isset($post['isApproved']) ? (bool)$post['isApproved'] : false,
			'isActive' => isset($post['isActive']) ? (bool)$post['isActive'] : true,
			'assignedDriverIds' => isset($post['assignedDriverIds']) && is_array($post['assignedDriverIds']) ? $post['assignedDriverIds'] : array()
		);
		
		// Add latitude/longitude only if they have valid values
		if ($latitude !== null) {
			$vendorData['latitude'] = $latitude;
		}
		if ($longitude !== null) {
			$vendorData['longitude'] = $longitude;
		}
		
		// Handle password
		$password = '';
		if (!empty($post['password'])) {
			$password = $post['password'];
		} else {
			// Generate a default password if not provided
			$password = 'Vendor@' . rand(1000, 9999);
		}
		
		// Handle image upload
		if (isset($_FILES['imagefile']['tmp_name']) && !empty($_FILES['imagefile']['tmp_name'])) {
			$firebase = $this->firebase->init();
			$storage = $firebase->createStorage();
			$defaultBucket = $storage->getBucket();
			
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['imagefile']['tmp_name']),
				['name' => "vendorImage" . rand() . time() . $_FILES['imagefile']['name']]
			);
			
			$vendorData['image'] = $uploadedFile->info()['mediaLink'];
		}
		
		// STEP 1: Create Firebase Auth user FIRST
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		
		$userProperties = [
			'email' => trim($post['email']),
			'emailVerified' => false,
			'password' => $password,
			'displayName' => trim($post['firstName']),
			'disabled' => false,
		];
		
		try {
			// Create user in Firebase Auth
			$createdUser = $auth->createUser($userProperties);
			$vendorId = $createdUser->uid; // Get the UID from created user
			
		} catch (\Throwable $th) {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Failed to create vendor account in Firebase Auth: ' . $th->getMessage()));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Failed to create vendor account in Firebase Auth: ' . $th->getMessage());
				redirect(base_url('vendors/addvendor'));
				return;
			}
		}
		
		// STEP 2: Store vendor data in Firestore Users collection using the Auth user's UID
		$response = $this->common->adddatamodel('Users', $vendorId, $vendorData);
		
		if ($response) {
			// Update assigned drivers
			if (!empty($vendorData['assignedDriverIds'])) {
				foreach ($vendorData['assignedDriverIds'] as $driverId) {
					$driverData = array('vendorId' => $vendorId);
					$this->common->updatedatamodel('Users', $driverId, $driverData);
				}
			}
			
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Vendor added successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'Vendor added successfully.');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Something went wrong. Please try again.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try again.');
			}
		}
		
		if (!$isAjax) {
			redirect(base_url('vendors'));
		}
	}
	public function adddrivers()
	{
		$this->template->template_render('drivers_add');
	}
	public function per_kmm()
	{
		$this->template->template_render('per_km');
	}

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

	public function view_vehicle($id)
	{
		$this->data['driverdetails'] = $this->drivers_model->get_driverdetails($id);
		$this->data['vehicledetails'] = $this->vehicle_model->get_vehicleByDriver($id);
		$this->data["driverId"] = $id;
		$this->template->template_render('view_vehicle', $this->data);
	}

	public function edit_driver_info($id)
	{
		$this->data['driverdetails'] = $this->drivers_model->get_driverdetails($id);
		$this->data['vehicledetails'] = $this->vehicle_model->get_vehicleByDriver($id);
		$this->data['vehicleId'] = $this->vehicle_model->get_vehicleIdByDriver($id);
		$this->data['driverId'] = $id;
		$this->template->template_render('edit_driver', $this->data);
	}

	public function approveVendor($id)
	{
	
	
		$data["isApproved"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		$this->session->set_flashdata('successmessage', 'Vendor Approved');	
		// if($driverdetails["stripeStatus"] == "approved"){
		
		// } else {
		// 	$this->session->set_flashdata('warningmessage', 'Driver Stripe Status is not approved yet.');				
		// }
		redirect('vendors');
	}

	public function disablevendor($id)
	{
		$data["isActive"] = false;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Vendor disabled successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to disable vendor');
		}
		redirect('vendors');
	}
	
	/**
	 * Activate vendor
	 */
	public function activatevendor($id)
	{
		$data["isActive"] = true;
		$response = $this->common->updatedatamodel("Users", $id, $data);
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Vendor activated successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to activate vendor');
		}
		redirect('vendors');
	}

	public function suspendDriver($id)
	{
		$data["id"] = $id;
		$data["isVerified"] = "suspended";
		$data["isApproved"] = FALSE;
		$response = $this->common->updatedatamodel("Users", $data["id"], $data);
		$this->session->set_flashdata('successmessage', 'Driver Suspended');
		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 deletevendor($id)
	{
		$response = $this->drivers_model->delete_driver($id);
		if(!$response){
			$this->session->set_flashdata('warningmessage', 'Something went wrong while deleting auth.');
			redirect('vendors');
		}
		$response = $this->common->deletedatamodel("Users", $id);
		$this->session->set_flashdata('successmessage', 'vendors Deleted');
		redirect('vendors');
	}
	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;
			}
		}

		$data["driver"]['carType']=$this->input->post('v_carType');

		$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;
			}
		}

		$data["driver"]["userRole"] = "driver";

		$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 editvendor()
	{
		$d_id = $this->uri->segment(3);
		$data['vendorinfo'] = $this->drivers_model->get_driverdetails($d_id);
		$data['id'] = $d_id;
		$data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
		
		// Get all drivers and mark assigned ones
		$allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
		$data['drivers'] = array();
		foreach ($allDrivers as $driverId => $driver) {
			$driver['isAssigned'] = (isset($driver['vendorId']) && $driver['vendorId'] == $d_id);
			$data['drivers'][$driverId] = $driver;
		}
		
		$this->template->template_render('editvendor', $data);
	}


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

		// Handle image upload
		if (isset($_FILES['imagefile']['tmp_name']) && !empty($_FILES['imagefile']['tmp_name'])) {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['imagefile']['tmp_name']),
				['name' => "vendorImage" . rand() . time() . $_FILES['imagefile']['name']]
			);
			$post["image"] = $uploadedFile->info()['mediaLink'];
		}
		
		// Get city data for HQ coordinates (if needed for Cannabus inventory)
		$cityData = null;
		if (!empty($post['cityId'])) {
			$cityData = $this->common->readdatadocument('Cities', $post['cityId']);
		}
		
		// Handle latitude/longitude - ensure proper decimal parsing
		$latitude = null;
		$longitude = null;
		$fulfillmentType = isset($post['fulfillment_type']) ? trim($post['fulfillment_type']) : 'storefront_pickup';
		
		if ($fulfillmentType == 'cannabus_inventory') {
			// For Cannabus inventory, use city HQ coordinates or leave blank
			if (!empty($cityData) && isset($cityData['hqLatitude']) && isset($cityData['hqLongitude'])) {
				$latitude = floatval($cityData['hqLatitude']);
				$longitude = floatval($cityData['hqLongitude']);
			}
			// If no HQ coordinates, leave as null (won't affect distance calculation)
		} else {
			// For storefront vendors, require real location
			if (isset($post['latitude']) && !empty(trim($post['latitude']))) {
				$latValue = trim($post['latitude']);
				// Ensure it's a valid decimal number
				if (is_numeric($latValue)) {
					$latitude = floatval($latValue);
					// Validate range
					if ($latitude < -90 || $latitude > 90) {
						$latitude = null;
					}
				}
			}
			
			if (isset($post['longitude']) && !empty(trim($post['longitude']))) {
				$lngValue = trim($post['longitude']);
				// Ensure it's a valid decimal number
				if (is_numeric($lngValue)) {
					$longitude = floatval($lngValue);
					// Validate range
					if ($longitude < -180 || $longitude > 180) {
						$longitude = null;
					}
				}
			}
		}
		
		// Prepare update data
		$updateData = array(
			'firstName' => isset($post['firstName']) ? trim($post['firstName']) : '',
			'lastName' => isset($post['lastName']) ? trim($post['lastName']) : '',
			'phoneNumber' => isset($post['phoneNumber']) ? trim($post['phoneNumber']) : '',
			'address' => isset($post['vendorAddress']) ? trim($post['vendorAddress']) : (isset($post['address']) ? trim($post['address']) : ''),
			'shopName' => isset($post['shopName']) ? trim($post['shopName']) : '',
			'cityId' => isset($post['cityId']) ? trim($post['cityId']) : '',
			'fulfillment_type' => $fulfillmentType,
			'googlePlaceId' => isset($post['googlePlaceId']) ? trim($post['googlePlaceId']) : '',
			'isApproved' => isset($post['isApproved']) ? (bool)$post['isApproved'] : false,
			'isActive' => isset($post['isActive']) ? (bool)$post['isActive'] : true
		);
		
		// Add latitude/longitude only if they have valid values
		if ($latitude !== null) {
			$updateData['latitude'] = $latitude;
		} else {
			// Remove latitude if null (for Cannabus inventory without HQ)
			$updateData['latitude'] = null;
		}
		if ($longitude !== null) {
			$updateData['longitude'] = $longitude;
		} else {
			// Remove longitude if null (for Cannabus inventory without HQ)
			$updateData['longitude'] = null;
		}
		
		// Handle password update
		if (isset($post['newpassword']) && !empty($post['newpassword'])) {
			$flag = $this->customer_model->update_customerpassword($id, $post['newpassword']);
			if (!$flag) {
				if ($isAjax) {
					echo json_encode(array('success' => false, 'message' => 'Error updating password.'));
					return;
				} else {
					$this->session->set_flashdata('warningmessage', 'Error updating password.');
					redirect('vendors/editvendor/' . $id);
					return;
				}
			}
		}
		
		// Update vendor data
		$response = $this->common->updatedatamodel("Users", $id, $updateData);
		
		// Handle driver assignments
		if (isset($post['assignedDriverIds']) && is_array($post['assignedDriverIds'])) {
			// Remove all existing assignments for this vendor
			$allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
			foreach ($allDrivers as $driverId => $driver) {
				if (isset($driver['vendorId']) && $driver['vendorId'] == $id) {
					$driverUpdate = array('vendorId' => '');
					$this->common->updatedatamodel('Users', $driverId, $driverUpdate);
				}
			}
			
			// Assign new drivers
			foreach ($post['assignedDriverIds'] as $driverId) {
				$driverUpdate = array('vendorId' => $id);
				$this->common->updatedatamodel('Users', $driverId, $driverUpdate);
			}
		}
		
		if ($response) {
			if ($isAjax) {
				echo json_encode(array('success' => true, 'message' => 'Vendor updated successfully!'));
				return;
			} else {
				$this->session->set_flashdata('successmessage', 'Vendor updated successfully.');
			}
		} else {
			if ($isAjax) {
				echo json_encode(array('success' => false, 'message' => 'Something went wrong. Please try again.'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Something went wrong. Please try again.');
			}
		}

		if (!$isAjax) {
			redirect('vendors/editvendor/' . $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');
		}
	}
}
