<?php

namespace App\Http\Middleware;

use App\Models\Cutting;
use App\Models\EmployeeAdvance;
use App\Models\LeaveRequest;
use App\Services\System\Setting\SystemService;
use App\Settings\SystemSettings;
use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        return [
            ...parent::share($request),
            'name' => fn () => app(SystemSettings::class)->app_name,
            'address' => fn () => app(SystemSettings::class)->address,
            'logo_url' => fn () => app(SystemService::class)->systemData()['logo_url'] ?? asset('assets/logo.png'),
            'favicon_url' => fn () => app(SystemService::class)->systemData()['favicon_url'] ?? null,
            'login_cover_url' => fn () => app(SystemService::class)->systemData()['login_cover_url'] ?? null,
            'auth' => fn () => [
                'user' => $request->user() ? [
                    'id' => $request->user()->id,
                    'email' => $request->user()->email,
                    'username' => $request->user()->username,
                    'is_active' => $request->user()->is_active,
                    'last_login_at' => $request->user()->last_login_at,
                    'roles' => $request->user()->getRoleNames(),
                    'permissions' => $request->user()->getAllPermissions()->pluck('name'),
                    'profile_photo_url' => $request->user()->profile?->profile_photo_url,
                ] : null,
                'password_default' => config('auth.password_default'),
            ],
            'flash' => [
                'success' => $request->session()->get('success'),
                'error' => $request->session()->get('error'),
            ],
            'sidebarOpen' => ! $request->hasCookie('sidebar_state')
                || $request->cookie('sidebar_state') === 'true',
            'appearance' => $request->cookie('appearance', 'system'),
            'vapidPublicKey' => config('webpush.vapid.public_key'),
            'pendingLeaveRequests' => fn () => $this->pendingLeaveRequests($request),
            'pendingEmployeeAdvances' => fn () => $this->pendingEmployeeAdvances($request),
            'pendingCuttings' => fn () => $this->pendingCuttings($request),
        ];
    }

    private function pendingLeaveRequests(Request $request): int
    {
        $user = $request->user();

        if ($user === null || ! $user->hasAnyRole(['owner', 'developer'])) {
            return 0;
        }

        return LeaveRequest::query()
            ->pending()
            ->count();
    }

    private function pendingEmployeeAdvances(Request $request): int
    {
        $user = $request->user();

        if ($user === null || ! $user->hasAnyRole(['owner', 'developer'])) {
            return 0;
        }

        return EmployeeAdvance::query()
            ->pending()
            ->count();
    }

    private function pendingCuttings(Request $request): int
    {
        $user = $request->user();

        if ($user === null || ! $user->can('stocks.view')) {
            return 0;
        }

        return Cutting::query()
            ->completed()
            ->count();
    }
}
