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

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

    function addnextcollection($collectionname,$documentname,$subcollectionname,$subdocumentname,$data){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

        $cityRef = $firestore->collection($collectionname)->document($documentname)->collection($subcollectionname)->document($subdocumentname);
        $cityRef->set($data);
        return true;
    }
    public  function update_customerstatus($id, $status)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
		try {
            if($status=="disable"){
                $updatedUser = $auth->enableUser($id);
            }else{
                $updatedUser = $auth->disableUser($id);
            }
			return True;
		} catch (\Throwable $th) {
			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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    if($firestore->collection($collectionname)->document($documentname)->delete()){
        return true;
    }else{
        return false;
    }
   

    }

    function readunitname($documentname=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
             
    $docRef = $firestore->collection("units")->document($documentname);
    $snapshot = $docRef->snapshot();

    if ($snapshot->exists()) {
        $j=$snapshot->data();
        return $j['unit'] ." / ".$j['zone'];
    
    } else {
          return '';  
    }
    }

    function readusername($documentname=""){
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            '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['fullName'];
    


    } else {
          return '';  
    }
    }


    function readusernamewithcarinfo($documentname=""){
        $x1=array();
        $x1['name']="";
        $x1['carType']="";
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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 deletedatamodelwithauth($collectionname,$documentname){
        $firebase = $this->firebase->init();
            $db = $firebase->createDatabase();
            $auth = $firebase->createAuth();
        
        $x=$this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);
        $auth = $firebase->createAuth();
        $auth->deleteUser($documentname);
        $firestore->collection($collectionname)->document($documentname)->delete();
        return true;
    }
    public function updatedatawithauth($collectionname,$data){
        
        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createDatabase();
            $auth = $firebase->createAuth();
        
            $x=$this->config->item('firebase_app_key');
            $firestore = new FirestoreClient([
                'projectId' => 'stream-c7e91',
                'keyFile' =>json_decode(file_get_contents($x), true)
              ]);
              if (!empty($data['password'])) {
                $auth->changeUserPassword($data['id'], $data['password']);
            }

        
       $res=$this->updatedatamodel($collectionname,$data['id'],$data);
        
            return [
                'success' => true,
                'message' => 'User Update and data added successfully.',
                'userId' => $res
            ];
        } catch (\Kreait\Firebase\Exception\AuthException $e) {
            return [
                'success' => false,
                'message' => 'Firebase Auth error: ' . $e->getMessage()
            ];
        } catch (\Throwable $e) {
            return [
                'success' => false,
                'message' => 'General error: ' . $e->getMessage()
            ];
        }
    }   
   public function adddatawithauth($collectionname,$data){
    try {
    $firebase = $this->firebase->init();
    $db = $firebase->createDatabase();
    $auth = $firebase->createAuth();

    $x=$this->config->item('firebase_app_key');
    $firestore = new FirestoreClient([
        'projectId' => 'stream-c7e91',
        'keyFile' =>json_decode(file_get_contents($x), true)
      ]);
      if (empty($data['email']) || empty($data['password'])) {
        throw new Exception("Email and password are required.");
    }

    $userProperties = [
        'email' => $data['email'],
        'emailVerified' => false,
        'password' => $data['password'],
        'displayName' => $data['name'] ?? 'User',
        'disabled' => false,
    ];

     $createdUser = $auth->createUser($userProperties);
    $userId = $createdUser->uid;
    $firestore->collection($collectionname)->document($userId)->create($data);

    return [
        'success' => true,
        'message' => 'User created and data added successfully.',
        'userId' => $userId
    ];
} catch (\Kreait\Firebase\Exception\AuthException $e) {
    return [
        'success' => false,
        'message' => 'Firebase Auth error: ' . $e->getMessage()
    ];
}catch (\Google\Cloud\Core\Exception\GoogleException $e) {
    return [
        'success' => false,
        'message' => 'Firestore error: ' . $e->getMessage()
    ];
} catch (\Throwable $e) {
    return [
        'success' => false,
        'message' => 'General error: ' . $e->getMessage()
    ];
}
}   
public function addnewUser($input)
{
    $firebase = $this->firebase->init();
    $db = $firebase->createDatabase();
    $auth = $firebase->createAuth();

    $input['password']="Welcome";
  

    $userProperties = [
        'email' => $input['email'],
        'emailVerified' => false,
        'password' => $input['password'], // ensure password is passed
        'displayName' => $input['first_name'] ?? 'User',
        'disabled' => false,
    ];

    try {
        $tello['identityType']=$input['type_identification'];
        $tello['officialId']=$input['identification'];
        $tello['firstName']=$input['first_name'];
        $tello['lastName']=$input['first_last_name'];
        $tello['seondLastName']=$input['sec_last_name'];
        $tello['fullName']=$input['first_name']. " ".$input['first_last_name']." ".$input['sec_last_name'];
        $tello['email']=$input['email'];
        $tello['password']=$input['password'];
        $tello['phone']=$input['primary_phone'];
        $tello['additionalPhone']=$input['additional_phone'];
        $tello['adminPrivileges']=$input['admin_privileges'];
        $tello['disableFinances']=$input['finance'];
        //$tello['floor']=$input['zone'];
       // $tello['houseNo']=$input['unit'];
        $tello['userType']=$input['user_type'];
        $tello['approved']=true;
        $tello['createdAt']=time()*1000;


       
        
        
        //phone

        // 1. Create Firebase Auth User
        $createdUser = $auth->createUser($userProperties);

        // 2. Sign in to get the UID
        $signInResult = $auth->signInWithEmailAndPassword($userProperties['email'], $userProperties['password']);
        $authData = $signInResult->data();
       
        $userId = $authData['localId'];
        $tello['userId']=$userId;

        // 3. Store in Firestore 'Users' collection
        $x = $this->config->item('firebase_app_key');
        $firestore = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $firestore->collection('Users')->document($userId)->create($tello);
        
        // 4. Proceed with Unit logic
        $unit = $input['unit'];
        $zone = $input['zone'];
        $userType = $input['user_type'];
        $unitsRef = $firestore->collection('units');
        $query = $unitsRef->where('unit', '=', $unit)->where('zone', '=', $zone)->documents();  
        

        if (!$query->isEmpty()) {
            $existingDoc = $query->rows()[0];
            $docRef = $existingDoc->reference();
            $existingData = $existingDoc->data();

            if ($userType === "owner" || $userType === "tenant") {
                // Rollback
                $auth->deleteUser($userId);
                $firestore->collection('Users')->document($userId)->delete();
                $shama['success']=false;
                 $shama['message']='Owner/Tenant already exists';
                // echo json_encode(['success' => false, 'message' => 'Owner/Tenant already exists']);
                return $shama;
            }

            if ($userType === "cohost" && in_array($userId, $existingData['cohost'] ?? [])) {
                // Rollback
                $auth->deleteUser($userId);
                $firestore->collection('Users')->document($userId)->delete();
                 $shama['success']=false;
                 $shama['message']='Cohost already exists';
                 return $shama;
            }

            // Add cohost to array
            $cohosts = $existingData['cohost'] ?? [];
            $cohosts[] = $userId;
            $docRef->update([
                ['path' => 'cohost', 'value' => array_unique($cohosts)]
            ]);
             $shama['success']=true;
                 $shama['message']='Cohost added successfully';
                 return $shama;


        } else {
            if ($userType === "cohost") {
                // Rollback
                $auth->deleteUser($userId);
                $firestore->collection('Users')->document($userId)->delete();
                  $shama['success']=false;
                 $shama['message']='Add owner/tenant first';
                 return $shama;
            }

            $unitData = [
                'zone' => $zone,
                'unit' => $unit,
                'owner' => $userType === 'owner' ? $userId : '',
                'tenant' => $userType === 'tenant' ? $userId : '',
                'cohost' => [],
            ];

            $firestore->collection('units')->add($unitData);
                 $shama['success']=true;
                 $shama['message']='User and unit created';
                 return $shama;
        }

    } catch (\Throwable $e) {
        if (isset($userId)) {
            $auth->deleteUser($userId);
            $firestore->collection('Users')->document($userId)->delete();
        }

         $shama['success']=false;
                 $shama['message']=$e->getMessage();
                 return $shama;

    }
}

   function addnewUserold($input) {
    $firebaseKeyPath = $this->config->item('firebase_app_key');
    $db = new FirestoreClient([
        'projectId' => 'stream-c7e91',
        'keyFile' => json_decode(file_get_contents($firebaseKeyPath), true)
    ]);

    $zone = $input['zone'];
    $unit = $input['unit'];
    $userType = $input['user_type'];

    // Mock user ID for now (you should generate/store this from Firestore user document creation)
    $userId = uniqid('user_');

    $unitsRef = $db->collection('units');
    $query = $unitsRef->where('unit', '=', $unit)->where('zone', '=', $zone)->documents();
    

    if (!$query->isEmpty()) {
        // Unit exists – update logic
        $existingDoc = $query->rows()[0];
        $existingData = $existingDoc->data();
        $docRef = $existingDoc->reference();
/*
        if ($userType == "owner" && !empty($existingData['owner'])) {
            echo json_encode(['success' => false, 'message' => 'Owner already exists in this unit']);
            return;
        }

        if ($userType == "tenant" && !empty($existingData['tenant'])) {
            echo json_encode(['success' => false, 'message' => 'Tenant already exists in this unit']);
            return;
        }
*/
        if($userType == "owner" || $userType == "tenant"){
               echo json_encode(['success' => false, 'message' => 'Owner/Tenant already exists in this unit Only add Cohsot']);
            return;
            
        }
        if ($userType == "cohost" && in_array($userId, $existingData['cohost'] ?? [])) {
            echo json_encode(['success' => false, 'message' => 'Cohost already exists in this unit']);
            return;
        }

        // Update existing unit
        $updateData = [];
        if ($userType == "cohost") {
            $cohosts = $existingData['cohost'] ?? [];
            $cohosts[] = $userId;
            $updateData['cohost'] = array_unique($cohosts);
        }

        $docRef->update(array_map(function($k, $v) {
            return ['path' => $k, 'value' => $v];
        }, array_keys($updateData), $updateData));

        echo json_encode(['success' => true, 'message' => 'User added to existing unit']);
        return;

    } else {
        if($userType == "cohost"){
               echo json_encode(['success' => false, 'message' => ' 1st Owner/Tenant then You Can add Cohsot']);
            return;
            
        }
        // Unit does not exist – create new unit document
        $unitData = [
            'zone' => $zone,
            'unit' => $unit,
            'owner' => $userType === 'owner' ? $userId : '',
            'tenant' => $userType === 'tenant' ? $userId : '',
            'cohost' => $userType === 'cohost' ? [$userId] : []
        ];

        $newDocId = rand() . time() . rand();
        $db->collection('units')->document($newDocId)->set($unitData);

        echo json_encode(['success' => true, 'message' => 'Unit created and user added']);
        return;
    }
}

