<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that is loaded on the first page visit.
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determine the current asset version.
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        return [
            ...parent::share($request),
            'ziggy' => fn () => [
                ...(new Ziggy)->toArray(),
                'location' => $request->url(),
            ],
            //Flash Messages
            'flash' => [
                'message' => fn () => Session::get('message'),
                'toastr' => fn () => Session::get('toastr')
            ],
            'lang' => function () {
                return Session::get('locale');
            },
            'roles' => function () {
                if (Auth::check()) {
                    return Auth::user()?->getRoleNames();
                }

                return [];
            },
            'permissions' => function () {
                if (Auth::check()) {
                    return Auth::user()?->getAllPermissions();
                }

                return [];
            }
        ];
    }
}
