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

require __DIR__ . '/../../vendor/autoload.php';

use Kreait\Firebase\Factory;

class Firebase
{

    protected $config = array();
    public $factory;
    protected $messaging;


    public function __construct()
    {
        // Assign the CodeIgniter super-object
        //parent::_construct();
        $this->CI = &get_instance();

        //      $this->serviceAccount = ServiceAccount::fromJsonFile();
        $this->factory = (new Factory)->withServiceAccount($this->CI->config->item('firebase_app_key'))
            ->withDefaultStorageBucket("powerlift-1ab98.firebasestorage.app")
           ->withDatabaseUri('https://powerlift-1ab98-default-rtdb.firebaseio.com');
              $this->messaging = $this->factory->createMessaging();

    }

    public function init()
    {
        // $factory = (new Factory)->withServiceAccount($this->CI->config->item('firebase_app_key'))
        //     ->withDatabaseUri('https://gamebike-5b2dc-default-rtdb.firebaseio.com/');

        return $this->factory;
    }
  public function sendPushNotification($deviceToken, $title, $body, $data = [])
    {
        $message = [
            'token' => $deviceToken,
            'notification' => [
                'title' => $title,
                'body' => $body,
            ],
            'data' => $data,
            'android' => [
                'priority' => 'high', // Ensure high-priority for Android
                'notification' => [
                    'sound' => 'default', // Ensures sound plays on Android
                ],
            ],
            'apns' => [
                'headers' => [
                    'apns-priority' => '10', // Ensures high-priority delivery
                ],
                'payload' => [
                    'aps' => [
                        'sound' => 'default', // Ensures sound plays on iOS
                        'content-available' => 1,
                    ],
                ],
            ],
        ];
        // echo "<pre>";
        // var_dump($message);
        // echo "</pre>";
    
        try {
            $result = $this->messaging->send($message);
            return ['success' => true, 'result' => $result];
        } catch (\Kreait\Firebase\Exception\Messaging\NotFound $e) {
            return ['success' => false, 'error' => 'Token is not registered or invalid.'];
        } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        } catch (\Exception $e) {
            return ['success' => false, 'error' => 'An unexpected error occurred: ' . $e->getMessage()];
        }
    }
    

    public function sendPushNotification1($deviceToken, $title, $body, $data = [])
    {
        $message = [
            'token' => $deviceToken,
            'notification' => [
                'title' => $title,
                'body' => $body,
              
            ],
            'data' => $data,
            'payload' => [
        'aps' => [
            
            'sound' => 'default',
        ],
    ],
            
        ];
    
        try {
            $result = $this->messaging->send($message);
            return ['success' => true, 'result' => $result];
        } catch (\Kreait\Firebase\Exception\Messaging\NotFound $e) {
            // Handle unregistered tokens
            return ['success' => false, 'error' => 'Token is not registered or invalid.'];
        } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
            // Handle other Firebase exceptions
            return ['success' => false, 'error' => $e->getMessage()];
        } catch (\Exception $e) {
            // Handle general exceptions
            return ['success' => false, 'error' => 'An unexpected error occurred: ' . $e->getMessage()];
        }
    }
    public function sendPushNotificationToMultipleDevices($deviceTokens, $title, $body, $data = [])
{
    // Prepare the message payload
    $message = [
        'notification' => [
            'title' => $title,
            'body' => $body,
        ],
        'data' => $data,
        'tokens' => $deviceTokens, // Array of device tokens
    ];

    try {
        // Send the message to multiple devices
        $result = $this->messaging->sendMulticast($message,$deviceTokens);

        // Handle responses
        $successCount = $result->successes()->count();
        $failureCount = $result->failures()->count();
        $failedTokens = [];

        foreach ($result->failures()->getItems() as $failure) {
            $failedTokens[] = $failure->target()->value();
        }

        return [
            'success' => true,
            'successCount' => $successCount,
            'failureCount' => $failureCount,
            'failedTokens' => $failedTokens,
        ];
    } catch (\Kreait\Firebase\Exception\FirebaseException $e) {
        // Handle Firebase exceptions
        return ['success' => false, 'error' => $e->getMessage()];
    } catch (\Exception $e) {
        // Handle general exceptions
        return ['success' => false, 'error' => 'An unexpected error occurred: ' . $e->getMessage()];
    }
}

    public function getdatase()
    {
        //$database = $factory->createDatabase();

    }
}
