<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CustomScheduleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $rules = [
            'client_id'        => 'required|exists:clients,id',
            'address_id'       => 'required|exists:addresses,id',
            'address_type'     => 'required|in:home,commercial',
            'service_type_id'  => 'required|exists:service_types,id',
            'description'      => 'nullable|string',
            'min_price'        => 'required|numeric|min:0',
            'max_price'        => 'required|numeric|min:0|gte:min_price',
            'offers_meal'      => 'nullable|boolean',
            'date'             => 'required|date|after_or_equal:today',
            'period_type'      => 'required|in:2,4,6,8',
            'start_time'       => 'required|date_format:H:i',
            'end_time'         => 'required|date_format:H:i|after:start_time',
            'quantity'         => 'required|integer|min:1',
            'speciality_ids'   => 'nullable|array',
            'speciality_ids.*' => 'exists:specialities,id',
        ];

        if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
            foreach ($rules as $key => $rule) {
                if (str_starts_with($rule, 'required')) {
                    $rules[$key] = 'sometimes|'.substr($rule, 9);
                }
            }
        }

        return $rules;
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'max_price.gte'       => __('requests.custom_schedule.max_price_gte'),
            'date.after_or_equal' => __('requests.custom_schedule.date_after_or_equal'),
            'end_time.after'      => __('requests.custom_schedule.end_time_after'),
        ];
    }
}
