<?php

namespace App\Mail\Invoices;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;

use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

use Barryvdh\DomPDF\Facade\Pdf;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Carbon\Carbon;

use App\Models\User;

use App\Helpers\Environment\SystemFeaturesHelper;
use App\Helpers\Support\PdfResourcesHelper;
use App\Enums\Invoicing\InvoiceStatus;

class EmailCFDI extends Mailable
{
    use Queueable, SerializesModels;

    public $invoice;
    public $business;

    public $pdf;
    public $pdfName;

    public $logo_url;
    public $fallback_url;
    public $hotel_logo;

    public function __construct($invoice, $business)
    {
      // Parameters
        $this->invoice  = $invoice;
        $this->business = $business;

      // Local Variables
        $paper_size = 'letter';
        $plane_date = Carbon::parse($invoice->date)->format('YmdHis');
        $invoice_format_serie = ($invoice->taxFormat?->serie ?? $invoice->invoice_type)."-{$invoice->serial_consecutive}";

        $this->logo_url = optional(User::first())->profile_photo;
        $this->fallback_url = public_path('images/harsi_logo.png');

        // Global Variables
        $this->pdfName  = "{$invoice->receptor->tax_id}-{$invoice_format_serie}-{$plane_date}";
        $this->hotel_logo = PdfResourcesHelper::domPDFImageRender($this->logo_url, $this->fallback_url);

      // Build PDF
        // Create QR
            $qrBase64 = base64_encode(QrCode::format('png')->size(150)->generate($invoice->verification_url));
            $qr_stamp = "data:image/png;base64,$qrBase64";

        // Define Issuer Logo
            $fallback_url = public_path('images/harsi_logo.png');
            $img_path  = $invoice->taxFormat?->url_logo ?? optional(User::first())->profile_photo;
            $tax_logo =PdfResourcesHelper::domPDFImageRender($img_path, $fallback_url);

        // Define view to Render
            $view = SystemFeaturesHelper::getFeatureStatus("sat_format_invoices")
                ? 'invoicing.invoices.pdf.standard.show'
                : 'invoicing.invoices.pdf.show';

        $this->pdf = Pdf::loadView($view, [
            'invoice' => $invoice,
            'issuer' => $business,
            'invoice_format_serie' => $invoice_format_serie,

            'title' => $this->pdfName,
            'logo_src' => $tax_logo,
            'qr_stamp' => $qr_stamp,
        ])->setPaper($paper_size)->setOptions([
            'defaultFont' => 'sans-serif',
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled'      => false
        ]);
    }

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: config('app.name')
                .' | '.__('entities')['invoicing']['invoice']
                .' #'.$this->invoice->sat_uuid,
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'emails.invoices.cfdi',
            with: [
                'invoice'     => $this->invoice,
                'business'    => $this->business,
                'logo_src'    => $this->logo_url ?? $this->fallback_url,
                'app_name'    => config('app.name'),
            ],
        );
    }

    public function attachments(): array
    {
        return [
            Attachment::fromData(fn () => $this->pdf->output(), $this->pdfName.'.pdf')
                ->withMime('application/pdf'),

            Attachment::fromPath(storage_path('app/public/'.$this->invoice->xml_path))
                ->withMime('application/xml'),
        ];
    }

}
