
<?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;

}

/**
 * Get comprehensive analytics data for admin dashboard
 */
public function getAnalytics()
{
    // 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;
    
    // Initialize analytics array
    $analytics = array(
        'users' => array(
            'totalRegistered' => 0,
            'totalActive' => 0,
            'totalSuspended' => 0,
            'todayRegistered' => 0
        ),
        'vendors' => array(
            'total' => 0,
            'approved' => 0,
            'pending' => 0,
            'rejected' => 0,
            'active' => 0
        ),
        'riders' => array(
            'total' => 0,
            'approved' => 0,
            'pending' => 0,
            'rejected' => 0,
            'active' => 0
        ),
        'orders' => array(
            'total' => 0,
            'completed' => 0,
            'cancelled' => 0,
            'disputed' => 0,
            'today' => 0,
            'week' => 0,
            'month' => 0
        ),
        'revenue' => array(
            'total' => 0,
            'today' => 0,
            'week' => 0,
            'month' => 0,
            'commission' => 0,
            'vendorEarnings' => 0,
            'riderPayouts' => 0
        )
    );
    
    // Get all users (customers only)
    $allUsers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'customer');
    if (empty($allUsers)) {
        $allUsers = array();
    }
    
    foreach ($allUsers as $userId => $user) {
        $analytics['users']['totalRegistered']++;
        
        // Check if active
        $isActive = true;
        if (isset($user['isSuspended']) && $user['isSuspended']) {
            $isActive = false;
            $analytics['users']['totalSuspended']++;
        } elseif (isset($user['isActive']) && !$user['isActive']) {
            $isActive = false;
        }
        
        if ($isActive) {
            $analytics['users']['totalActive']++;
        }
        
        // Check registration date
        if (isset($user['registrationDate']) && $user['registrationDate'] >= $todayTimestamp) {
            $analytics['users']['todayRegistered']++;
        }
    }
    
    // Get all vendors
    $allVendors = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'vendor');
    if (empty($allVendors)) {
        $allVendors = array();
    }
    
    foreach ($allVendors as $vendorId => $vendor) {
        $analytics['vendors']['total']++;
        
        $isApproved = isset($vendor['isApproved']) ? $vendor['isApproved'] : false;
        $isActive = isset($vendor['isActive']) ? $vendor['isActive'] : true;
        
        if ($isApproved) {
            $analytics['vendors']['approved']++;
            if ($isActive) {
                $analytics['vendors']['active']++;
            }
        } else {
            // Check if rejected
            if (isset($vendor['verificationStatus']) && $vendor['verificationStatus'] == 'rejected') {
                $analytics['vendors']['rejected']++;
            } else {
                $analytics['vendors']['pending']++;
            }
        }
    }
    
    // Get all riders/drivers
    $allRiders = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
    if (empty($allRiders)) {
        $allRiders = array();
    }
    
    foreach ($allRiders as $riderId => $rider) {
        $analytics['riders']['total']++;
        
        $isApproved = isset($rider['isApproved']) ? $rider['isApproved'] : false;
        $isActive = isset($rider['isActive']) ? $rider['isActive'] : true;
        
        if ($isApproved) {
            $analytics['riders']['approved']++;
            if ($isActive) {
                $analytics['riders']['active']++;
            }
        } else {
            // Check if rejected
            if (isset($rider['verificationStatus']) && $rider['verificationStatus'] == 'rejected') {
                $analytics['riders']['rejected']++;
            } else {
                $analytics['riders']['pending']++;
            }
        }
    }
    
    // Get all orders
    $allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
    if (empty($allOrders)) {
        $allOrders = array();
    }
    
    foreach ($allOrders as $orderId => $order) {
        $analytics['orders']['total']++;
        
        $orderDate = isset($order['date']) ? $order['date'] : 0;
        $orderAmount = isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
        $orderStatus = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
        
        // Count by status
        if (in_array($orderStatus, array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
            $analytics['orders']['completed']++;
            $analytics['revenue']['total'] += $orderAmount;
            
            // Calculate commission (assuming 10% commission, adjust as needed)
            $analytics['revenue']['commission'] += $orderAmount * 0.10;
            
            // Calculate vendor earnings (assuming 90% goes to vendor, adjust as needed)
            $analytics['revenue']['vendorEarnings'] += $orderAmount * 0.90;
        } elseif ($orderStatus == 'cancelled') {
            $analytics['orders']['cancelled']++;
        }
        
        // Check if disputed
        if (isset($order['hasDispute']) && $order['hasDispute']) {
            $analytics['orders']['disputed']++;
        }
        
        // Orders by time period
        if ($orderDate >= $todayTimestamp && $orderDate <= $todayEndTimestamp) {
            $analytics['orders']['today']++;
            if (in_array($orderStatus, array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
                $analytics['revenue']['today'] += $orderAmount;
            }
        }
        if ($orderDate >= $weekStartTimestamp) {
            $analytics['orders']['week']++;
            if (in_array($orderStatus, array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
                $analytics['revenue']['week'] += $orderAmount;
            }
        }
        if ($orderDate >= $monthStartTimestamp) {
            $analytics['orders']['month']++;
            if (in_array($orderStatus, array('delivered', 'deliver', 'rate', 'rated', 'completed'))) {
                $analytics['revenue']['month'] += $orderAmount;
            }
        }
    }
    
    // Get rider payouts (if stored in a separate collection)
    $allPayouts = $this->common->readdatafromcollectionwhereclause('Payouts');
    if (!empty($allPayouts)) {
        foreach ($allPayouts as $payoutId => $payout) {
            if (isset($payout['status']) && $payout['status'] == 'paid' && isset($payout['amount'])) {
                $analytics['revenue']['riderPayouts'] += floatval($payout['amount']);
            }
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode($analytics);
    exit;
}

     public function index()
     {
        $this->load->helper('delivery');
        
        // Get all cities
        $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 orders
        $allOrders = $this->common->readdatafromcollectionwhereclause('Orders');
        
        // Calculate statistics
        $stats = array(
            'ordersToday' => 0,
            'ordersWeek' => 0,
            'ordersMonth' => 0,
            'revenueToday' => 0,
            'revenueWeek' => 0,
            'revenueMonth' => 0,
            'pendingDeliveries' => 0,
            'completedDeliveries' => 0,
            'cannabusInventoryOrders' => 0,
            'storefrontOrders' => 0,
            'revenueByCity' => array(),
            'driversByCity' => array(),
            'ordersByCity' => array()
        );
        
        // Get all drivers
        $allDrivers = $this->common->readdatafromcollectionwhereclause('Users', 'userRole', '=', 'driver');
        $activeDrivers = 0;
        
        foreach ($allDrivers as $driverId => $driver) {
            if (isset($driver['isApproved']) && $driver['isApproved']) {
                $activeDrivers++;
                
                // Count drivers by city
                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]++;
                }
            }
        }
        
        // Process orders
        foreach ($allOrders as $orderId => $order) {
            $orderDate = isset($order['date']) ? $order['date'] : 0;
            $orderAmount = isset($order['totalAmount']) ? floatval($order['totalAmount']) : 0;
            $orderStatus = isset($order['orderStatus']) ? $order['orderStatus'] : 'pending';
            
            // Orders by time period
            if ($orderDate >= $todayTimestamp && $orderDate <= $todayEndTimestamp) {
                $stats['ordersToday']++;
                $stats['revenueToday'] += $orderAmount;
            }
            if ($orderDate >= $weekStartTimestamp) {
                $stats['ordersWeek']++;
                $stats['revenueWeek'] += $orderAmount;
            }
            if ($orderDate >= $monthStartTimestamp) {
                $stats['ordersMonth']++;
                $stats['revenueMonth'] += $orderAmount;
            }
            
            // Delivery status
            if ($orderStatus == 'pending' || $orderStatus == 'confirmed' || $orderStatus == 'preparing' || $orderStatus == 'out_for_delivery') {
                $stats['pendingDeliveries']++;
            } elseif ($orderStatus == 'delivered') {
                $stats['completedDeliveries']++;
            }
            
            // Revenue 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['revenueByCity'][$cityName])) {
                    $stats['revenueByCity'][$cityName] = 0;
                    $stats['ordersByCity'][$cityName] = 0;
                }
                $stats['revenueByCity'][$cityName] += $orderAmount;
                $stats['ordersByCity'][$cityName]++;
            }
            
            // Check fulfillment type (simplified - would need vendor data for accurate count)
            if (isset($order['items']) && is_array($order['items'])) {
                foreach ($order['items'] as $item) {
                    if (isset($item['vendorId'])) {
                        $vendor = $this->common->readdatadocument('Vendors', $item['vendorId']);
                        if (!empty($vendor) && isset($vendor['fulfillment_type'])) {
                            if ($vendor['fulfillment_type'] == 'cannabus_inventory') {
                                $stats['cannabusInventoryOrders']++;
                            } elseif ($vendor['fulfillment_type'] == 'storefront_pickup') {
                                $stats['storefrontOrders']++;
                            }
                        }
                    }
                }
            }
        }
        
        $data['stats'] = $stats;
        $data['activeDrivers'] = $activeDrivers;
        
        // Get the date 7 days before for existing chart
        $seven_days_ago = date('Y-m-d', strtotime('-7 days'));
         $seven_days_agoms=strtotime($seven_days_ago)*1000;
        $tripsCount = $this->common->readdatafromcollectionbetween("Orders", "date", ">",$seven_days_agoms);
    //    echo "<pre>";
    //    print_r($tripsCount);
    //    echo "</pre>";
       
       
        $sales = array_fill_keys(range(0, 7), 0);  // 7 days
        $datearray=array();
        for ($i = 0; $i <= 6; $i++) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $datearray[$i]=$date;
            $nosales[$date]=0;
            $totalsale[$date]=0;
            $retailsale[$date]=0;
            $bookingcomplete[$date]=0;
        }
        $totalsales = array_fill_keys(range(0, 7), 0);  // 7 days
      
        foreach($tripsCount as $t=>$j){
            // echo "<pre>";
            // print_r($j);
            // echo "</pre>";
            $orderDate = $j['date'];
            $orderDateReadable = date('Y-m-d', $orderDate / 1000);
            $daysDifference = floor(($todayTimestamp - $orderDate) / (1000 * 60 * 60 * 24));
         
            $nosales[$orderDateReadable] = $nosales[$orderDateReadable]+$j['totalQuantity'];
            $totalsale[$orderDateReadable] = $totalsale[$orderDateReadable]+$j['displayPrice'];
            $retailsale[$orderDateReadable] = $retailsale[$orderDateReadable]+$j['price'];
            if($j['orderStatus']=="deliver" ||$j['orderStatus']=="delivered"||$j['orderStatus']=="rate"||$j['orderStatus']=="rated") {
                $bookingcomplete[$orderDateReadable]=$bookingcomplete[$orderDateReadable]+1;
            }
            // foreach ($j['productsData'] as $key=> $product) {
            //     $nosales[$daysDifference] += 1;

            // }
            
        }
      
        $data['datearray']=$datearray;
        $data['nosales']=$nosales;
        $data['totalsale']=$totalsale;
        $data['retailsale']=$retailsale;
        $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
                )
            )
        ));
    }
     
}
