<?php

//require_once ROOT . DS . 'app' . DS . 'Vendor' . DS . 'firebase'. DS . 'autoload.php';
require_once ROOT . DS . 'app' . DS . 'Vendor'  . DS . 'vendor' . DS . 'autoload.php';
use Kreait\Firebase\Factory;
use Kreait\Firebase\Contract\Auth;
use Kreait\Firebase\Contract\Firestore;
use Kreait\Firebase\Messaging\CloudMessage;

use Kreait\Firebase\Auth\UserQuery;

class Firebase
{


    private static $instance = null;
    private $factory;
    private $auth;
    private $firestore;

    private function __construct()
    {
        $json_file_dir = ROOT . DS . 'app' . DS . 'Vendor' . DS . FIREBASE_JSON_FILE;
        //putenv("GOOGLE_APPLICATION_CREDENTIALS=" . $json_file_dir);


        try {
            // Ensure the JSON file exists and is readable
            if (!file_exists($json_file_dir) || !is_readable($json_file_dir)) {
                return false;
                throw new Exception("Service account JSON file not found or unreadable at: $json_file_dir");

            }

            // Create the Firebase factory with the service account JSON file
            $this->factory = (new Factory)->withServiceAccount($json_file_dir);

            // Create the authentication and messaging services
            $auth = $this->factory->createAuth();
            $messaging = $this->factory->createMessaging();

            $this->auth = $auth;
            $this->messaging = $messaging;
        } catch (\Throwable $e) {
            // Handle the error and rethrow it as needed
            return false;
            throw new Exception("Failed to initialize Firebase services: " . $e->getMessage());
        }


    }
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Firebase();
        }
        return self::$instance;
    }


    public function sendPushNotification($notification){


        try {
        $message = CloudMessage::fromArray([
            'token' => $notification['to'],
            'notification' => $notification['notification'], // optional
            'data' => $notification['data'], // optional
        ]);
        $r =  $this->messaging->send($message);
        return true;
        } catch (\Kreait\Firebase\Exception\MessagingException $e) {
            //echo 'Messaging Exception: ' . $e->getMessage();
            return false;

        } catch (\Exception $e) {
            //echo 'General Exception: ' . $e->getMessage();
            return false;
        }
    }

     function getFirebaseInfoAgainstUID($fuid){
         try {
             $users = $this->auth->getUser($fuid);
             $provider_id = $users->providerData[0]->providerId;

        return $provider_id;


         }    catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
           return false;
}


       return $users;

    }
    function postVideoToFirestore($video_data)
    {

        try {
            $collectionName = 'video_summaries';

            // Get a reference to the collection
            $collection = $this->firestore->collection($collectionName);

            // Set the document data
            $collection->add($video_data);
            return true;

        } catch (\Google\Cloud\Core\Exception\ServiceException $e) {

            return false;
        } catch (\Exception $e) {
           return false;
        }


    }

    function deleteVideoFromFirestore($video_id)
    {







        $collectionName = 'video_summaries';



// Get a reference to the collection and document
        $document =  $this->firestore->collection($collectionName);

// Set the document data
        $query = $document->where('video_id', '==', (int)$video_id);

// Execute the query
        $snapshot = $query->documents();
        foreach ($snapshot as $document) {


            if ($document->exists()) {

               $document->reference()->delete();
              return true;
            }
        }

        return true;



    }



  /*  function deleteVideoFromFirestores($video_id)
    {

        $json_file_dir = ROOT . DS . 'app' . DS . 'Vendor' . DS . FIREBASE_JSON_FILE;
        putenv("GOOGLE_APPLICATION_CREDENTIALS=" . $json_file_dir);


        $projectId = 'foodtok-26e78';
        $firestore = new FirestoreClient([
            'projectId' => $projectId,
        ]);

        $collectionName = 'videosummeries2';
        $documentId = 'myDocument';
        $data = [
            'field1' => 'value1',
            'field2' => 'value2',
        ];

// Get a reference to the collection and document
        $document = $firestore->collection($collectionName);


// Set the document data
        $document->add($data);

        echo 'Document added to collection!';
        die();


        $collectionReference = $firestore->collection('video_summaries');
        $documentId = '003ea3c8-abe2-41fa-920c-ea1210b2835b';

// Retrieve the specific document
        $documentReference = $collectionReference->document($documentId);
        $documentSnapshot = $documentReference->snapshot();
pr($documentSnapshot);
        /*$documentReference = $collectionReference->document($userId);
        $snapshot = $documentReference->snapshot();

        echo "Hello " . $snapshot['firstName'];

    }*/
    public function testEmail($email)
    {


        $actionCodeSettings = [
            'continueUrl' => 'https://www.foodtok.com/verify-email?code=1234',
            'handleCodeInApp' => true,
            'dynamicLinkDomain' => 'https://www.foodtok.com',
            'androidPackageName' => 'com.foodtok.app',
            'androidMinimumVersion' => '12',
            'androidInstallApp' => true,
            'iOSBundleId' => 'com.foodtok.app',
        ];
        try {
            $this->auth->sendEmailVerificationLink($email);
        }catch (Exception $e) {
            return $e->getMessage();
        }

    }


    public  function getUserDetailsAgainstEmail($email)
    {
        try {
            $user = $this->auth->getUserByEmail($email);
            return $user;

        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
            return false;
        }

    }

    public  function getUserDetailsAgainstUID($uid)
    {
        try {
            $user = $this->auth->getUser($uid );


            return $user;

        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
            return false;
        }

    }
    public function createUser($data)
    {
        $userProperties = [
            'email' => $data['email'],
            'emailVerified' => false,
            //'phoneNumber' => '+15555550100',
            'password' => '123456',
            'displayName' => $data['first_name'].' '.$data['last_name'],
            //'photoUrl' => $data['profile_pic'],
            'disabled' => false,
        ];

        $createdUser = $this->auth->createUser($userProperties);
        return $createdUser;
    }

    public function deleteUser($uid)
    {


        try {
            $this->auth->deleteUser($uid);
        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
                //echo $e->getMessage();
            return false;
            } catch (\Kreait\Firebase\Exception\AuthException $e) {
                return true;
}
    }

    public  function changePassword($uid,$password)
    {


        try {
           return $this->auth->changeUserPassword($uid,$password);
            $updatedUser = $this->enableUser($uid);
        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
            //echo $e->getMessage();
            return false;
        } catch (\Kreait\Firebase\Exception\AuthException $e) {
            return true;
        }
    }


}

//$factory = $this->factory;
// $users =  $this->auth->listUsers($defaultMaxResults = 1000, $defaultBatchSize = 1000);
//pr($users);

/* $userProperties = [
      'email' => 'user@example.com',
      'emailVerified' => false,
      'phoneNumber' => '+15555550100',
      'password' => 'secretPassword',
      'displayName' => 'John Doe',
      'photoUrl' => 'http://www.example.com/12345678/photo.png',
      'disabled' => false,
  ];

  $createdUser = $this->auth->createUser($userProperties);
  pr($createdUser);
 // return $factory->createDatabase();*/

?>