<?php

namespace App\Traits;

use App\Http\Resources\FormViewResource;
use Mtc\MercuryDataModels\Form;

trait GetsFormResource
{
    /**
     * @param Form $form
     * @param array $values
     * @return FormViewResource|null
     */
    protected function getResourceForForm(?Form $form, array $values = []): ?FormViewResource
    {
        return $form
            ? new FormViewResource($form)->setValues($values)
            : null;
    }

    /**
     * @param string $enquiry_type
     * @param string $containing_field_type
     * @param array $values
     * @return FormViewResource|null
     */
    protected function getResourceForFormByEnquiryType(
        string $enquiry_type,
        string $containing_field_type,
        array $values = []
    ): ?FormViewResource {
        $resource = Form::query()
            ->whereHas('type', fn ($query) => $query->where('name', '=', $enquiry_type))
            ->whereHas('questions', fn ($query) => $query->where('type', '=', $containing_field_type))
            ->first();

        return $resource
            ? new FormViewResource($resource)->setValues($values)
            : null;
    }
}
