<?php

namespace App\Http\Middleware;

use App\Settings\GeneralSettings;
use Illuminate\Http\Request;
use Inertia\Middleware;

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),
            'auth' => [
                'user' => $request->user(),
            ],
            'locale' => app()->getLocale(),
            'settings' => tap(app(GeneralSettings::class)->toArray(), function (&$settings) {
                unset($settings['gallery_password_hash']);
            }),
            'translations' => function () use ($request) {
                $currentLocale = app()->getLocale(); // Store current locale
                $requestedLocale = $request->input('locale', $currentLocale);
                app()->setLocale($requestedLocale); // Set locale based on request or current

                $lang = [
                    'filament' => trans('filament'),
                    'api' => trans('api'),
                    'settings' => trans('settings'),
                    // Add other translation files as needed
                ];

                app()->setLocale($currentLocale); // Revert to original locale

                return $lang;
            },
        ];
    }
}
