<?php

namespace Inside\DESK\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Inside\Form\Events\FormSubmissionStatusEditedEvent;
use Inside\Form\Models\FormSubmission;
use Inside\Notify\Listeners\BaseNotificationListener;

class FormStatusListener extends BaseNotificationListener implements ShouldQueue
{
    /**
     * @param FormSubmissionStatusEditedEvent $event
     * @return void
     */
    public function handle(FormSubmissionStatusEditedEvent $event)
    {
        /** @var FormSubmission|null $model */
        $model = FormSubmission::query()->find($event->submission->id);

        if (! $model) {
            return;
        }

        $form = $model->answerable;

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

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

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

        /** @var FormSubmission|null $submission */
        $submission = FormSubmission::query()->where('user_uuid', $model->user_uuid)->where('answerable_uuid', $form->uuid)->where('created_at', date('Y-m-d H:i:s', $model->created_at))->first();

        if (! $submission || $submission->status === $model->status) {
            return;
        }

        $submission->notify = $model->notify;
        $submission->comment = $model->comment;
        $submission->status = $model->status;
        $submission->save();
    }
}
