<?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 booking()	{
		$data = array();
		if(isset($_POST['bookingreport'])) {
			$triplist = $this->common->readdatafromcollectionbetween("Bookings", "bookingDate" , ">", strtotime($this->input->post('booking_from'))*1000, "bookingDate" , "<", strtotime($this->input->post('booking_to'))*1000);
			// echo "<pre>";
			// print_r($triplist);
			// echo "</pre>";
			//exit;
			if(empty($triplist)) {
				$this->session->set_flashdata('warningmessage', 'No bookings found..');
			} else {
				unset($_SESSION['warningmessage']);
				foreach ($triplist 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('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);
	}

	/**
	 * Revenue & Financial Management Dashboard
	 */
	public function revenue()
	{
		// 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;
		$vendorId = $this->input->get('vendorId');
		$cityId = $this->input->get('cityId');
		
		// Get all orders
		$allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
		
		// Filter orders by date and criteria
		$filteredOrders = array();
		foreach ($allOrders as $orderId => $order) {
			$orderDate = isset($order['date']) ? $order['date'] : 0;
			$orderStatus = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
			
			// Only include completed orders for revenue
			if (!in_array($orderStatus, array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
				continue;
			}
			
			if ($orderDate >= $fromDate && $orderDate <= $toDate) {
				// Filter by vendor if specified
				if ($vendorId && isset($order['items']) && is_array($order['items'])) {
					$hasVendor = false;
					foreach ($order['items'] as $item) {
						if (isset($item['vendorId']) && $item['vendorId'] == $vendorId) {
							$hasVendor = true;
							break;
						}
					}
					if (!$hasVendor) {
						continue;
					}
				}
				
				// Filter by city if specified
				if ($cityId && (!isset($order['cityId']) || $order['cityId'] != $cityId)) {
					continue;
				}
				
				$filteredOrders[$orderId] = $order;
			}
		}
		
		// Calculate financial statistics
		$financials = array(
			'totalRevenue' => 0,
			'platformCommission' => 0,
			'vendorEarnings' => 0,
			'riderPayouts' => 0,
			'refundsIssued' => 0,
			'paymentProcessingFees' => 0,
			'netRevenue' => 0,
			'ordersCount' => count($filteredOrders),
			'revenueByVendor' => array(),
			'revenueByCategory' => array(),
			'revenueByDay' => array(),
			'commissionRate' => 0.10 // 10% commission, adjust as needed
		);
		
		foreach ($filteredOrders as $orderId => $order) {
			$orderAmount = isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
			$financials['totalRevenue'] += $orderAmount;
			
			// Calculate commission (assuming 10%)
			$commission = $orderAmount * $financials['commissionRate'];
			$financials['platformCommission'] += $commission;
			
			// Vendor earnings (90% of order)
			$vendorEarning = $orderAmount * (1 - $financials['commissionRate']);
			$financials['vendorEarnings'] += $vendorEarning;
			
			// Payment processing fee (assuming 2.9% + $0.30, adjust as needed)
			$processingFee = ($orderAmount * 0.029) + 0.30;
			$financials['paymentProcessingFees'] += $processingFee;
			
			// Revenue by vendor
			if (isset($order['items']) && is_array($order['items'])) {
				foreach ($order['items'] as $item) {
					if (isset($item['vendorId'])) {
						$vId = $item['vendorId'];
						if (!isset($financials['revenueByVendor'][$vId])) {
							$vendor = $this->common->readdatadocument('Users', $vId);
							$vendorName = isset($vendor['shopName']) ? $vendor['shopName'] : 
										(isset($vendor['firstName']) ? $vendor['firstName'] : 'Unknown Vendor');
							$financials['revenueByVendor'][$vId] = array(
								'vendorId' => $vId,
								'vendorName' => $vendorName,
								'totalRevenue' => 0,
								'earnings' => 0,
								'ordersCount' => 0
							);
						}
						$itemAmount = isset($item['totalPrice']) ? floatval($item['totalPrice']) : ($orderAmount / count($order['items']));
						$financials['revenueByVendor'][$vId]['totalRevenue'] += $itemAmount;
						$financials['revenueByVendor'][$vId]['earnings'] += $itemAmount * (1 - $financials['commissionRate']);
						$financials['revenueByVendor'][$vId]['ordersCount']++;
					}
					
					// Revenue by category
					if (isset($item['categoryId'])) {
						$catId = $item['categoryId'];
						if (!isset($financials['revenueByCategory'][$catId])) {
							$category = $this->common->readdatadocument('Categories', $catId);
							$catName = isset($category['categoryName']) ? $category['categoryName'] : 'Unknown Category';
							$financials['revenueByCategory'][$catId] = array(
								'categoryId' => $catId,
								'categoryName' => $catName,
								'totalRevenue' => 0,
								'ordersCount' => 0
							);
						}
						$itemAmount = isset($item['totalPrice']) ? floatval($item['totalPrice']) : ($orderAmount / count($order['items']));
						$financials['revenueByCategory'][$catId]['totalRevenue'] += $itemAmount;
						$financials['revenueByCategory'][$catId]['ordersCount']++;
					}
				}
			}
			
			// Revenue by day
			if (isset($order['date'])) {
				$dateKey = date('Y-m-d', $order['date'] / 1000);
				if (!isset($financials['revenueByDay'][$dateKey])) {
					$financials['revenueByDay'][$dateKey] = 0;
				}
				$financials['revenueByDay'][$dateKey] += $orderAmount;
			}
			
			// Check for refunds
			if (isset($order['refunded']) && $order['refunded'] && isset($order['refundAmount'])) {
				$financials['refundsIssued'] += floatval($order['refundAmount']);
			}
		}
		
		// Get rider payouts for the period
		$allPayouts = $this->common->readdatafromcollectionwhereclause('Payouts');
		if (!empty($allPayouts)) {
			foreach ($allPayouts as $payoutId => $payout) {
				$payoutDate = isset($payout['date']) ? $payout['date'] : 0;
				if ($payoutDate >= $fromDate && $payoutDate <= $toDate) {
					if (isset($payout['status']) && $payout['status'] == 'paid' && isset($payout['amount'])) {
						$financials['riderPayouts'] += floatval($payout['amount']);
					}
				}
			}
		}
		
		// Calculate net revenue
		$financials['netRevenue'] = $financials['platformCommission'] - $financials['paymentProcessingFees'] - $financials['riderPayouts'];
		
		// Get vendors list for filter dropdown
		$allVendors = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'vendor');
		$data['vendors'] = $allVendors;
		
		// Get cities list for filter dropdown
		$allCities = $this->common->readdatafromcollectionwhereclause('Cities');
		$data['cities'] = $allCities;
		
		$data['financials'] = $financials;
		$data['fromDate'] = date('Y-m-d', $fromDate / 1000);
		$data['toDate'] = date('Y-m-d', $toDate / 1000);
		$data['selectedVendorId'] = $vendorId;
		$data['selectedCityId'] = $cityId;
		
		$this->template->template_render('report_revenue', $data);
	}

	/**
	 * Export revenue report
	 */
	public function exportRevenueReport()
	{
		// This would generate CSV/Excel export
		// For now, just redirect to revenue page
		$this->revenue();
	}
}
