
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller {

	 function __construct()
     {
          parent::__construct();
       
          $this->load->helper('url');
          $this->load->library('session');
          $this->load->model('dashboard_model');
          $this->load->model('common');
          $this->load->model('geofence_model');
     }

     function formatNumber($value) {
        if ($value >= 1000000) {
            return rtrim(rtrim($value / 1000000, '0'), '.') . 'M'; // Convert to millions without rounding
        } elseif ($value >= 1000) {
            return rtrim(rtrim($value / 1000, '0'), '.') . 'K'; // Convert to thousands without rounding
        } else {
            return $value; // Keep the original value if it's less than 1000
        }
    }
    
    

public function dashobaordinfo(){
    $tripsCount = $this->common->readdatafromcollectionbetween("Orders");
   $noofsale=0;
   $totalsale=0;
   $bookingcomplete=0;
   $reatailsale=0;
    foreach($tripsCount as $t=>$j){
        if($j['orderStatus']=="deliver" ||$j['orderStatus']=="delivered"||$j['orderStatus']=="rate"||$j['orderStatus']=="rated") {
                $bookingcomplete=$bookingcomplete+1;
            }
            $noofsale = $noofsale+$j['totalQuantity'];

            $totalsale = $totalsale+$j['displayPrice'];
            $reatailsale = $reatailsale+$j['price'];

    }
    $jan['noofsale']=$this->formatNumber($noofsale);
    $jan['totalsale']=$this->formatNumber($totalsale);
    $jan['bookingcomplete']=$this->formatNumber($bookingcomplete);
    $jan['reatailsale']=$this->formatNumber($reatailsale);
    
    echo json_encode($jan);
    exit;

}

     public function index()
     {
        $this->load->helper('delivery');
        
        // Get all cities (if needed for driver city mapping)
        $allCities = $this->common->readdatafromcollectionwhereclause('Cities');
        $data['cities'] = $allCities;
        
        // Date ranges
        $today = date('Y-m-d');
        $todayTimestamp = strtotime('today') * 1000;
        $todayEndTimestamp = strtotime('tomorrow') * 1000 - 1;
        $weekStartTimestamp = strtotime('-7 days') * 1000;
        $monthStartTimestamp = strtotime('-30 days') * 1000;
        
        // Get all bookings from Bookings collection
        $allBookings = $this->common->readdatafromcollectionwhereclause('Bookings');
        
        // Get all users (customers)
        $allUsers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'user');
        $totalUsers = 0;
        $activeUsers = 0;
        
        foreach ($allUsers as $userId => $user) {
            $totalUsers++;
            if (isset($user['isApproved']) && $user['isApproved']) {
                $activeUsers++;
            }
        }
        
        // Get all drivers
        $allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
        $totalDrivers = 0;
        $activeDrivers = 0;
        
        foreach ($allDrivers as $driverId => $driver) {
            $totalDrivers++;
            if (isset($driver['isApproved']) && $driver['isApproved']) {
                $activeDrivers++;
            }
        }
        
        // Get total bookings count
        $totalBookings = count($allBookings);
        $completedBookings = 0;
        $pendingBookings = 0;
        
        // Calculate statistics for bookings
        $stats = array(
            'totalUsers' => $totalUsers,
            'activeUsers' => $activeUsers,
            'totalDrivers' => $totalDrivers,
            'activeDrivers' => $activeDrivers,
            'totalBookings' => $totalBookings,
            'completedBookings' => 0,
            'pendingBookings' => 0,
            'ordersToday' => 0,
            'ordersWeek' => 0,
            'ordersMonth' => 0,
            'revenueToday' => 0,
            'revenueWeek' => 0,
            'revenueMonth' => 0,
            'pendingDeliveries' => 0,
            'completedDeliveries' => 0,
            'revenueByCity' => array(),
            'driversByCity' => array(),
            'ordersByCity' => array()
        );
        
        // Process bookings
        foreach ($allBookings as $bookingId => $booking) {
            // Get booking date - use pickupDate if available, otherwise bookingDate
            $bookingDate = isset($booking['pickupDate']) ? $booking['pickupDate'] : (isset($booking['bookingDate']) ? $booking['bookingDate'] : 0);
            
            // Get booking price - use driverPrice if available, otherwise price
            $bookingPrice = 0;
            if (isset($booking['driverPrice'])) {
                $bookingPrice = floatval($booking['driverPrice']);
            } elseif (isset($booking['price'])) {
                $bookingPrice = floatval($booking['price']);
            }
            
            // Get booking status
            $bookingStatus = isset($booking['status']) ? strtolower($booking['status']) : 'pending';
            
            // Count completed and pending bookings
            // Completed statuses: rideComplete, completed, delivered, rated
            if (in_array($bookingStatus, array('ridecomplete', 'completed', 'delivered', 'rated', 'deliver'))) {
                $stats['completedBookings']++;
                $completedBookings++;
            } else {
                $stats['pendingBookings']++;
                $pendingBookings++;
            }
            
            // Bookings by time period
            if ($bookingDate >= $todayTimestamp && $bookingDate <= $todayEndTimestamp) {
                $stats['ordersToday']++;
                $stats['revenueToday'] += $bookingPrice;
            }
            if ($bookingDate >= $weekStartTimestamp) {
                $stats['ordersWeek']++;
                $stats['revenueWeek'] += $bookingPrice;
            }
            if ($bookingDate >= $monthStartTimestamp) {
                $stats['ordersMonth']++;
                $stats['revenueMonth'] += $bookingPrice;
            }
            
            // Booking status for pending/completed deliveries
            if (in_array($bookingStatus, array('pending', 'confirmed', 'accepted', 'in_progress', 'on_way'))) {
                $stats['pendingDeliveries']++;
            } elseif (in_array($bookingStatus, array('ridecomplete', 'completed', 'delivered'))) {
                $stats['completedDeliveries']++;
            }
            
            // Revenue grouping by driver location (if needed)
            // Since bookings don't have cityId, we can group by driver location or skip city-based stats
            // For now, we'll keep the structure but skip city-based grouping for bookings
        }
        
        // Count drivers by city (if drivers have cityId)
        foreach ($allDrivers as $driverId => $driver) {
            if (isset($driver['cityId'])) {
                $cityName = 'Unknown';
                $city = $this->common->readdatadocument('Cities', $driver['cityId']);
                if (!empty($city) && isset($city['cityName'])) {
                    $cityName = $city['cityName'];
                }
                
                if (!isset($stats['driversByCity'][$cityName])) {
                    $stats['driversByCity'][$cityName] = 0;
                }
                $stats['driversByCity'][$cityName]++;
            }
        }
        
        $data['stats'] = $stats;
        $data['totalUsers'] = $totalUsers;
        $data['activeUsers'] = $activeUsers;
        $data['totalDrivers'] = $totalDrivers;
        $data['activeDrivers'] = $activeDrivers;
        $data['totalBookings'] = $totalBookings;
        $data['completedBookings'] = $completedBookings;
        $data['pendingBookings'] = $pendingBookings;
        
        // Get bookings data for last 7 days for chart
        $seven_days_ago = date('Y-m-d', strtotime('-7 days'));
        $seven_days_agoms = strtotime($seven_days_ago) * 1000;
        // Query bookings by pickupDate or bookingDate
        $recentBookings = $this->common->readdatafromcollectionbetween("Bookings", "pickupDate", ">", $seven_days_agoms);
        // If no results with pickupDate, try bookingDate
        if (empty($recentBookings)) {
            $recentBookings = $this->common->readdatafromcollectionbetween("Bookings", "bookingDate", ">", $seven_days_agoms);
        }
        
        // Initialize arrays for last 7 days
        $datearray = array();
        $totalsale = array();
        $bookingcomplete = array();
        
        for ($i = 0; $i <= 6; $i++) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $datearray[$i] = $date;
            $totalsale[$date] = 0;
            $bookingcomplete[$date] = 0;
        }
        
        // Process recent bookings for chart data
        foreach($recentBookings as $t => $booking) {
            // Get booking date - use pickupDate if available, otherwise bookingDate
            $bookingDate = isset($booking['pickupDate']) ? $booking['pickupDate'] : (isset($booking['bookingDate']) ? $booking['bookingDate'] : 0);
            $bookingDateReadable = date('Y-m-d', $bookingDate / 1000);
            
            // Only process if date is in our array
            if (isset($totalsale[$bookingDateReadable])) {
                // Calculate revenue - use driverPrice if available, otherwise price
                $bookingPrice = 0;
                if (isset($booking['driverPrice'])) {
                    $bookingPrice = floatval($booking['driverPrice']);
                } elseif (isset($booking['price'])) {
                    $bookingPrice = floatval($booking['price']);
                }
                $totalsale[$bookingDateReadable] += $bookingPrice;
                
                // Count completed bookings
                $bookingStatus = isset($booking['status']) ? strtolower($booking['status']) : 'pending';
                if (in_array($bookingStatus, array('ridecomplete', 'completed', 'delivered', 'rated'))) {
                    $bookingcomplete[$bookingDateReadable]++;
                }
            }
        }
      
        $data['datearray'] = $datearray;
        $data['totalsale'] = $totalsale;
        $data['bookingcomplete'] = $bookingcomplete;

         $this->template->template_render('dashboard',$data);
     }
     
	
  public function iechart()
  {
      $data= $this->common->get_iechartdata();
      $res = "['" . implode ( "', '", array_keys($data)) . "']";
      $income = "['" . implode ( "', '", array_column($data, 'income')) . "']";
      $expense = "['" . implode ( "', '", array_column($data, 'expense')) . "']";
      echo json_encode(array('res'=>$res,'admin'=>$income,'driver'=>$expense));
  }
  public function remindermark()
  {
      $data = array('r_isread' => 1);
      $this->db->where('r_id',$this->input->post('r_id'));
      echo $this->db->update('reminder',$data);
  }
  public function categories()
  {

      $data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
      $this->template->template_render('categories', $data);
  }
  public function subcategories()
  {
    $data['maincategories'] = $this->common->readdatafromcollectionwhereclause('Categories');
      $data['categories'] = $this->common->readdatafromcollectionwhereclause('Subcategories');
      $this->template->template_render('subcategories', $data);
  }
  
  public function updatesubcategory()
	{
    $post = $this->input->post();
    // echo "<pre>";
    // print_r($post);
    // echo "</pre>";
   
    
	 	$response = $this->common->updatedatamodel('Subcategories', $post['id'], $post);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Subcategories updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/Subcategories'));
	}
  
  public function updatecategory()
	{
    $post = $this->input->post();
    // echo "<pre>";
    // print_r($post);
    // echo "</pre>";
   
    
	 	$response = $this->common->updatedatamodel('Categories', $post['id'], $post);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
	}
    //
    public function updatesetting()
	{
        $post = $this->input->post();
    $d['tax'] = floatval($this->input->post('tax'));
    $d['serviceFee'] = floatval($this->input->post('serviceFee'));
    $d['delivery'] = floatval($this->input->post('delivery'));
    
    
	 	$response = $this->common->updatedatamodel('Settings', $post['id'], $d);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Settings updated successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/settings'));
	}
  public function insertsubcategory()
	{

		
		$data = $this->input->post();
        $id=time();

    $response = $this->common->adddatamodel('Subcategories',$id, $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Subcategories added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/subcategories'));		
	}

  public function insertcategory()
	{

		
		$data = $this->input->post();
        $id=time();

    $response = $this->common->adddatamodel('Categories',$id, $data);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category added successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));		
	}
  public function addcategory()
  {

      $this->template->template_render('addcategory');
  }
  public function addsubcategory()
  {
    $data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
      $this->template->template_render('addsubcategory',$data);
  }
  public function editcategory()
  {
      $id = $this->uri->segment(3);
  $data['id'] = $id;
      $data['category'] = $this->common->readdatadocument('Categories', $id);
      $this->template->template_render('addcategory', $data);
  }

  public function editsubcategory()
  {
      $id = $this->uri->segment(3);
  $data['id'] = $id;
  $data['categories'] = $this->common->readdatafromcollectionwhereclause('Categories');
      $data['category'] = $this->common->readdatadocument('Subcategories', $id);
      $this->template->template_render('addsubcategory', $data);
  }

  public function settings(){
    $id="pUWUaBGGSbhdBY0BUq06";
    $data['id'] = $id;
    $data['category'] = $this->common->readdatadocument('Settings', $id);
    $this->template->template_render('addsetting', $data);
  }

  public function deletecategory()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Categories', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Category deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/categories'));
	}
  
  public function deletesubcategory()
	{
    $id = $this->uri->segment(3);

		$response = $this->common->deletedatamodel('Subcategories', $id);

    if ($response) {
      $this->session->set_flashdata('successmessage', 'Subcategories deleted successfully..');
    } else {
      $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
    }

    redirect(base_url('dashboard/Subcategories'));
	}

  // City Management Methods
  public function cities()
  {
      $cities = $this->common->readdatafromcollectionwhereclause('Cities');
      $data['cities'] = $cities;
      
      // Calculate overall statistics
      $overallStats = array(
          'totalOrders' => 0,
          'totalRevenue' => 0,
          'totalDrivers' => 0,
          'totalVendors' => 0
      );
      
      // Get all orders
      $allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
      foreach ($allOrders as $order) {
          $overallStats['totalOrders']++;
          $overallStats['totalRevenue'] += isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
      }
      
      // Get all drivers
      $allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
      foreach ($allDrivers as $driver) {
          if (isset($driver['isApproved']) && $driver['isApproved']) {
              $overallStats['totalDrivers']++;
          }
      }
      
      // Get all vendors
      $allVendors = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'vendor');
      foreach ($allVendors as $vendor) {
          if (isset($vendor['isApproved']) && $vendor['isApproved']) {
              $overallStats['totalVendors']++;
          }
      }
      
      $data['overallStats'] = $overallStats;
      
      // Calculate stats per city
      $cityStatsData = array();
      foreach ($cities as $cityId => $city) {
          $cityStats = array(
              'orders' => 0,
              'revenue' => 0,
              'drivers' => 0,
              'vendors' => 0,
              'pendingOrders' => 0
          );
          
          // Count orders for this city
          foreach ($allOrders as $order) {
              if (isset($order['cityId']) && $order['cityId'] == $cityId) {
                  $cityStats['orders']++;
                  $cityStats['revenue'] += isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
                  if (isset($order['orderStatus']) && in_array($order['orderStatus'], array('pending', 'confirmed', 'preparing'))) {
                      $cityStats['pendingOrders']++;
                  }
              }
          }
          
          // Count drivers for this city
          foreach ($allDrivers as $driver) {
              if (isset($driver['cityId']) && $driver['cityId'] == $cityId && isset($driver['isApproved']) && $driver['isApproved']) {
                  $cityStats['drivers']++;
              }
          }
          
          // Count vendors for this city
          foreach ($allVendors as $vendor) {
              if (isset($vendor['cityId']) && $vendor['cityId'] == $cityId && isset($vendor['isApproved']) && $vendor['isApproved']) {
                  $cityStats['vendors']++;
              }
          }
          
          $cityStatsData[$cityId] = $cityStats;
      }
      
      $data['cityStatsData'] = $cityStatsData;
      
      $this->template->template_render('city_management', $data);
  }

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

  public function insertcity()
  {
      $post = $this->input->post();
      
      // Check if this is an AJAX request
      $isAjax = $this->input->is_ajax_request();
      
      // Check for duplicate city name (case-insensitive)
      $cityName = trim($post['cityName']);
      $allCities = $this->common->readdatafromcollectionwhereclause('Cities');
      
      foreach ($allCities as $cityId => $city) {
          if (isset($city['cityName']) && strtolower(trim($city['cityName'])) === strtolower($cityName)) {
              if ($isAjax) {
                  echo json_encode(array('success' => false, 'message' => 'City with this name already exists. Please use a different name.'));
                  return;
              } else {
                  $this->session->set_flashdata('warningmessage', 'City with this name already exists. Please use a different name.');
                  redirect(base_url('dashboard/addcity'));
                  return;
              }
          }
      }
      
      $data = array(
          'cityName' => $cityName,
          'latitude' => floatval($post['latitude']),
          'longitude' => floatval($post['longitude']),
          'state' => trim($post['state']),
          'country' => trim($post['country']),
          'googlePlaceId' => isset($post['googlePlaceId']) ? trim($post['googlePlaceId']) : '',
          'hqAddress' => isset($post['hqAddress']) ? trim($post['hqAddress']) : '',
          'hqLatitude' => isset($post['hqLatitude']) && $post['hqLatitude'] != '' ? floatval($post['hqLatitude']) : null,
          'hqLongitude' => isset($post['hqLongitude']) && $post['hqLongitude'] != '' ? floatval($post['hqLongitude']) : null
      );
      
      $id = time();
      $response = $this->common->adddatamodel('Cities', $id, $data);

      if ($response) {
          if ($isAjax) {
              echo json_encode(array('success' => true, 'message' => 'City added successfully!'));
              return;
          } else {
              $this->session->set_flashdata('successmessage', 'City 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..Try again');
          }
      }

      if (!$isAjax) {
          redirect(base_url('dashboard/cities'));
      }
  }

  public function editcity()
  {
      $id = $this->uri->segment(3);
      $data['id'] = $id;
      $data['city'] = $this->common->readdatadocument('Cities', $id);
      $this->template->template_render('addcity', $data);
  }

  public function updatecity()
  {
      $post = $this->input->post();
      
      // Check if this is an AJAX request
      $isAjax = $this->input->is_ajax_request();
      
      // Check for duplicate city name (case-insensitive), excluding current city
      $cityName = trim($post['cityName']);
      $currentId = $post['id'];
      $allCities = $this->common->readdatafromcollectionwhereclause('Cities');
      
      foreach ($allCities as $cityId => $city) {
          if ($cityId != $currentId && isset($city['cityName']) && strtolower(trim($city['cityName'])) === strtolower($cityName)) {
              if ($isAjax) {
                  echo json_encode(array('success' => false, 'message' => 'City with this name already exists. Please use a different name.'));
                  return;
              } else {
                  $this->session->set_flashdata('warningmessage', 'City with this name already exists. Please use a different name.');
                  redirect(base_url('dashboard/editcity/' . $currentId));
                  return;
              }
          }
      }
      
      $data = array(
          'cityName' => $cityName,
          'latitude' => floatval($post['latitude']),
          'longitude' => floatval($post['longitude']),
          'state' => trim($post['state']),
          'country' => trim($post['country']),
          'googlePlaceId' => isset($post['googlePlaceId']) ? trim($post['googlePlaceId']) : '',
          'hqAddress' => isset($post['hqAddress']) ? trim($post['hqAddress']) : '',
          'hqLatitude' => isset($post['hqLatitude']) && $post['hqLatitude'] != '' ? floatval($post['hqLatitude']) : null,
          'hqLongitude' => isset($post['hqLongitude']) && $post['hqLongitude'] != '' ? floatval($post['hqLongitude']) : null
      );
      
      $response = $this->common->updatedatamodel('Cities', $post['id'], $data);

      if ($response) {
          if ($isAjax) {
              echo json_encode(array('success' => true, 'message' => 'City updated successfully!'));
              return;
          } else {
              $this->session->set_flashdata('successmessage', 'City 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..Try again');
          }
      }

      if (!$isAjax) {
          redirect(base_url('dashboard/cities'));
      }
  }

  public function deletecity()
  {
      $id = $this->uri->segment(3);

      $response = $this->common->deletedatamodel('Cities', $id);

      if ($response) {
          $this->session->set_flashdata('successmessage', 'City deleted successfully..');
      } else {
          $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
      }

      redirect(base_url('dashboard/cities'));
  }

  // City Settings - Configure city-specific settings
  public function city_settings()
  {
      $cityId = $this->uri->segment(3);
      if (!$cityId) {
          redirect(base_url('dashboard/cities'));
          return;
      }
      
      $city = $this->common->readdatadocument('Cities', $cityId);
      if (empty($city)) {
          $this->session->set_flashdata('warningmessage', 'City not found.');
          redirect(base_url('dashboard/cities'));
          return;
      }
      
      $data['city'] = $city;
      $data['cityId'] = $cityId;
      
      // Initialize default settings if not set
      if (!isset($city['settings'])) {
          $city['settings'] = array(
              'cutoffTime' => '22:00',
              'minOrderAmount' => 0,
              'deliveryFeeBase' => 0,
              'loyaltyPointsPerDollar' => 1,
              'loyaltyPointsRequired' => 100,
              'enablePromotions' => true,
              'enableLoyalty' => true
          );
      }
      
      $data['settings'] = $city['settings'];
      
      $this->template->template_render('city_settings', $data);
  }

  // Update city settings
  public function update_city_settings()
  {
      $post = $this->input->post();
      $cityId = $post['cityId'];
      $isAjax = $this->input->is_ajax_request();
      
      // Prepare settings data
      $settings = array(
          'cutoffTime' => isset($post['cutoffTime']) ? trim($post['cutoffTime']) : '22:00',
          'minOrderAmount' => isset($post['minOrderAmount']) ? floatval($post['minOrderAmount']) : 0,
          'deliveryFeeBase' => isset($post['deliveryFeeBase']) ? floatval($post['deliveryFeeBase']) : 0,
          'loyaltyPointsPerDollar' => isset($post['loyaltyPointsPerDollar']) ? floatval($post['loyaltyPointsPerDollar']) : 1,
          'loyaltyPointsRequired' => isset($post['loyaltyPointsRequired']) ? intval($post['loyaltyPointsRequired']) : 100,
          'enablePromotions' => isset($post['enablePromotions']) ? true : false,
          'enableLoyalty' => isset($post['enableLoyalty']) ? true : false
      );
      
      $updateData = array('settings' => $settings);
      
      $response = $this->common->updatedatamodel('Cities', $cityId, $updateData);
      
      if ($response) {
          if ($isAjax) {
              echo json_encode(array('success' => true, 'message' => 'City settings updated successfully!'));
              return;
          } else {
              $this->session->set_flashdata('successmessage', 'City settings updated successfully.');
          }
      } else {
          if ($isAjax) {
              echo json_encode(array('success' => false, 'message' => 'Failed to update city settings.'));
              return;
          } else {
              $this->session->set_flashdata('warningmessage', 'Failed to update city settings.');
          }
      }
      
      if (!$isAjax) {
          redirect(base_url('dashboard/city_settings/' . $cityId));
      }
  }

  // City Analytics - View city-specific analytics
  public function city_analytics()
  {
      $cityId = $this->uri->segment(3);
      if (!$cityId) {
          redirect(base_url('dashboard/cities'));
          return;
      }
      
      $city = $this->common->readdatadocument('Cities', $cityId);
      if (empty($city)) {
          $this->session->set_flashdata('warningmessage', 'City not found.');
          redirect(base_url('dashboard/cities'));
          return;
      }
      
      $data['city'] = $city;
      $data['cityId'] = $cityId;
      
      // Get all orders for this city
      $allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
      $cityOrders = array();
      foreach ($allOrders as $orderId => $order) {
          if (isset($order['cityId']) && $order['cityId'] == $cityId) {
              $cityOrders[$orderId] = $order;
          }
      }
      
      // Calculate analytics
      $analytics = array(
          'totalOrders' => count($cityOrders),
          'totalRevenue' => 0,
          'averageOrderValue' => 0,
          'pendingOrders' => 0,
          'completedOrders' => 0,
          'cancelledOrders' => 0,
          'ordersByStatus' => array(),
          'revenueByDay' => array(),
          'ordersByDay' => array()
      );
      
      foreach ($cityOrders as $order) {
          $amount = isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
          $analytics['totalRevenue'] += $amount;
          
          $status = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
          if (!isset($analytics['ordersByStatus'][$status])) {
              $analytics['ordersByStatus'][$status] = 0;
          }
          $analytics['ordersByStatus'][$status]++;
          
          if (in_array($status, array('pending', 'confirmed', 'preparing'))) {
              $analytics['pendingOrders']++;
          } elseif (in_array($status, array('delivered', 'completed', 'rated'))) {
              $analytics['completedOrders']++;
          } elseif ($status == 'cancelled') {
              $analytics['cancelledOrders']++;
          }
          
          // Group by day
          if (isset($order['date'])) {
              $date = date('Y-m-d', $order['date'] / 1000);
              if (!isset($analytics['revenueByDay'][$date])) {
                  $analytics['revenueByDay'][$date] = 0;
                  $analytics['ordersByDay'][$date] = 0;
              }
              $analytics['revenueByDay'][$date] += $amount;
              $analytics['ordersByDay'][$date]++;
          }
      }
      
      if ($analytics['totalOrders'] > 0) {
          $analytics['averageOrderValue'] = $analytics['totalRevenue'] / $analytics['totalOrders'];
      }
      
      // Get drivers and vendors count
      $allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
      $allVendors = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'vendor');
      
      $analytics['totalDrivers'] = 0;
      $analytics['activeDrivers'] = 0;
      foreach ($allDrivers as $driver) {
          if (isset($driver['cityId']) && $driver['cityId'] == $cityId) {
              $analytics['totalDrivers']++;
              if (isset($driver['isApproved']) && $driver['isApproved']) {
                  $analytics['activeDrivers']++;
              }
          }
      }
      
      $analytics['totalVendors'] = 0;
      $analytics['activeVendors'] = 0;
      foreach ($allVendors as $vendor) {
          if (isset($vendor['cityId']) && $vendor['cityId'] == $cityId) {
              $analytics['totalVendors']++;
              if (isset($vendor['isApproved']) && $vendor['isApproved']) {
                  $analytics['activeVendors']++;
              }
          }
      }
      
      $data['analytics'] = $analytics;
      $data['cityOrders'] = $cityOrders;
      
      $this->template->template_render('city_analytics', $data);
  }

  // City Zones Configuration
  public function cityzones()
  {
      $cityId = $this->uri->segment(3);
      if (!$cityId) {
          redirect(base_url('dashboard/cities'));
          return;
      }
      
      $data['city'] = $this->common->readdatadocument('Cities', $cityId);
      $data['cityId'] = $cityId;
      
      // Get zones for this city
      $zones = $this->common->readdatafromcollectionwhereclause('CityZones', 'cityId', '=', $cityId);
      $data['zones'] = $zones;
      
      $this->template->template_render('cityzones', $data);
  }

  public function updatecityzones()
  {
      $post = $this->input->post();
      $cityId = $post['cityId'];
      
      // Default zones structure
      $zones = array(
          'zone1' => array(
              'minDistance' => 0,
              'maxDistance' => 12,
              'fee' => 3.00,
              'minimumOrder' => 25.00
          ),
          'zone2' => array(
              'minDistance' => 12,
              'maxDistance' => 20,
              'fee' => 6.50,
              'minimumOrder' => 25.00,
              'storefrontMinimumOrder' => 40.00
          ),
          'zone3' => array(
              'minDistance' => 20,
              'maxDistance' => 30,
              'fee' => 10.00,
              'minimumOrder' => 70.00
          ),
          'zone4' => array(
              'minDistance' => 30,
              'maxDistance' => 999999,
              'fee' => 15.00,
              'minimumOrder' => 125.00
          )
      );
      
      // Update with posted values if provided
      foreach ($zones as $zoneKey => $zoneData) {
          if (isset($post[$zoneKey . '_fee'])) {
              $zones[$zoneKey]['fee'] = floatval($post[$zoneKey . '_fee']);
          }
          if (isset($post[$zoneKey . '_minOrder'])) {
              $zones[$zoneKey]['minimumOrder'] = floatval($post[$zoneKey . '_minOrder']);
          }
          if (isset($post[$zoneKey . '_minDistance'])) {
              $zones[$zoneKey]['minDistance'] = floatval($post[$zoneKey . '_minDistance']);
          }
          if (isset($post[$zoneKey . '_maxDistance'])) {
              $zones[$zoneKey]['maxDistance'] = floatval($post[$zoneKey . '_maxDistance']);
          }
          if (isset($post[$zoneKey . '_storefrontMinOrder'])) {
              $zones[$zoneKey]['storefrontMinimumOrder'] = floatval($post[$zoneKey . '_storefrontMinOrder']);
          }
      }
      
      $zoneData = array(
          'cityId' => $cityId,
          'zones' => $zones,
          'updatedAt' => time()
      );
      
      // Check if zones exist for this city
      $existingZones = $this->common->readdatafromcollectionwhereclause('CityZones', 'cityId', '=', $cityId);
      $zoneId = null;
      
      if (!empty($existingZones)) {
          $zoneId = key($existingZones);
      } else {
          $zoneId = time();
      }
      
      $response = $this->common->adddatamodel('CityZones', $zoneId, $zoneData);
      
      if ($response) {
          $this->session->set_flashdata('successmessage', 'City zones updated successfully..');
      } else {
          $this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
      }
      
      redirect(base_url('dashboard/cityzones/' . $cityId));
  }

    /**
     * Delivery Zone Testing Tool
     */
    public function zonetest()
    {
        $data['cities'] = $this->common->readdatafromcollectionwhereclause('Cities');
        $this->template->template_render('zone_test', $data);
    }
    
    /**
     * Get vendors for zone test dropdown
     */
    public function getvendorsforzonetest()
    {
        $vendors = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '==', 'vendor');
        
        $vendorList = array();
        foreach ($vendors as $vendorId => $vendor) {
            $vendorName = isset($vendor['shopName']) ? $vendor['shopName'] : 
                         (isset($vendor['firstName']) ? $vendor['firstName'] . ' ' . (isset($vendor['lastName']) ? $vendor['lastName'] : '') : 'Unknown Vendor');
            
            $vendorList[$vendorId] = array(
                'shopName' => isset($vendor['shopName']) ? $vendor['shopName'] : '',
                'firstName' => isset($vendor['firstName']) ? $vendor['firstName'] : '',
                'lastName' => isset($vendor['lastName']) ? $vendor['lastName'] : '',
                'fulfillment_type' => isset($vendor['fulfillment_type']) ? $vendor['fulfillment_type'] : 'storefront_pickup',
                'cityId' => isset($vendor['cityId']) ? $vendor['cityId'] : '',
                'name' => $vendorName
            );
        }
        
        echo json_encode(array(
            'success' => true,
            'vendors' => $vendorList
        ));
    }
    
    /**
     * Get products for zone test dropdown (filtered by vendor)
     */
    public function getproductsforzonetest()
    {
        $vendorId = $this->input->get('vendorId');
        
        if (!$vendorId) {
            echo json_encode(array(
                'success' => false,
                'message' => 'Vendor ID is required',
                'products' => array()
            ));
            return;
        }
        
        // Get all products
        $allProducts = $this->common->readdatafromcollectionwhereclause('Products');
        
        $productList = array();
        foreach ($allProducts as $productId => $product) {
            // Filter by vendor if specified
            if ($vendorId && isset($product['vendorId']) && $product['vendorId'] != $vendorId) {
                continue;
            }
            
            $productName = isset($product['name']) ? $product['name'] : 'Unknown Product';
            $productPrice = isset($product['displayPrice']) ? $product['displayPrice'] : 
                          (isset($product['price']) ? $product['price'] : 0);
            
            $productList[] = array(
                'id' => $productId,
                'name' => $productName,
                'price' => number_format($productPrice, 2)
            );
        }
        
        echo json_encode(array(
            'success' => true,
            'products' => $productList
        ));
    }

    /**
     * Calculate zone test via AJAX
     */
    public function calculatezonetest()
    {
        $this->load->helper('delivery');
        
        $cityId = $this->input->post('cityId');
        $customerLat = floatval($this->input->post('customerLat'));
        $customerLon = floatval($this->input->post('customerLon'));
        $items = json_decode($this->input->post('items'), true);
        
        if (!$cityId || !$customerLat || !$customerLon || empty($items)) {
            echo json_encode(array(
                'success' => false,
                'message' => 'Missing required fields'
            ));
            return;
        }

        // Get city data
        $city = $this->common->readdatadocument('Cities', $cityId);
        if (empty($city) || !isset($city['hqLatitude']) || !isset($city['hqLongitude'])) {
            echo json_encode(array(
                'success' => false,
                'message' => 'City not found or HQ not configured'
            ));
            return;
        }

        // Prepare customer data
        $customer = array(
            'latitude' => $customerLat,
            'longitude' => $customerLon
        );

        // Prepare order items with vendor data
        $orderItems = array();
        $hasStorefront = false;
        $hasCannabusInventory = false;
        $vendorDetails = array();
        
        foreach ($items as $item) {
            if (!isset($item['vendorId'])) {
                continue;
            }
            
            // Vendors are stored in 'Users' collection with userRole = 'vendor'
            $vendor = $this->common->readdatadocument('Users', $item['vendorId']);
            if (empty($vendor)) {
                continue;
            }
            
            // Check if it's actually a vendor
            if (!isset($vendor['userRole']) || $vendor['userRole'] != 'vendor') {
                continue;
            }
            
            $fulfillmentType = isset($vendor['fulfillment_type']) ? $vendor['fulfillment_type'] : 'storefront_pickup';
            
            if ($fulfillmentType == 'storefront_pickup') {
                $hasStorefront = true;
            } elseif ($fulfillmentType == 'cannabus_inventory') {
                $hasCannabusInventory = true;
            }
            
            // Get vendor name (shopName or firstName + lastName)
            $vendorName = 'Unknown Vendor';
            if (isset($vendor['shopName']) && !empty($vendor['shopName'])) {
                $vendorName = $vendor['shopName'];
            } elseif (isset($vendor['firstName'])) {
                $vendorName = $vendor['firstName'];
                if (isset($vendor['lastName']) && !empty($vendor['lastName'])) {
                    $vendorName .= ' ' . $vendor['lastName'];
                }
            }
            
            $vendorDetails[] = array(
                'vendorId' => $item['vendorId'],
                'vendorName' => $vendorName,
                'fulfillmentType' => $fulfillmentType,
                'vendorLat' => isset($vendor['latitude']) ? floatval($vendor['latitude']) : null,
                'vendorLon' => isset($vendor['longitude']) ? floatval($vendor['longitude']) : null
            );
            
            $orderItems[] = array(
                'vendor' => $vendor,
                'vendorId' => $item['vendorId']
            );
        }

        if (empty($orderItems)) {
            echo json_encode(array(
                'success' => false,
                'message' => 'No valid order items found'
            ));
            return;
        }

        // Calculate distances
        $hqLat = $city['hqLatitude'];
        $hqLon = $city['hqLongitude'];
        
        $hqToCustomer = calculate_distance($hqLat, $hqLon, $customerLat, $customerLon);
        
        // Calculate vendor distances
        $vendorDistances = array();
        foreach ($vendorDetails as $vendor) {
            if ($vendor['vendorLat'] && $vendor['vendorLon']) {
                $hqToVendor = calculate_distance($hqLat, $hqLon, $vendor['vendorLat'], $vendor['vendorLon']);
                $vendorToCustomer = calculate_distance($vendor['vendorLat'], $vendor['vendorLon'], $customerLat, $customerLon);
                
                $vendorDistances[] = array(
                    'vendorId' => $vendor['vendorId'],
                    'vendorName' => $vendor['vendorName'],
                    'fulfillmentType' => $vendor['fulfillmentType'],
                    'hqToVendor' => round($hqToVendor, 2),
                    'vendorToCustomer' => round($vendorToCustomer, 2),
                    'totalDistance' => round($hqToVendor + $vendorToCustomer, 2)
                );
            }
        }

        // Calculate chargeable distance
        $chargeableDistance = calculate_chargeable_distance($orderItems, $city, $customer, $this->common);

        // Get zones configuration
        $zones = get_city_zones($cityId, $this->common);

        // Assign zone
        $zoneKey = assign_zone($chargeableDistance, $zones);

        // Get pricing
        $pricing = get_zone_pricing($zoneKey, $zones, $hasStorefront);

        // Find farthest vendor for multi-vendor orders
        $farthestVendor = null;
        if ($hasStorefront && count($vendorDistances) > 1) {
            $maxDistance = 0;
            foreach ($vendorDistances as $vendor) {
                if ($vendor['hqToVendor'] > $maxDistance) {
                    $maxDistance = $vendor['hqToVendor'];
                    $farthestVendor = $vendor;
                }
            }
        }

        echo json_encode(array(
            'success' => true,
            'data' => array(
                'city' => array(
                    'name' => isset($city['cityName']) ? $city['cityName'] : 'Unknown',
                    'hqAddress' => isset($city['hqAddress']) ? $city['hqAddress'] : 'Not set',
                    'hqLat' => $hqLat,
                    'hqLon' => $hqLon
                ),
                'customer' => array(
                    'lat' => $customerLat,
                    'lon' => $customerLon
                ),
                'distances' => array(
                    'hqToCustomer' => round($hqToCustomer, 2),
                    'chargeableDistance' => round($chargeableDistance, 2)
                ),
                'vendors' => $vendorDistances,
                'farthestVendor' => $farthestVendor,
                'zone' => array(
                    'key' => $zoneKey,
                    'distance' => round($chargeableDistance, 2),
                    'minDistance' => isset($zones[$zoneKey]['minDistance']) ? $zones[$zoneKey]['minDistance'] : 0,
                    'maxDistance' => isset($zones[$zoneKey]['maxDistance']) ? $zones[$zoneKey]['maxDistance'] : 999999
                ),
                'pricing' => $pricing,
                'orderType' => array(
                    'hasCannabusInventory' => $hasCannabusInventory,
                    'hasStorefront' => $hasStorefront,
                    'isMultiVendor' => count($vendorDistances) > 1
                )
            )
        ));
    }
     
}
