<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Google\Cloud\Firestore\FirestoreClient;

class Admin_model extends CI_Model
{
    /**
     * Get all admin users
     */
    public function getall_admins()
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        $citiesRef = $db->collection('Admin');
        $documents = $citiesRef->documents();
        $output = array();
        
        foreach ($documents as $document) {
            if ($document->exists()) {
                $path = $document->id();
                $output[$path] = $document->data();
            }
        }
        
        return $output;
    }

    /**
     * Get single admin
     */
    public function get_admin($adminId)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
        
        try {
            $document = $db->collection('Admin')->document($adminId)->snapshot()->data();
            return $document;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Add new admin - Creates in both Firebase Auth and Firestore
     */
    public function add_admin($data)
    {
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();
        
        // Create user in Firebase Authentication
        $userProperties = [
            'email' => $data['email'],
            'emailVerified' => false,
            'password' => $data['password'],
            'displayName' => $data['fullName'],
            'disabled' => false,
        ];

        try {
            $createdUser = $auth->createUser($userProperties);
            $userId = $createdUser->uid;
        } catch (\Throwable $th) {
            log_message('error', 'Failed to create admin in Auth: ' . $th->getMessage());
            return false;
        }

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

        try {
            // Use the Auth UID as the document ID
            $docRef = $firestore->collection('Admin')->document($userId);
            
            // Remove password from Firestore data (it's in Auth)
           // unset($data['password']);
            $data['id'] = $userId;
            
            $docRef->set($data);
            return true;
        } catch (\Exception $e) {
            // Rollback - delete from Auth
            try {
                $auth->deleteUser($userId);
            } catch (\Exception $rollbackEx) {
                log_message('error', 'Rollback failed: ' . $rollbackEx->getMessage());
            }
            log_message('error', 'Failed to add admin to Firestore: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Update admin
     */
    public function update_admin($adminId, $data)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        try {
            $updateData = array();
            foreach ($data as $key => $value) {
                $d['path'] = $key;
                $d['value'] = $value;
                array_push($updateData, $d);
            }

            $docRef = $db->collection('Admin')->document($adminId);
            $docRef->update($updateData);
            return true;
        } catch (\Exception $e) {
            log_message('error', 'Failed to update admin: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Update admin password in Firebase Auth
     */
    public function update_password($adminId, $newPassword)
    {
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();
        
        try {
            $auth->changeUserPassword($adminId, $newPassword);
            return true;
        } catch (\Throwable $th) {
            log_message('error', 'Failed to update admin password: ' . $th->getMessage());
            return false;
        }
    }

    /**
     * Delete admin from Firestore
     */
    public function delete_admin($adminId)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        try {
            $docRef = $db->collection('Admin')->document($adminId);
            $docRef->delete();
            return true;
        } catch (\Exception $e) {
            log_message('error', 'Failed to delete admin from Firestore: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Delete admin from Firebase Auth
     */
    public function delete_admin_auth($adminId)
    {
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();

        try {
            $auth->deleteUser($adminId);
            return true;
        } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
            log_message('error', 'Admin not found in Auth: ' . $e->getMessage());
            return false;
        } catch (\Kreait\Firebase\Exception\AuthException $e) {
            log_message('error', 'Failed to delete admin from Auth: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get admin by email
     */
    public function get_admin_by_email($email)
    {
        $x = $this->config->item('firebase_app_key');
        $db = new FirestoreClient([
            'projectId' => 'stream-c7e91',
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);

        try {
            $citiesRef = $db->collection('Admin')->where('email', '=', $email);
            $documents = $citiesRef->documents();
            
            foreach ($documents as $document) {
                if ($document->exists()) {
                    return array(
                        'id' => $document->id(),
                        'data' => $document->data()
                    );
                }
            }
            
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }
}

