<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class DentistRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true; // policy enforced in controller
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:190'],
            'specialty' => ['nullable', 'string', 'max:120'],
            'color' => ['required', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'slot_duration_min' => ['required', 'integer', 'min:5', 'max:240'],
            'buffer_min' => ['required', 'integer', 'min:0', 'max:120'],
            'is_bookable_online' => ['sometimes', 'boolean'],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            // schedule grid: schedules[weekday][] = ["09:00-13:00", ...]
            'schedules' => ['sometimes', 'array'],
            'schedules.*' => ['array'],
            'schedules.*.*' => ['regex:/^([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d$/'],
        ];
    }

    /** @return array<int, array{weekday:int,start_time:string,end_time:string}> */
    public function scheduleRows(): array
    {
        $rows = [];
        foreach ($this->input('schedules', []) as $weekday => $ranges) {
            foreach (array_filter((array) $ranges) as $range) {
                [$start, $end] = explode('-', $range);
                if ($start < $end) {
                    $rows[] = [
                        'weekday' => (int) $weekday,
                        'start_time' => $start,
                        'end_time' => $end,
                    ];
                }
            }
        }

        return $rows;
    }
}
