<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reports extends CI_Controller {
	function __construct()   {
          parent::__construct();
          $this->load->helper('url');
         // $this->load->database();
          $this->load->model('vehicle_model');
          $this->load->model('customer_model');
          $this->load->model('drivers_model');
          $this->load->model('incomexpense_model');
          $this->load->model('fuel_model');
          $this->load->model('trips_model');
          $this->load->model('common');
          $this->load->library('session');
    }
	public function index()	{
		redirect('reports/booking');
	}
	public function booking()	{
		$data = array();
		$data['tripsData'] = array();
		
		if(isset($_POST['bookingreport'])) {
			$fromDate = strtotime($this->input->post('booking_from')) * 1000;
			$toDate = strtotime($this->input->post('booking_to')) * 1000;
			
			$triplist = $this->common->readdatafromcollectionbetween("Bookings", "bookingDate" , ">", $fromDate, "bookingDate" , "<", $toDate);
			
			if(empty($triplist)) {
				$this->session->set_flashdata('warningmessage', 'No bookings found..');
			} else {
				unset($_SESSION['warningmessage']);
				foreach ($triplist as $tripId => $tripDetails) {
					$bookingData = $tripDetails;
					
					// Get user/customer data
					if (isset($tripDetails['userId'])) {
						$customerData = $this->common->readdatadocument('Users', $tripDetails['userId']);
						if (!empty($customerData)) {
							$bookingData['userName'] = isset($customerData['userName']) ? $customerData['userName'] : 'Unknown User';
							$bookingData['userEmail'] = isset($customerData['email']) ? $customerData['email'] : '';
						}
					}
					
					// Get driver data
					if (isset($tripDetails['driverId'])) {
						$driverData = $this->common->readdatadocument('Users', $tripDetails['driverId']);
						if (!empty($driverData)) {
							$bookingData['driverName'] = isset($driverData['userName']) ? $driverData['userName'] : 'Unknown Driver';
						}
					}
					
					// Get vehicle data
					if (isset($tripDetails['vehicle']) && is_array($tripDetails['vehicle'])) {
						$bookingData['vehicleName'] = isset($tripDetails['vehicle']['name']) ? $tripDetails['vehicle']['name'] : 'Unknown Vehicle';
					}
					
					// Get pickup address
					if (isset($tripDetails['pickUp']) && is_array($tripDetails['pickUp'])) {
						$bookingData['pickupAddress'] = isset($tripDetails['pickUp']['address']) ? $tripDetails['pickUp']['address'] : 'Address not specified';
					}
					
					// Get destinations count
					if (isset($tripDetails['destinations']) && is_array($tripDetails['destinations'])) {
						$bookingData['destinationsCount'] = count($tripDetails['destinations']);
					}
					
					$data["tripsData"][$tripId]["bookingDetails"] = $bookingData;
				}
			}
		}
		
		$data['fromDate'] = isset($_POST['booking_from']) ? $_POST['booking_from'] : '';
		$data['toDate'] = isset($_POST['booking_to']) ? $_POST['booking_to'] : '';
		
		$this->template->template_render('report_booking', $data);
	}
	public function incomeexpense()	{
		$data = array();
		$triplist = array();
		$data["drivers"] = $this->drivers_model->getall_drivers()["user"];
		if(isset($_POST['incomeexpensereport'])) {
			if (isset($_POST['driverId']) && $_POST['driverId'] != "" && !empty($_POST['driverId'])) {
				$triplist = $this->common->readdatafromcollectionbetweenwhere("Bookings", "bookingDate" , ">", strtotime($this->input->post('incomeexpense_from'))*1000, "bookingDate" , "<", strtotime($this->input->post('incomeexpense_to'))*1000, "driverId" , "=", $_POST["driverId"]);
			} else {
				$triplist = $this->common->readdatafromcollectionbetweenwhere("Bookings", "bookingDate" , ">", strtotime($this->input->post('incomeexpense_from'))*1000, "bookingDate" , "<", strtotime($this->input->post('incomeexpense_to'))*1000);
			}
			if(empty($triplist)) {
				$this->session->set_flashdata('warningmessage', 'No Data found..');
			} else {
				unset($_SESSION['warningmessage']);
				foreach ($triplist as $tripId => $tripDetails) {
					$data["tripsData"][$tripId]["bookingDetails"] = $tripDetails;
				}
			}
		}
		$this->template->template_render('report_incomeexpense',$data);
	}
	public function fuels()	{
		if(isset($_POST['fuelreport'])) {
			$fuelreport = $this->fuel_model->fuel_reports($this->input->post('fuel_from'),$this->input->post('fuel_to'),$this->input->post('fuel_vechicle'));
			if(empty($fuelreport)) {
				$this->session->set_flashdata('warningmessage', 'No data found..');
				$data['fuel'] = '';
			} else {
				unset($_SESSION['warningmessage']);
				$data['fuel'] = $fuelreport;
			}
		}
		$data['vehiclelist'] = $this->vehicle_model->getall_vehicle();
		$this->template->template_render('report_fuel',$data);
	}

	/**
	 * Delivery Reports & Analytics
	 * Reports per city, per vendor, per driver, revenue, etc.
	 */
	public function delivery()
	{
		$data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
		
		// Get date range filters
		$fromDate = $this->input->get('fromDate') ? strtotime($this->input->get('fromDate')) * 1000 : strtotime('-30 days') * 1000;
		$toDate = $this->input->get('toDate') ? strtotime($this->input->get('toDate')) * 1000 : time() * 1000;
		$cityId = $this->input->get('cityId');
		
		// Get all orders
		$allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
		
		// Filter orders by date and city
		$filteredOrders = array();
		foreach ($allOrders as $orderId => $order) {
			$orderDate = isset($order['date']) ? $order['date'] : 0;
			
			if ($orderDate >= $fromDate && $orderDate <= $toDate) {
				if (!$cityId || (isset($order['cityId']) && $order['cityId'] == $cityId)) {
					$filteredOrders[$orderId] = $order;
				}
			}
		}
		
		// Calculate statistics
		$stats = array(
			'totalOrders' => count($filteredOrders),
			'totalRevenue' => 0,
			'cannabusInventoryOrders' => 0,
			'storefrontOrders' => 0,
			'multiVendorOrders' => 0,
			'ordersByCity' => array(),
			'ordersByZone' => array(),
			'ordersByStatus' => array(),
			'revenueByCity' => array()
		);
		
		foreach ($filteredOrders as $orderId => $order) {
			// Revenue
			if (isset($order['totalAmount'])) {
				$stats['totalRevenue'] += floatval($order['totalAmount']);
			}
			
			// Orders by city
			if (isset($order['cityId'])) {
				$cityName = 'Unknown';
				$city = $this->common->readdatadocument('Cities', $order['cityId']);
				if (!empty($city) && isset($city['cityName'])) {
					$cityName = $city['cityName'];
				}
				
				if (!isset($stats['ordersByCity'][$cityName])) {
					$stats['ordersByCity'][$cityName] = 0;
					$stats['revenueByCity'][$cityName] = 0;
				}
				$stats['ordersByCity'][$cityName]++;
				$stats['revenueByCity'][$cityName] += isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
			}
			
			// Orders by zone
			if (isset($order['zone'])) {
				$zone = $order['zone'];
				if (!isset($stats['ordersByZone'][$zone])) {
					$stats['ordersByZone'][$zone] = 0;
				}
				$stats['ordersByZone'][$zone]++;
			}
			
			// Orders by status
			$status = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
			if (!isset($stats['ordersByStatus'][$status])) {
				$stats['ordersByStatus'][$status] = 0;
			}
			$stats['ordersByStatus'][$status]++;
			
			// Check fulfillment type (simplified - would need vendor data)
			if (isset($order['items']) && is_array($order['items'])) {
				$vendorCount = 0;
				foreach ($order['items'] as $item) {
					if (isset($item['vendorId'])) {
						$vendorCount++;
					}
				}
				if ($vendorCount > 1) {
					$stats['multiVendorOrders']++;
				}
			}
		}
		
		$data['stats'] = $stats;
		$data['fromDate'] = date('Y-m-d', $fromDate / 1000);
		$data['toDate'] = date('Y-m-d', $toDate / 1000);
		$data['selectedCityId'] = $cityId;
		
		$this->template->template_render('report_delivery', $data);
	}
}
