<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
use Google\Cloud\Firestore\FirestoreClient;
class Common extends CI_Model{

    function get_firestore()
    {
        $x = $this->config->item('firebase_app_key');
        return new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
    }

    function adddatamodel($collectionname,$documentname,$data){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $cityRef = $firestore->collection($collectionname)->document($documentname);
  
    if($cityRef->set($data)){
        return true;
    }else{
        return false;
    }
 
  
    }

    function getAddress($latitude, $longitude)
    {
            //google map api url
            $API_KEY = "AIzaSyAe_Fm2ja1OuDHswu4mgZKQN9DRakGyzzs";
            $url = "https://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude&key=" . $API_KEY;
            // send http request
            $geocode = file_get_contents($url);
            $json = json_decode($geocode);
            $address = $json->results[0]->formatted_address;
            return $address;
    }

    public function mydate($startdate)
{
    $jana = array();
    $pos = 0;
    date_default_timezone_set('UTC');

    $currentDate = date($startdate);

    // Concatenate the time to the current date
    $startOfDayStr = $currentDate . ' 00:00:01';

    // Convert the datetime string to a timestamp
    $startOfDayTimestamp = strtotime($startOfDayStr);

    // Convert the timestamp to milliseconds
    $startdate = $startOfDayTimestamp * 1000;

    // Get the end of the day timestamp
    $endOfDayStr = $currentDate . ' 23:59:59';
    $endOfDayTimestamp = strtotime($endOfDayStr);
    $enddate = $endOfDayTimestamp * 1000;

    // Adding one day in milliseconds
    $oneDayInMilliseconds = 24 * 60 * 60 * 1000;
    $tomorrowStartdate = $startdate + $oneDayInMilliseconds;
   //   echo "start date:".  $startdate."ENd date:".$enddate;
      $data['startdate']=$startdate;
      $data['enddate']=$enddate;
      return $data;


    // Your existing logic here...
}
    function get_iechartdata()
    {
        $date = $this->createDateRangeArray(date('Y-m-d', strtotime('-5 day')), date('Y-m-d'));
        $arr  = array();
        foreach ($date as $key => $dates) {
         //   print_r($dates);
         $tella=  $this->mydate($dates);
        //  echo "<pre>";
        //  print_r($tella);
        //  echo "</pre>";  
         
         
         $income = 0;
            $expense = 0;
       $triplist = $this->readdatafromcollectionbetween("Bookings", "bookingDate" , ">", $tella['startdate'], "bookingDate" , "<", $tella['enddate']);
            if(!empty($triplist)) {
                foreach ($triplist as $tripId => $tripDetails) {
                    $income = $income + 1;
                }
            }
 /*
            $triplist = $this->readdatafromcollectionbetween("Bookings", "bookingDate" , ">", $tella['startdate'], "bookingDate" , "<", $tella['enddate']);
            if(!empty($triplist)) {
                foreach ($triplist as $tripId => $tripDetails) {
                    $expense = $expense + ((float)$tripDetails["price"] *80/100);
                }
   
                }
   */
                // $triplist = $this->readdatafromcollectionbetweenwhere("Payouts", "status" , "=", "paid", "completionTimeStamp" , ">", strtotime($dates)*1000, "completionTimeStamp" , "<", strtotime($dates)*86400000);
            // if(!empty($triplist)) {
            //     foreach ($triplist as $tripId => $tripDetails) {
            //         $expense = $expense + (float)$tripDetails["amount"];
            //     }
            // }
            $arr[$dates]['income']  = ($income) ? $income : 0;
     //       $arr[$dates]['expense'] = ($expense) ? $expense : 0;
            $income = 0;
            $expense = 0;
        }
        return $arr;
    }

    function createDateRangeArray($strDateFrom, $strDateTo)
    {
        $aryRange  = array();
        $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
        $iDateTo   = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
        if ($iDateTo >= $iDateFrom) {
            array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
            while ($iDateFrom < $iDateTo) {
                $iDateFrom += 86400; // add 24 hours
                array_push($aryRange, date('Y-m-d', $iDateFrom));
            }
        }
        return $aryRange;
    }


    function updatedatamodel($collectionname="",$documentname="",$data=""){
      
        $ceta=array();
        foreach ($data as $key => $value) {
            $d['path']=$key;
            $d['value']=$value;
array_push($ceta,$d);
        }

        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $cityRef = $firestore->collection($collectionname)->document($documentname);
   
    $cityRef->update($ceta);
    return true;
    }
   
    function deletedatamodel($collectionname,$documentname){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    if($firestore->collection($collectionname)->document($documentname)->delete()){
        return true;
    }else{
        return false;
    }
   

    }



    function readusername($documentname=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection("Users")->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {
        $j=$snapshot->data();
        return $j['firstName'] ." ".$j['lastName'];
    


    } else {
          return '';  
    }
    }


    function readusernamewithcarinfo($documentname=""){
        $x1=array();
        $x1['name']="";
        $x1['carType']="";
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection("Users")->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {
        $j=$snapshot->data();
        $x1['name']= $j['firstName'] ." ".$j['lastName']. " (".$j['userName'].")";
        $x1['carType']=$j['carType'];
          return $x1;

    } else {
          return $x1;  
    }
    }


