<?php

namespace App\Mail;

use App\Facades\Settings;
use App\Facades\Site;
use App\IntegrationRepository;
use App\Modules\Valuation\ConditionPriceTier;
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;
use Mtc\MercuryDataModels\Vehicle;

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'];
                        }
                    }
                }
            }
        }

        $valuation = $this->enquiry->reason;
        $condition = $valuation?->cosmetic_condition ?? null;
        $customerOnlyTier = ConditionPriceTier::fromCondition($condition);
        if ($customerOnlyTier !== null && empty($valuation?->{$customerOnlyTier})) {
            $customerOnlyTier = null;
        }

        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,
                'valuation_email_price_to_show' => Settings::get('valuation-email-price-to-show', 'all'),
                'vehicle_image' => $this->resolveVehicleImage(),
                'valuation_customer_only_tier' => $customerOnlyTier,
                'valuation_highlight_tier' => null,
                'valuation_condition_label' => $condition,
                'socials' => app(IntegrationRepository::class)->findNonEmptyValuesForType('socials')
                    ->map(fn ($link, $key) => [
                        'key' => $key,
                        'url' => $link,
                    ])->values(),
            ],
        );
    }

    /**
     * Resolve the primary image URL for the vehicle this enquiry relates to, so it is
     * available to the customer confirmation template. Returns null when the enquiry
     * does not relate to a vehicle or the vehicle has no image.
     */
    private function resolveVehicleImage(): ?string
    {
        $vehicle = $this->enquiry->reason instanceof Vehicle
            ? $this->enquiry->reason
            : $this->enquiry->objects->firstWhere('object_type', 'vehicle')?->object;

        if (!$vehicle instanceof Vehicle) {
            return null;
        }

        return $vehicle->primaryMediaUse?->getUrl('large')
            ?? $vehicle->primaryMediaUse?->media?->getOriginalUrlAttribute();
    }

    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
        };
    }
}
