<?php

namespace Daylight\Core\Modules\FormBuilder\Notifications;

use Daylight\Core\Modules\FormBuilder\Models\Form;
use Daylight\Core\Modules\FormBuilder\Models\FormSubmission;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Storage;

class FormSubmissionNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public Form $form,
        public FormSubmission $submission,
        public ?string $overrideRecipient = null,
    ) {}

    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $fields = collect($this->form->fields);
        $data = $this->submission->data;
        $files = $this->submission->files ?? [];

        $message = (new MailMessage)
            ->subject(__('daylight::forms.notification_subject', ['name' => $this->form->name]))
            ->greeting(__('daylight::forms.notification_greeting'))
            ->line(__('daylight::forms.notification_intro', ['name' => $this->form->name]));

        if (! $this->overrideRecipient) {
            if ($this->form->cc) {
                foreach ($this->parseEmails($this->form->cc) as $cc) {
                    $message->cc($cc);
                }
            }

            if ($this->form->bcc) {
                foreach ($this->parseEmails($this->form->bcc) as $bcc) {
                    $message->bcc($bcc);
                }
            }
        }

        foreach ($fields as $field) {
            $fieldId = $field['id'];
            $label = $field['label'] ?: $field['type'];
            $value = $data[$fieldId] ?? null;

            if ($field['type'] === 'heading' || $field['type'] === 'file') {
                continue;
            }

            if ($field['type'] === 'checkbox') {
                $value = $value ? __('daylight::general.yes') : __('daylight::general.no');
            }

            if (is_array($value)) {
                $value = implode(', ', $value);
            }

            $message->line("**{$label}:** " . ($value ?: '-'));
        }

        if (! empty($files)) {
            $disk = Storage::disk('media');

            foreach ($files as $fieldId => $filePaths) {
                foreach ((array) $filePaths as $path) {
                    if ($disk->exists($path)) {
                        $message->attachData(
                            $disk->get($path),
                            basename($path),
                            ['mime' => $disk->mimeType($path)],
                        );
                    }
                }
            }
        }

        $message->line('---');
        $message->line(__('daylight::forms.submitted_at_date', ['date' => $this->submission->created_at->isoFormat('LLL')]));

        if ($this->submission->ip_address) {
            $message->line(__('daylight::forms.ip_address_value', ['ip' => $this->submission->ip_address]));
        }

        if ($this->submission->page_url) {
            $message->line(__('daylight::forms.page_url') . ': ' . $this->submission->page_url);
        }

        return $message;
    }

    /** @return string[] */
    protected function parseEmails(string $emails): array
    {
        return array_filter(array_map('trim', explode(',', $emails)));
    }
}
