<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Menu;
use App\Services\SettingService;
use Illuminate\Http\Request;
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
    {
        $settingService = app(SettingService::class);
        $user = $request->user();

        // Fetch dynamic menus from database
        $dbMenus = Menu::with(['children'])
            ->whereNull('parent_id')
            ->orderBy('sort_order', 'asc')
            ->get();

        $navigation = [];
        $grouped = $dbMenus->groupBy('group_name');
        foreach ($grouped as $groupName => $items) {
            $navigation[] = [
                'groupName' => $groupName,
                'items' => $items->map(function ($menu) {
                    return [
                        'id' => $menu->id,
                        'title' => $menu->title,
                        'href' => $menu->href,
                        'icon' => $menu->icon,
                        'roles' => $menu->roles,
                        'permissions' => $menu->permissions,
                        'children' => $menu->children->map(function ($child) {
                            return [
                                'id' => $child->id,
                                'title' => $child->title,
                                'href' => $child->href,
                                'icon' => $child->icon,
                                'roles' => $child->roles,
                                'permissions' => $child->permissions,
                            ];
                        })->toArray(),
                    ];
                })->values()->toArray(),
            ];
        }

        return [
            ...parent::share($request),
            'auth' => [
                'user' => $user ? [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'outlet_id' => $user->outlet_id,
                    'email_verified_at' => $user->email_verified_at,
                    'roles' => $user->getRoleNames(),
                    'permissions' => $user->getAllPermissions()->pluck('name'),
                ] : null,
            ],
            'settings' => [
                'site_name' => $settingService->get('site_name', 'Laravel'),
                'site_logo' => $settingService->get('site_logo'),
                'site_favicon' => $settingService->get('site_favicon'),
                'site_description' => $settingService->get('site_description'),
                'thermal_logo' => $settingService->get('thermal_logo', '/images/logo-thermal.png'),
                'qris_image' => $settingService->get('qris_image', '/images/radhcloud-qris.png'),
                'version' => config('app.version', 'v1.0.0'),
            ],
            'is_demo_mode' => app()->environment('demo'),
            'navigation' => $navigation,
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'last_transaction' => fn () => $request->session()->get('last_transaction'),
            ],
            'ziggy' => fn () => [
                ...(new Ziggy)->toArray(),
                'location' => $request->url(),
            ],
            'qz_cert' => fn () => \App\Models\QzCertificate::where('status', 'active')->first()?->public_certificate,
            'qz_algo' => config('qztray.signature_algorithm', 'sha256'),
        ];
    }
}
