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

	 function __construct()
     {
          parent::__construct();
          $this->load->database();
          $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()
     {
        //    $data["employsCount"] = $this->common->readnumberofdocumentsincollectionbetween("Employs");
        //    $data["driversCount"] = $this->common->readnumberofdocumentsincollectionbetween("Users", "userRole", "=", "driver");
        //    $data["customersCount"] = $this->common->readnumberofdocumentsincollectionbetween("Users", "userRole", "=", "user");
        //    $data["tripsCount"] = $this->common->readnumberofdocumentsincollectionbetween("Bookings", "bookingDate", ">", strtotime(date("Y/m/d"))*1000 , "bookingDate", "<", time()*1000);
        //    $data["bookings"] = $this->common->readdatafromcollectionbetween("Bookings", "bookingDate" , ">", strtotime(date("Y/m/d"))*1000, "bookingDate" , "<", time()*1000);
           
        //    $data['reminderlist']= $this->common->readdatafromcollectionwhereclause("Reminder");
        //    $data['drivers'] = $this->common->readdatafromcollectionwhereclause("Users", "userRole", "=", "driver");
     
        $today = date('Y-m-d');
         $todayms=strtotime($today)*1000;
         $todayTimestamp = strtotime('today') * 1000;

        // Get the date 7 days before
        $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'));
	}
     
}
