<?php

namespace App\Http\Middleware;

use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
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
    {
        $appSettings = [];
        if ($request->user()) {
            $settings = Setting::all()->pluck('value', 'key');
            $appSettings = [
                'business_name' => $settings['business_name'] ?? 'RentDesk',
                'business_address' => $settings['business_address'] ?? '',
                'business_phone' => $settings['business_phone'] ?? '',
                'business_logo' => isset($settings['business_logo']) && $settings['business_logo']
                    ? '/storage/' . $settings['business_logo']
                    : null,
                'default_electricity_rate' => $settings['default_electricity_rate'] ?? 25,
                'invoice_prefix' => $settings['invoice_prefix'] ?? 'RD',
                'voucher_prefix' => $settings['voucher_prefix'] ?? 'OV',
            ];
        }

        return [
            ...parent::share($request),
            'auth' => [
                'user' => $request->user() ? [
                    ...$request->user()->toArray(),
                    'is_admin' => $request->user()->isAdmin(),
                ] : null,
            ],
            'appSettings' => $appSettings,
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
            ],
        ];
    }
}
