<?php

namespace App\Providers;

use App\Models\Loan;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if ($this->app->environment('production')) {
            URL::forceScheme('https');
        }

        // View Composer untuk semua view (*)
        View::composer('*', function ($view) {
            if (Auth::check()) {
                $user = Auth::user();
                
                // Fetch active loans to derive notifications
                $loans = Loan::with('book')
                    ->where('user_id', $user->id)
                    ->whereIn('status', ['Dipinjam', 'Terlambat'])
                    ->get();

                $notifikasi = collect();

                foreach ($loans as $loan) {
                    $dueAt = Carbon::parse($loan->due_at);
                    $sisaHari = (int) now()->diffInDays($dueAt, false);

                    if ($sisaHari < 0) {
                        $notifikasi->push([
                            'icon' => 'bi-exclamation-octagon-fill',
                            'color' => 'danger',
                            'title' => 'TERLAMBAT: ' . $loan->book->judul,
                            'content' => "Segera kembalikan buku. Denda berlaku.",
                            'time' => 'Sekarang',
                            'read' => false,
                            'type' => 'denda_active',
                        ]);
                    } elseif ($sisaHari <= 3) {
                        $notifikasi->push([
                            'icon' => 'bi-exclamation-triangle-fill',
                            'color' => 'warning',
                            'title' => 'Jatuh Tempo: ' . $loan->book->judul,
                            'content' => "Tersisa {$sisaHari} hari lagi.",
                            'time' => 'Segera',
                            'read' => false,
                            'type' => 'warning_jatuh_tempo',
                        ]);
                    }
                }

                $unreadCount = $notifikasi->where('read', false)->count();
                $view->with('notifikasi', $notifikasi);
                $view->with('unreadNotificationsCount', $unreadCount);
            } else {
                $view->with('notifikasi', collect([])); 
                $view->with('unreadNotificationsCount', 0);
            }
        });
    }
}
