<?php

namespace App\Mail;

use App\Models\Sale;
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 SaleReceiptMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly Sale $sale
    ) {}

    public function envelope(): Envelope
    {
        $businessName = Setting::getValue('business_name', config('app.name'));

        return new Envelope(
            subject: "Your Receipt — {$this->sale->sale_number} | {$businessName}",
        );
    }

    public function content(): Content
    {
        return new Content(view: 'emails.sale-receipt');
    }

    public function attachments(): array
    {
        $sale = $this->sale->load(['customer', 'items.product', 'payments', 'user', 'branch']);

        $data = [
            'sale'     => $sale,
            'settings' => [
                'business_name'    => Setting::getValue('business_name', 'INVENTINO'),
                'business_logo'    => Setting::getValue('business_logo', null),
                'business_address' => Setting::getValue('address', ''),
                'business_phone'   => Setting::getValue('phone', ''),
                'business_email'   => Setting::getValue('email', ''),
                'business_website' => Setting::getValue('website', ''),
                'currency_symbol'  => Setting::getValue('currency_symbol', '₦'),
                'receipt_header'   => Setting::getValue('receipt_header', 'Thank you for your purchase'),
                'receipt_footer'   => Setting::getValue('receipt_footer', 'Please visit us again!'),
                'branch_name'      => $sale->branch?->name ?? '',
                'branch_address'   => $sale->branch?->address ?? '',
            ],
        ];

        $pdf = Pdf::loadView('receipts.sale', $data)
            ->setPaper([0, 0, 226.77, 841.89], 'portrait')
            ->setOption('isHtml5ParserEnabled', true)
            ->setOption('isRemoteEnabled', true)
            ->setOption('chroot', public_path());

        return [
            Attachment::fromData(
                fn () => $pdf->output(),
                "receipt-{$sale->sale_number}.pdf"
            )->withMime('application/pdf'),
        ];
    }
}
