<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Hash;
use App\Hashing\PBKDF2Hasher;
use App\Services\EAN13Service;
use App\Models\Compra;
use App\Models\DetalleCompra;
use App\Observers\CompraObserver;
use App\Observers\ProductoObserver;
use App\Observers\ProductVariantObserver;
use App\Observers\DetalleCompraObserver;
use App\Models\Producto;
use App\Models\ProductVariant;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton(EAN13Service::class, function ($app) {
            return new EAN13Service();
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        app()->setLocale('es');
        
        Compra::observe(CompraObserver::class);
        Producto::observe(ProductoObserver::class);
        ProductVariant::observe(ProductVariantObserver::class);
        DetalleCompra::observe(DetalleCompraObserver::class);

        // Usar el hasher personalizado para todo el sistema
        Hash::extend('custom', function () {
            return new PBKDF2Hasher();
        });

        try {
            if (Schema::hasTable('settings')) {
                $setting = Setting::first();
                if ($setting) {
                    // Aquí se actualizan los valores de configuración de Filament
                    Config::set('filament.brand.logo', $setting->logo ? Storage::url($setting->logo) : null);
                    Config::set('filament.brand.colors.primary', $setting->primary_color ?? '#3498db');
                    Config::set('filament.brand.colors.secondary', $setting->secondary_color ?? '#2ecc71');
                }
            }
        } catch (\Exception $e) {
            Log::warning('Skipping settings load in AppServiceProvider: ' . $e->getMessage());
        }
    }

}
