<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $serviceAccountPath = storage_path('app/firebase/service-account.json');



        $this->app->singleton(Messaging::class, function () use ($serviceAccountPath) {
            // Check if the file exists and is readable
            if (file_exists($serviceAccountPath) && is_readable($serviceAccountPath)) {
                try {
                    return (new Factory)
                        ->withServiceAccount($serviceAccountPath)
                        ->createMessaging();
                } catch (\Exception $e) {
                    Log::error("Failed to initialize Firebase Messaging: " . $e->getMessage());
                    return null; // Return null if Firebase initialization fails
                }
            }

            // If file is missing or unreadable, log and return null
            Log::info("Firebase service account file not found or not readable at: {$serviceAccountPath}. Skipping Firebase Messaging initialization.");
            return null;
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if(Schema::hasTable('settings'))
        {

            Schema::defaultStringLength(191);

            //if have stripe payment gateway then set cashier config file
            if(!empty(setting('apps.stripe_public_key')) && !empty(setting('apps.stripe_secret_key')))
            {   
                config(['cashier.key' => setting('apps.stripe_public_key')]);
                config(['cashier.secret' => setting('apps.stripe_secret_key')]);
                config(['cashier.webhook.secret' => setting('apps.stripe_webhook_secret_key')]);

            }

            
            config(['paystack.publicKey' => setting('apps.paystack_public_key') ]);
            config(['paystack.secretKey' => setting('apps.paystack_secret_key') ]);
            config(['paystack.paymentUrl' => 'https://api.paystack.co' ]);
            config(['paystack.merchantEmail' => setting('apps.paystack_merchant_email')]);

            config(['app.timezone' => setting('regional.timezone_default')]);

            // set openai api key
            $openai_api_key = setting('ai.openai_api_key') ?: env('OPENAI_API_KEY', false);
            config(['openai.api_key' => $openai_api_key]);

            if($this->app->environment('production')) {
                \URL::forceScheme('https');
            }
        }

    }
}
