<?php

namespace App\Http\Requests;

use App\Models\InspectionTemplate;
use Illuminate\Foundation\Http\FormRequest;

class InspectionStoreRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create inspections');
    }

    public function rules(): array
    {
        return [
            'selectedTemplateId' => 'required|exists:inspection_templates,id',
            'inspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
            'inspectionFormData' => 'nullable|array',
            'inspectionResult' => 'nullable|in:pass,fail',
            'inspectionNotes' => 'nullable|string',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $template = InspectionTemplate::find($this->input('selectedTemplateId'));
            if ($template) {
                foreach ($template->fields as $field) {
                    if (($field['required'] ?? false) && empty($this->input("inspectionFormData.{$field['name']}"))) {
                        $validator->errors()->add(
                            "inspectionFormData.{$field['name']}",
                            "El campo {$field['label']} es obligatorio."
                        );
                    }
                }
            }
        });
    }
}