<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Kreait\Firebase\Factory;
class FirebaseServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this->app->singleton('firebase.firestore', function ($app) {
            $serviceAccountKey = \App\CentralLogics\Helpers::get_business_settings('push_notification_service_file_content')??[];
            if(is_array($serviceAccountKey) && !empty($serviceAccountKey['project_id']) && !empty($serviceAccountKey['client_email']) && !empty($serviceAccountKey['private_key'])){
                try {
                    $serviceAccount = $serviceAccountKey;
                    $serviceAccount['private_key'] = str_replace('\\n', "\n", $serviceAccount['private_key']);
                    return (new Factory)
                        ->withServiceAccount($serviceAccount)
                        ->createMessaging();
                } catch (\Throwable $e) {
                    \Illuminate\Support\Facades\Log::warning('Firebase firestore init failed: ' . $e->getMessage());
                    return false;
                }
            }
            return false;
        });

        $this->app->singleton('firebase.messaging', function ($app) {
            $serviceAccountKey = \App\CentralLogics\Helpers::get_business_settings('push_notification_service_file_content')??[];
            if(is_array($serviceAccountKey) && !empty($serviceAccountKey['project_id']) && !empty($serviceAccountKey['client_email']) && !empty($serviceAccountKey['private_key'])){
                try {
                    $serviceAccount = $serviceAccountKey;
                    $serviceAccount['private_key'] = str_replace('\\n', "\n", $serviceAccount['private_key']);
                    return (new Factory)
                        ->withServiceAccount($serviceAccount)
                        ->createMessaging();
                } catch (\Throwable $e) {
                    \Illuminate\Support\Facades\Log::warning('Firebase messaging init failed: ' . $e->getMessage());
                    return false;
                }
            }
            return false;
        });
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}
