<?php

namespace App\Mail;

use App\Models\Order;
use App\Models\Setting;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OrderInvoiceMail extends Mailable
{
    use Queueable, SerializesModels;

    public Order $order;
    public string $status;
    public bool $isAdminAlert;
    public string $emailContent;

    /**
     * Create a new message instance.
     */
    public function __construct(Order $order, string $status = 'placed', bool $isAdminAlert = false)
    {
        $this->order = $order;
        $this->order->loadMissing('items.product');
        $this->status = $status;
        $this->isAdminAlert = $isAdminAlert;

        // Resolve dynamic email templates with standard fallbacks
        if ($this->isAdminAlert) {
            $template = Setting::getValue(
                'email_template_admin_order_placed',
                "Hello Admin,\n\nA new order has been placed on **{site_name}**. Below is a summary of the order details. The customer invoice PDF is attached for your reference.\n\n{product_list}"
            );
        } else {
            $template = match ($this->status) {
                'shipped' => Setting::getValue(
                    'email_template_order_shipped',
                    "Hello {customer_name},\n\nWe are excited to let you know that your order has been dispatched via **{courier_name}** and is on its way to you.\n\n{product_list}"
                ),
                'delivered' => Setting::getValue(
                    'email_template_order_delivered',
                    "Hello {customer_name},\n\nGreat news! Your order has been delivered successfully. We hope you are satisfied with your purchase. Thank you for shopping with us!\n\n{product_list}"
                ),
                'cancelled' => Setting::getValue(
                    'email_template_order_cancelled',
                    "Hello {customer_name},\n\nWe regret to inform you that your order **#{order_number}** has been cancelled. If this was done in error or if you have any questions, please contact our support team immediately.\n\n{product_list}"
                ),
                'payment_received' => Setting::getValue(
                    'email_template_order_payment_received',
                    "Hello {customer_name},\n\nWe have successfully received your payment of **৳{grand_total}** for order **#{order_number}**. We are now preparing your items for shipping.\n\n{product_list}"
                ),
                default => Setting::getValue(
                    'email_template_order_placed',
                    "Hello {customer_name},\n\nWe have successfully received your order and are preparing it for delivery. A PDF copy of your invoice is attached to this email.\n\n{product_list}"
                ),
            };
        }

        $this->emailContent = \App\Services\NotificationDispatcher::parseShortcodes($template, $this->order);
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        $siteName = Setting::getValue('site_name', 'Sawdabazar');
        
        if ($this->isAdminAlert) {
            $subject = "[ADMIN ALERT] New Order Received #{$this->order->order_number} - {$siteName}";
        } else {
            $subject = match ($this->status) {
                'shipped' => "Your Order #{$this->order->order_number} has been shipped! - {$siteName}",
                'delivered' => "Your Order #{$this->order->order_number} has been delivered! - {$siteName}",
                'cancelled' => "Your Order #{$this->order->order_number} has been cancelled - {$siteName}",
                'payment_received' => "Payment received for Order #{$this->order->order_number} - {$siteName}",
                default => "Your Order Receipt #{$this->order->order_number} - {$siteName}",
            };
        }

        return new Envelope(
            subject: $subject,
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.order_invoice',
        );
    }

    /**
     * Get the attachments for the message.
     */
    public function attachments(): array
    {
        // Hydrate items relation for PDF generation
        $this->order->load('items.product');

        // Generate the PDF invoice on the fly
        $pdf = Pdf::loadView('pdf.invoice', ['order' => $this->order])
            ->setPaper('a4', 'portrait')
            ->setWarnings(false);

        return [
            Attachment::fromData(fn () => $pdf->output(), 'invoice-' . $this->order->order_number . '.pdf')
                ->withMime('application/pdf'),
        ];
    }
}
