<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Mtc\Crm\Models\Form;

class PartialEnquirySubmissionRequest extends SubmitEnquiryRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return array_merge([
            'id' => [
                'required',
                'numeric',
                'exists:forms,id',
            ],
            'section_id' => [
                'required',
                'numeric',
            ],
            'questions' => [
                'required',
                'array',
            ],
            'source' => [
                'nullable',
                'string'
            ],
        ], $this->questionSpecificRules());
    }

    /**
     * @return array
     */
    protected function questionSpecificRules(): array
    {
        if (empty($this->form())) {
            // no form found - no question rules. will fail form validation
            return [];
        }

        return $this->form()
            ->questions
            ->where('form_section_id', $this->input('section_id'))
            ->keyBy(fn($question) => $question->type == 'file_upload'
                ? "files.$question->id"
                : "questions.$question->id")
            ->map(fn ($question) => $question->validation)
            ->filter()
            ->toArray();
    }
}
