<?php

namespace Inside\DESK\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Inside\Content\Models\Contents\Forms;
use Inside\Form\Events\FormSubmitedEvent;
use Inside\Form\Models\FormAnswer;
use Inside\Form\Models\FormSubmission;

/**
 * Form submited listener
 *
 * @category Class
 * @package  Inside\DESK\Listeners\FormSubmittedListener
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class FormSubmittedListener implements ShouldQueue
{
    public function handle(FormSubmitedEvent $event): void
    {
        $model = $event->submission;

        $form = $model->answerable;

        $langcode = $form->langcode === 'en' ? 'fr' : 'en';

        $form = $form->getTranslationIfExists($langcode);

        if ($form->langcode !== $langcode) {
            return;
        }

        $formSubmission = FormSubmission::query()->where([
            'user_uuid' => $model->user_uuid,
            'answerable_uuid' => $form->uuid,
            'created_at' => date('Y-m-d H:i:s', $model->created_at),
        ])->first();

        if (! $formSubmission instanceof FormSubmission) {
            $formSubmission = FormSubmission::create(
                [
                    "answerable_uuid" => $form->uuid,
                    "answerable_type" => Forms::class,
                    "user_uuid" => $model->user_uuid,
                    "created_at" => date('Y-m-d H:i:s', $model->created_at),
                ]
            );
        }

        /** @var FormSubmission $formSubmission */
        $formSubmission->edited_at = $model->edited_at;
        $formSubmission->editor_uuid = $model->editor_uuid;
        $formSubmission->status = $model->status;
        $formSubmission->comment = $model->comment;
        $formSubmission->code = $model->code;

        // We fetch from DB instead of $model->answers() to be sure answers are the last saved ones
        $formAnswers = FormAnswer::where('submission_id', $model->id)
            ->get()
            ->map(fn (FormAnswer $formAnswer) => ['field_id' => $formAnswer->field_id, 'answer' => $formAnswer->answer]);

        $formSubmission->answers()->delete();
        $formSubmission->answers()->createMany($formAnswers);
        $formSubmission->save();
    }
}