function readdatafromcollectionwhereclauseorderbyandlimit($collectionname,$orderby,$collectionkey ="",$collectiontype = "",$collectionkeyvalue="",$limit=10){
    $citiesRef="";
    $documents="";
    $x=$this->config->item('firebase_app_key');
    $db = new FirestoreClient([
        'projectId' => 'stream-c7e91',
        'keyFile' =>json_decode(file_get_contents($x), true)
      ]);

    if($collectionkey !="" && $collectiontype !="" && $collectionkeyvalue !="" ){
        $citiesRef = $db->collection($collectionname)->where($collectionkey, $collectiontype, $collectionkeyvalue)->limit($limit);
        ;    
        $documents = $citiesRef->documents();
    }else{
        $citiesRef = $db->collection($collectionname)->limit($limit);
        ;    
        $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 = "", $limit = 5) {
    $citiesRef = "";
    $documents = "";
    $x = $this->config->item('firebase_app_key');
    $db = new FirestoreClient([
        'projectId' => 'stream-c7e91',
        'keyFile' => json_decode(file_get_contents($x), true)
    ]);

    // Check if the collection has the where clause
    if ($collectionkey != "" && $collectiontype != "" && $collectionkeyvalue != "") {
        // Build query with where clause and order by the specified field
        $citiesRef = $db->collection($collectionname)
            ->where($collectionkey, $collectiontype, $collectionkeyvalue)
          //  ->orderBy($orderby, 'DESC');  // Add orderBy with DESC (or ASC as needed)
            ->limit($limit);
        $documents = $citiesRef->documents();
    } else {
        // No where clause, order by 'timeStamp' by default
        $citiesRef = $db->collection($collectionname)
            ->orderBy('timeStamp', 'DESC')  // Default ordering by timeStamp
            ->limit($limit);
        $documents = $citiesRef->documents();
    }

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

    return $output;
}

    function readdatafromcollectionorderby($collectionname,$orderby,$limit=5){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

            $citiesRef = $db->collection($collectionname)->limit($limit)->orderBy($orderby, 'DESC');    
            $documents = $citiesRef->documents();
      
        $output=array();
        
        foreach ($documents as $document) {
           if ($document->exists()) {
                $j=array();
                $output[$document->id()]=$document->data();
            }
        }

        return $output;
    }
    function nextedreaddatafromcollectionwhereclause($collectionname, $doc, $collection1)
{
    $x = $this->config->item('firebase_app_key');
    $keyData = json_decode(file_get_contents($x), true);

    if (!$keyData) {
        die("Invalid Firebase credentials.");
    }

    $firestore = new FirestoreClient([
        'projectId' => 'stream-c7e91',
        'keyFile' => $keyData
    ]);

    $parentDoc = $firestore->collection($collectionname)->document($doc)->snapshot();

    if (!$parentDoc->exists()) {
        echo "Parent document does not exist: $doc";
        return [];
    }

    $citiesRef = $firestore
        ->collection($collectionname)
        ->document($doc)
        ->collection($collection1);

    $documents = $citiesRef->documents([
        'retries' => 1,
        'timeoutMillis' => 5000
    ]);

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

    return $output;
}

    function readnextcollection($collectionname,$doc ="",$subcollectionname=""){
        $citiesRef="";
        $documents="";
        $x=$this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' =>json_decode(file_get_contents($x), true)
          ]);

            $citiesRef = $db->collection($collectionname)->document($doc)->collection("Conversations");    
            $documents = $citiesRef->documents();

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

        return $output;
    }

    function readdatafromcollectionWithPagination($collectionname, $orderBy = 'createdDate', $direction = 'DESC', $page = 1, $perPage = 10, $whereConditions = [])
    {
        $page = max(1, (int)$page);
        $perPage = max(1, (int)$perPage);
        $direction = strtoupper($direction) === 'ASC' ? 'ASC' : 'DESC';
        $offset = ($page - 1) * $perPage;

        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $query = $db->collection($collectionname);

        if (!empty($whereConditions) && is_array($whereConditions)) {
            foreach ($whereConditions as $condition) {
                if (!isset($condition['field'], $condition['operator'], $condition['value'])) {
                    continue;
                }
                $query = $query->where($condition['field'], $condition['operator'], $condition['value']);
            }
        }

        $orderInstructions = [];
        if (is_array($orderBy)) {
            foreach ($orderBy as $order) {
                if (!isset($order['field'])) {
                    continue;
                }
                $orderInstructions[] = [
                    'field' => $order['field'],
                    'direction' => isset($order['direction']) && strtoupper($order['direction']) === 'ASC' ? 'ASC' : 'DESC'
                ];
            }
        } else {
            $orderInstructions[] = [
                'field' => $orderBy,
                'direction' => $direction
            ];
        }

        foreach ($orderInstructions as $order) {
            $query = $query->orderBy($order['field'], $order['direction']);
        }

        if ($offset > 0) {
            $query = $query->offset($offset);
        }

        $query = $query->limit($perPage + 1);
        $documents = $query->documents();

        $items = [];
        $count = 0;
        $hasMore = false;

        foreach ($documents as $document) {
            if (!$document->exists()) {
                continue;
            }

            if ($count >= $perPage) {
                $hasMore = true;
                break;
            }

            $data = $document->data();
            $data['id'] = $document->id();

            if (!isset($data[$orderBy])) {
                try {
                    $data[$orderBy] = $document->get($orderBy);
                } catch (Exception $e) {
                    $data[$orderBy] = null;
                }
            }

            $items[] = $data;
            $count++;
        }

        return [
            'items'   => $items,
            'hasMore' => $hasMore,
            'page'    => $page,
            'perPage' => $perPage,
        ];
    }

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

        if($collectionkey !="" && $collectiontype !=""  ){
            $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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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();
        }

        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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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' => 'stream-c7e91',
            '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 '';  
    }
    }




}



?>
