<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void {}

    public function boot(): void
    {
        \App\Models\Job::observe(\App\Observers\JobObserver::class);
        \App\Models\Lead::observe(\App\Observers\LeadObserver::class);
        \App\Models\Quote::observe(\App\Observers\QuoteObserver::class);
        \App\Models\Contract::observe(\App\Observers\ContractObserver::class);

        \Illuminate\Pagination\Paginator::useBootstrapFive();

        // Share unread notification count + recent notifications + nav permissions with the layout.
        View::composer('layouts.app', function ($view) {
            if (! auth()->check()) return;

            $user   = auth()->user();
            $userId = $user->id;

            $unreadCount = \App\Models\CrmNotification::where('user_id', $userId)
                ->whereNull('read_at')
                ->count();

            $recentNotifs = \App\Models\CrmNotification::where('user_id', $userId)
                ->orderByDesc('created_at')
                ->take(8)
                ->get();

            $view->with('recentNotifs', $recentNotifs);
            $view->with('unreadCount', $unreadCount);

            // Build a permission map for sidebar visibility (single query for non-admin roles).
            $allNavKeys = [
                'leads.view', 'jobs.view', 'contacts.view', 'calendar.view', 'calendar.manage',
                'quotes.view', 'contracts.view', 'materials.view',
                'check_measure.view', 'processing.view',
                'delivery.view', 'installation.view', 'completion.view',
                'purchase_orders.view', 'inventory.view',
                'timesheet.view', 'timesheet.admin',
                'staff_invoices.view', 'staff_invoices.approve',
                'reports.view',
            ];

            if ($user->role?->name === 'office_admin') {
                $navPerms = array_fill_keys($allNavKeys, true);
            } elseif ($user->role_id) {
                $dbPerms  = \App\Models\RolePermission::where('role_id', $user->role_id)
                    ->whereIn('permission', $allNavKeys)
                    ->pluck('granted', 'permission')
                    ->toArray();
                // Keys absent from DB default to false (no implicit grant for nav items).
                $navPerms = array_merge(array_fill_keys($allNavKeys, false), array_map('boolval', $dbPerms));
            } else {
                $navPerms = array_fill_keys($allNavKeys, false);
            }

            $view->with('navPerms', $navPerms);
        });
    }
}
