<?php

namespace App\Notifications;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class InvoiceNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public readonly Order $order
    ) {}

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

    public function toMail(object $notifiable): MailMessage
    {
        $order   = $this->order;
        $order->loadMissing(['user', 'items.product', 'payment', 'address']);
        $payment = $order->payment;

        $paymentMethodLabel = match ($payment?->payment_method) {
            'cash'     => 'COD (Bayar di Tempat)',
            'card'     => 'Kartu Kredit/Debit',
            'transfer' => 'Transfer Bank',
            'ewallet'  => 'E-Wallet',
            'qris'     => 'QRIS',
            default    => ucfirst($payment?->payment_method ?? '-'),
        };

        // Generate PDF directly in the queued job to avoid JSON encode issues
        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('invoices.pdf', compact('order'))
            ->setPaper('a4', 'portrait')
            ->setOptions([
                'defaultFont'  => 'sans-serif',
                'isHtml5ParserEnabled' => true,
                'isRemoteEnabled'      => false,
            ]);
            
        $pdfContent = $pdf->output();

        return (new MailMessage)
            ->subject('Invoice Pesanan #' . $order->order_id . ' – ' . config('app.name'))
            ->view('emails.invoice-email', [
                'notifiable' => $notifiable,
                'order' => $order,
                'paymentMethodLabel' => $paymentMethodLabel,
                'url' => route('order.show', $order->order_id)
            ])
            // Lampirkan PDF sebagai attachment
            ->attachData(
                $pdfContent,
                'Invoice-Order-' . $order->order_id . '.pdf',
                ['mime' => 'application/pdf']
            );
    }
}
