<?php

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreShippingCityRequest extends FormRequest
{
    public function authorize(): bool
    {
        return (bool) $this->user();
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:191', 'regex:/^[\p{L}\p{M}\s.\-\']+$/u'],
            'country_id' => ['required', 'integer', Rule::exists('countries', 'id')->where('status', 1)],
            'state_id' => [
                'required',
                'integer',
                Rule::exists('states', 'id')
                    ->where('status', 1)
                    ->where(fn ($q) => $q->where('country_id', $this->input('country_id'))),
            ],
            'cost' => ['nullable', 'numeric', 'min:0', 'max:99999999.99'],
            'status' => ['nullable', 'boolean'],
        ];
    }

    public function messages(): array
    {
        return [
            'name.regex' => 'City name may only contain letters, spaces, hyphens, apostrophes, and periods.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('name')) {
            $name = strip_tags(trim((string) $this->input('name')));
            $name = preg_replace('/\s+/u', ' ', $name) ?? '';
            $this->merge(['name' => $name !== '' ? $name : null]);
        }
    }
}
