<?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\FormSubmissionDeletedEvent;
use Inside\Form\Models\FormAnswer;
use Inside\Form\Models\FormSubmission;

class FormSubmissionDeletedListener implements ShouldQueue
{
    public function handle(FormSubmissionDeletedEvent $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->delete();
        }
    }
}
