<?php

namespace App\Http\Requests;

use App\Services\Settings\SettingsService;
use Illuminate\Foundation\Http\FormRequest;

class UpdateSettingsRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->role === 'business_owner';
    }

    protected function prepareForValidation(): void
    {
        $settings = app(SettingsService::class);
        $page = $settings->normalizePage($this->route('page', 'business'));
        $payload = $this->all();

        foreach ($settings->booleanFields($page) as $field) {
            $payload[$field] = (bool) ($payload[$field] ?? false);
        }

        foreach (['currency', 'default_currency'] as $field) {
            if (isset($payload[$field])) {
                $payload[$field] = strtoupper((string) $payload[$field]);
            }
        }

        if ($page === 'booking' && isset($payload['booking_slug'])) {
            $payload['booking_slug'] = str((string) $payload['booking_slug'])->slug()->toString();
        }

        $this->replace($payload);
    }

    public function rules(): array
    {
        $settings = app(SettingsService::class);
        $business = $this->attributes->get('current_business') ?? abort(403);

        return $settings->rules($business, $this->route('page', 'business'));
    }

    public function payload(): array
    {
        return $this->validated();
    }
}
