<?php

namespace App\Http\Middleware;

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
    {
        $user = $request->user();
        
        return [
            ...parent::share($request),
            'auth' => [
                'user' => $user ? [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'username' => $user->username ?? null,
                    // 權限資料
                    'roles' => $user->getRoleNames(),
                    'role_labels' => $user->roles->pluck('display_name'),
                    'permissions' => $user->getAllPermissions()->pluck('name')->toArray(),
                ] : null,
            ],
            'flash' => [
                'success' => $request->session()->get('success'),
                'error' => $request->session()->get('error'),
            ],
            'branding' => function () {
                $tenant = tenancy()->tenant;
                if (!$tenant) {
                    return null;
                }

                $logoUrl = null;
                if (isset($tenant->branding['logo_path'])) {
                    $logoUrl = \Storage::url($tenant->branding['logo_path']);
                }

                return [
                    'logo_url' => $logoUrl,
                    'primary_color' => $tenant->branding['primary_color'] ?? '#01ab83',
                    'text_color' => $tenant->branding['text_color'] ?? '#1a1a1a',
                ];
            },
        ];
    }
}
