<?php

namespace App\Mail;

use App\Facades\Settings;
use App\Facades\Site;
use App\IntegrationRepository;
use App\Traits\GetsColourSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Mtc\Crm\Contracts\EnquiryModel;
use Mtc\MercuryDataModels\GlobalContent;

class NewEnquiryCustomerCopyNotification extends Mailable
{
    use Queueable;
    use SerializesModels;
    use GetsColourSettings;
    use CheckThemeTemplateTrait;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(
        public readonly EnquiryModel $enquiry,
    ) {

        $action = $this->enquiry->actions->where('action_name', 'send-copy-via-mail')->first();
        if ($action) {
            $this->enquiry->subject = $action->data['enquiry_subject'] ?? '';
            $this->enquiry->intro = $action->data['enquiry_content'] ?? '';
        }
    }

    public function envelope(): Envelope
    {
        return new Envelope(
            from: new Address(
                Settings::get('mail-from-email') ?: config('mail.from.address'),
                Settings::get('mail-from-name')
            ),
            subject: __('crm::enquiries.customer-autorespond', ['title' => $this->enquiry->title]),
        );
    }

    public function content(): Content
    {
        $template = 'customer-autoresponder';
        if (!empty($this->enquiry->form->type->template_name)) {
            $template = $this->enquiry->form->type->template_name;
        }
        $contentText = $this->enquiry->form?->confirmation_message;
        $footerText = '';
        $globalContent = GlobalContent::query()->where('slug', 'customer-enquiry-autoresponder')->first();


        if (!empty($globalContent->content)) {
            foreach ($globalContent?->content as $content) {
                if (!empty($content['children'])) {
                    foreach ($content['children'] as $childContent) {
                        if ($childContent['slug'] == 'content' && empty($contentText)) {
                            $contentText = $childContent['content'];
                        } elseif ($childContent['slug'] == 'footer') {
                            $footerText = $childContent['content'];
                        }
                    }
                }
            }
        }

        return new Content(
            view: $this->getTemplateName($template),
            with: [
                'theme' => Settings::get('mail-customer-theme'),
                'site_name' => Settings::get('app-name'),
                'site_logo' => Settings::get('site-logo') ?? ['url' => null],
                'phone_number' => Settings::get('app-contact-phone_number'),
                'phone_number_formatted' => $this->displayNumber(Settings::get('app-contact-phone_number', '')),
                'site_url' => Site::url(''),
                'enquiry' => $this->enquiry,
                'site_logo_alternate' => Settings::get('site-alternate-logo'),
                'colours' => $this->getColourSettings(),
                'content' => $contentText,
                'footer' => $footerText,
                'socials' => app(IntegrationRepository::class)->findNonEmptyValuesForType('socials')
                    ->map(fn($link, $key) => [
                        'key' => $key,
                        'url' => $link,
                    ])->values(),
            ],
        );
    }

    protected function displayNumber(string $number): string
    {
        return match (Settings::get('app-phone-number-format')) {
            '3-3-4' => substr($number, 0, 3) . ' ' . substr($number, 3, 3) . ' ' . substr($number, 6),
            '4-3-3' => substr($number, 0, 4) . ' ' . substr($number, 4, 3) . ' ' . substr($number, 7),
            '5-3-3' => substr($number, 0, 5) . ' ' . substr($number, 5, 3) . ' ' . substr($number, 8),
            '5-6' => substr($number, 0, 5) . ' ' . substr($number, 5),
            default => $number
        };
    }
}