    function readImage($documentname=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection("Users")->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {
        $j=$snapshot->data();
        return $j['image'];
    


    } else {
          return '';  
    }
    }



    function readdatadocument($collectionname ="",$documentname=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection($collectionname)->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {

        return $snapshot->data();
    } else {
          return '';  
    }
    }

    function readdatacollection($collectionname, $subCollectionname, $documentname){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

        if($subCollectionname !=""){
            $citiesRef = $db->collection($collectionname)->document($documentname)->collection($subCollectionname);
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname);    
            $documents = $citiesRef->documents();
        }

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }

    function readdatafromcollectionwhereclauseorderby($collectionname,$orderby,$collectionkey ="",$collectiontype = "",$collectionkeyvalue=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

        if($collectionkey !="" && $collectiontype !="" && $collectionkeyvalue !="" ){
            $citiesRef = $db->collection($collectionname)->orderByField($orderby)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname)->orderBy('timeStamp', 'DESC');    
            $documents = $citiesRef->documents();
        }

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }


    function readdatafromcollectionwhereclause($collectionname,$collectionkey ="",$collectiontype = "",$collectionkeyvalue=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

        if($collectionkey !="" && $collectiontype !="" && $collectionkeyvalue !="" ){
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname);    
            $documents = $citiesRef->documents();
        }

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }
        function readdatafromcollection3whereclause($collectionname,$collectionkey1 ="",$collectiontype1 = "",$collectionkeyvalue1="",$collectionkey2 ="",$collectiontype2 = "",$collectionkeyvalue2="",$collectionkey3 ="",$collectiontype3 = "",$collectionkeyvalue3=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

        
            $citiesRef = $db->collection($collectionname)->where($collectionkey1, $collectiontype1, $collectionkeyvalue1)
->where($collectionkey2, $collectiontype2, $collectionkeyvalue2)
->where($collectionkey3, $collectiontype3, $collectionkeyvalue3)

            ;    
            $documents = $citiesRef->documents();
        

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }

    function readdatafromcollectionbetween($collectionname,$collectionkey ="",$collectiontype = "",$collectionkeyvalue="", $collectionkey2 ="",$collectiontype2 = "",$collectionkeyvalue2=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
        if($collectionkey2 !="" && $collectiontype2 !="" && $collectionkeyvalue2 !="" ){
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue)->where($collectionkey2, $collectiontype2, $collectionkeyvalue2);    
            $documents = $citiesRef->documents();
        }elseif($collectionkey !="" && $collectiontype !="" && $collectionkeyvalue !="" ){
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname);    
            $documents = $citiesRef->documents();
        }

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }

    function readnumberofdocumentsincollectionbetween($collectionname,$collectionkey ="",$collectiontype = "",$collectionkeyvalue="", $collectionkey2 ="",$collectiontype2 = "",$collectionkeyvalue2=""){
        $citiesRef="";
        $documents="";
        $documentsCount=0;
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
        if($collectionkey2 !="" && $collectiontype2 !="" && $collectionkeyvalue2 !="" ){
            $citiesRef = $db->collection($collectionname)
            ->where($collectionkey, $collectiontype, $collectionkeyvalue)
            ->where($collectionkey2, $collectiontype2, $collectionkeyvalue2);    
            $documents = $citiesRef->documents();
        }elseif($collectionkey !="" && $collectiontype !="" && $collectionkeyvalue !="" ){
            echo $collectionname;
            echo "<br>";
            echo $collectionkey;
            echo "<br>";
            echo $collectiontype;
            echo "<br>";
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname);    
            $documents = $citiesRef->documents();
        }

        foreach ($documents as $document) {
           if ($document->exists()) {
                $documentsCount ++;
            }
        }

        return $documentsCount;
    }

    function readdatafromcollectionbetweenwhere($collectionname,$collectionkey ="",$collectiontype = "",$collectionkeyvalue="", $collectionkey2 ="",$collectiontype2 = "",$collectionkeyvalue2="", $collectionkey3 ="",$collectiontype3 = "",$collectionkeyvalue3=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
        $output=array();
        if($collectionkey3 !="" && $collectiontype3 !="" && $collectionkeyvalue3 !="" ){
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue)->where($collectionkey2, $collectiontype2, $collectionkeyvalue2);
            $documents = $citiesRef->documents();

                    foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                if ($document->data()['driverId'] == $collectionkeyvalue3) {
                    $output[$document->id()]=$document->data();
                }
            }
        }

        // ->where($collectionkey3, $collectiontype3, $collectionkeyvalue3);    
            // $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
                    foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }
        }

        
        return $output;
    }
    function readdatafromcollectionbetween2where($collectionname,$collectionkey ="",$collectiontype = "",$collectionkeyvalue="", $collectionkey2 ="",$collectiontype2 = "",$collectionkeyvalue2=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
        if($collectionkey2 !="" && $collectiontype2 !="" && $collectionkeyvalue2 !="" ){
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue)->where($collectionkey2, $collectiontype2, $collectionkeyvalue2);    
            $documents = $citiesRef->documents();
        }else{
            $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue);    
            $documents = $citiesRef->documents();
        }

        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }


    function readdatadocumentwithcondition($collectionname ="Settings",$documentname="testing",$where=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'staff-checkin-b4972',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection($collectionname)->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {

        return $snapshot->data();
    } else {
          return '';  
    }
    }




}



?>
