<?php

namespace Daylight\Core\Modules\FormBuilder\Livewire;

use Daylight\Core\Modules\FormBuilder\Models\Form;
use Daylight\Core\Modules\FormBuilder\Models\FormSubmission;
use Daylight\Core\Modules\FormBuilder\Notifications\FormSubmissionNotification;
use Illuminate\Support\Facades\Notification;
use Illuminate\View\View;
use Livewire\Component;

class ResendSubmission extends Component
{
    public Form $form;

    public FormSubmission $submission;

    public string $recipient = '';

    public bool $sent = false;

    public function mount(Form $form, FormSubmission $submission): void
    {
        $this->form = $form;
        $this->submission = $submission;
        $this->recipient = $form->recipient_email;
    }

    public function resend(): void
    {
        $this->validate([
            'recipient' => ['required', 'string', 'max:500'],
        ]);

        $recipients = array_filter(array_map('trim', explode(',', $this->recipient)));

        Notification::route('mail', $recipients)
            ->notify(new FormSubmissionNotification($this->form, $this->submission, $this->recipient));

        $this->sent = true;
    }

    public function render(): View
    {
        return view('daylight::livewire.form-builder.resend-submission');
    }
}
