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

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Exception\Messaging\NotFound;
use Kreait\Firebase\Exception\MessagingException;

#[\AllowDynamicProperties]
class Notifications
{
    protected $CI;
    protected $firebase = null;
    protected $tosend;

    public function __construct()
    {
        $this->CI = &get_instance();
        $this->CI->load->model('CommonModel');

        try {
            if (class_exists(Factory::class)) {
                $serviceAccountPath = $_SERVER['DOCUMENT_ROOT'].'/google_key/webtrix-report-firebase-adminsdk-a3qcw-c4d1f742dd.json';
                if (file_exists($serviceAccountPath)) {
                    $this->firebase = (new Factory())->withServiceAccount($serviceAccountPath);
                    log_message('debug', 'Firebase initialized successfully.');
                } else {
                    log_message('error', 'Firebase service account file not found: '.$serviceAccountPath);
                }
            } else {
                log_message('error', 'Firebase PHP SDK not installed.');
            }
        } catch (\Exception $e) {
            log_message('error', 'Firebase initialization failed: '.$e->getMessage());
        }
    }

    public function sendmessage($data, $tosend)
    {
        $this->tosend = $tosend;

        // Ensure Firebase is available before proceeding
        if (empty($this->firebase)) {
            log_message('error', 'Firebase not initialized. Notification not sent.');
            return false;
        }

        $token = $this->getRegisterUserToken();
        if (empty($token)) {
            log_message('error', 'No valid FCM token found for adminID: '.$tosend);
            return false;
        }

        try {
            $notification = Notification::create($data['title'] ?? 'Notification', $data['body'] ?? '');
            $message = CloudMessage::withTarget('token', $token)->withNotification($notification);

            $messaging = $this->firebase->createMessaging();
            $messaging->send($message);

            log_message('debug', 'Firebase notification sent successfully to token: '.$token);
            return true;
        } catch (NotFound $e) {
            log_message('error', 'Firebase token not found or invalid: '.$e->getMessage());
        } catch (MessagingException $e) {
            log_message('error', 'Firebase messaging error: '.$e->getMessage());
        } catch (\Exception $e) {
            log_message('error', 'Firebase general error: '.$e->getMessage());
        }

        return false;
    }

    private function getRegisterUserToken()
    {
        $where = array("adminID" => $this->tosend);
        $tDetails = $this->CI->CommonModel->getMasterDetails('admin', 'gfcmToken', $where);
        if (!empty($tDetails) && !empty($tDetails[0]->gfcmToken)) {
            return $tDetails[0]->gfcmToken;
        }
        return null;
    }
}
