<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;
use App\Models\CompanyInformation;
use Illuminate\Support\Facades\Auth;

use App\Models\Testimonial;
use App\Models\Gallary;
use App\Models\SectionImage;

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
     */
    public function rootView(Request $request): string
    {
        $route = $request->route();
        // 1) If we actually have a route...
        if ($route) {
            // 2) If it's the fallback route => always use app.jsx
            if ($route->getName() === 'fallback') {
                return 'app';
            }
            // 3) Otherwise, if the path starts with "admin/", use admin.jsx
            if (str_starts_with($request->path(), 'admin/')) {
                return 'admin';
            }
        }
        // 4) For all else, use app.jsx
        return '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 array_merge(parent::share($request), [
            'auth' => [
                'user' => Auth::user() ? [
                    'id' => Auth::user()->id,
                    'name' => Auth::user()->name,
                    'email' => Auth::user()->email,
                    'photo' => Auth::user()->photo,
                    'role' => Auth::user()->roles->pluck('name')->first(), 
                    'roles' => Auth::user()->getRoleNames(),
                    'permissions' => Auth::user()->getAllPermissions()->pluck('name'),
                ] : null,
            ],

            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'mail_success' => fn () => $request->session()->get('mail_success'),
                'booking_success' => fn () => $request->session()->get('booking_success'),
                'error' => fn () => $request->session()->get('error'),
            ],
            'turnstileSiteKey' => config('services.turnstile.sitekey'),
            'siteinfo' => CompanyInformation::first() ?? null,
            'sectionimages' =>SectionImage::first()?? null,
            'testimonials' => Testimonial::where('status', true) 
                ->select('name', 'message', 'photo') 
                ->get(),
        ]);
    }
}
