<?php

namespace App\Providers;

use App\Models\Tenants\Tenant;
use App\Services\ApprovalService;
use App\Services\Sales\BusinessCardRequestService;
use App\Services\Sales\SalesManagerService;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // 모든 뷰에 테넌트 목록 공유 (전역용)
        View::composer('*', function ($view) {
            if (auth()->check()) {
                // 테넌트가 선택되지 않은 경우 자동으로 HQ 테넌트 설정
                if (! session('selected_tenant_id')) {
                    $hqTenant = auth()->user()->getHQTenant();
                    if ($hqTenant) {
                        session(['selected_tenant_id' => $hqTenant->id]);
                    }
                }

                $globalTenants = Tenant::active()
                    ->orderBy('company_name')
                    ->get(['id', 'company_name', 'code']);

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

        // 사이드바 메뉴 뱃지 데이터 (전역 공유 - Blade 컴포넌트에서도 접근 가능)
        // ⚠️ 모든 뱃지를 이 한 곳에서 통합 관리 (View::share 덮어쓰기 방지)
        View::composer('partials.sidebar', function ($view) {
            $menuBadges = [
                'byRoute' => [],
                'byUrl' => [],
            ];

            if (auth()->check()) {
                // ── 영업 뱃지 ──
                try {
                    $salesManagerService = app(SalesManagerService::class);
                    $approvalStats = $salesManagerService->getApprovalStats();

                    if ($approvalStats['pending'] > 0) {
                        $menuBadges['byRoute']['sales.managers.approvals'] = $approvalStats['pending'];
                        $menuBadges['byUrl']['/sales/managers/approvals'] = $approvalStats['pending'];
                    }

                    $businessCardService = app(BusinessCardRequestService::class);
                    $businessCardPending = $businessCardService->getPendingCount();
                    if ($businessCardPending > 0) {
                        $menuBadges['byRoute']['sales.business-cards.manage'] = $businessCardPending;
                        $menuBadges['byUrl']['/sales/business-cards/manage'] = $businessCardPending;
                    }
                } catch (\Exception $e) {
                    // 서비스 오류 시 무시
                }

                // ── 결재 뱃지 (색상별) ──
                try {
                    $counts = app(ApprovalService::class)->getBadgeCounts(auth()->id());
                    $menuBadges['byUrl']['/approval-mgmt/pending'] = ['count' => $counts['pending'], 'color' => '#ef4444'];
                    $menuBadges['byUrl']['/approval-mgmt/drafts'] = ['count' => $counts['draft'], 'color' => '#3b82f6'];
                    $menuBadges['byUrl']['/approval-mgmt/references'] = ['count' => $counts['reference_unread'], 'color' => '#10b981'];
                } catch (\Throwable $e) {
                    // 테이블 미존재 등 예외 무시
                }
            }

            View::share('menuBadges', $menuBadges);
        });
    }
}
