<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Evento;
use App\Observers\EventoObserver;
use App\Services\NotificacionService;

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

    public function boot(): void
    {
        \Illuminate\Pagination\Paginator::useBootstrapFive();

        // Registrar observer del modelo Evento
        Evento::observe(EventoObserver::class);

        view()->composer('layouts.app', function ($view) {
            try {
                if (\Illuminate\Support\Facades\Schema::hasTable('sponsors')) {
                    $view->with('footerSponsors', \App\Models\Sponsor::where('activo', true)->orderBy('orden')->get());
                } else {
                    $view->with('footerSponsors', collect());
                }

                if (\Illuminate\Support\Facades\Schema::hasTable('torneos')) {
                    $view->with('navTorneos', \App\Models\Torneo::orderByDesc('fecha_inicio')->take(5)->get());
                } else {
                    $view->with('navTorneos', collect());
                }

                // Badge de notificaciones para el layout
                if (session()->has('user_logged_in') && \Illuminate\Support\Facades\Schema::hasTable('notificaciones')) {
                    $service = app(NotificacionService::class);
                    $view->with('notifCount', $service->contarNoLeidas(session('user_tipo'), session('user_id')));
                } else {
                    $view->with('notifCount', 0);
                }

            } catch (\Exception $e) {
                $view->with('footerSponsors', collect());
                $view->with('navTorneos', collect());
                $view->with('notifCount', 0);
            }
        });
    }
}

