<?php

namespace App\Http\Requests;

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

class SubmitEnquiryRequest extends FormRequest
{
    /** @var Form $form */
    protected $form;

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

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

    public function attributes()
    {
        if (empty($this->form())) {
            // no form found - no question rules. will fail form validation
            return [];
        }

        return $this->form()
            ->questions
            ->keyBy(fn($question) => $question->type == 'file_upload'
                ? "files.$question->id"
                : "questions.$question->id")
            ->map(fn ($question) => $question->name)
            ->filter()
            ->toArray();
    }

    protected function prepareForValidation()
    {
        if (!$this->filled('questions') && $this->filled('sections')) {
            $this->merge([
                'questions' => collect($this->input('sections'))
                    ->pluck('segments')
                    ->flatten(1)
                    ->pluck('questions')
                    ->flatten(1)
                    ->keyBy('id')
                    ->map(fn ($question) => $question['value'] ?? null)
                    ->toArray()
            ]);
        }
    }

    /**
     * @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
            ->keyBy(fn($question) => $question->type == 'file_upload'
                ? (($question->data['allow_multiple'] ?? false) ? "files.$question->id.*" : "files.$question->id")
                : "questions.$question->id")
            ->map(fn ($question) => $question->validation)
            ->filter()
            ->toArray();
    }

    /**
     * Get the form object from request
     *
     * @return Form|null
     */
    public function form(): ?Form
    {
        if (!tenant()) {
            return null;
        }

        if (empty($this->form)) {
            $this->form = Form::query()
                ->with('questions')
                ->find($this->input('id'));
        }

        return $this->form;
    }
}
