<?php
namespace ComptaFlowUK\Services;

defined('ABSPATH') || exit;

class PDFGenerator {

    public static function generateInvoicePDF(array $invoice, array $lines, array $client, array $company): string {
        $template = ($invoice['invoice_type'] === 'CREDIT_NOTE')
            ? COMPTAFLOW_UK_PLUGIN_DIR . 'src/Templates/PDF/credit-note.php'
            : COMPTAFLOW_UK_PLUGIN_DIR . 'src/Templates/PDF/invoice.php';

        ob_start();
        include $template;
        $html = ob_get_clean();

        $dompdf_autoload = COMPTAFLOW_UK_PLUGIN_DIR . 'vendor/dompdf/autoload.inc.php';
        if (file_exists($dompdf_autoload)) {
            require_once $dompdf_autoload;
            $dompdf = new \Dompdf\Dompdf(['isRemoteEnabled' => false]);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            return $dompdf->output();
        }

        return $html;
    }

    public static function streamPDF(array $invoice, array $lines, array $client, array $company, bool $download = true): void {
        $dompdf_autoload = COMPTAFLOW_UK_PLUGIN_DIR . 'vendor/dompdf/autoload.inc.php';

        $template = ($invoice['invoice_type'] === 'CREDIT_NOTE')
            ? COMPTAFLOW_UK_PLUGIN_DIR . 'src/Templates/PDF/credit-note.php'
            : COMPTAFLOW_UK_PLUGIN_DIR . 'src/Templates/PDF/invoice.php';

        ob_start();
        include $template;
        $html = ob_get_clean();

        $filename = sanitize_file_name($invoice['invoice_number']) . '.pdf';

        if (file_exists($dompdf_autoload)) {
            require_once $dompdf_autoload;
            $dompdf = new \Dompdf\Dompdf(['isRemoteEnabled' => false]);
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream($filename, ['Attachment' => $download]);
        } else {
            header('Content-Type: text/html; charset=utf-8');
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML template output
            echo $html;
        }
        exit;
    }
}
