<?php
/**
 * PDF invoice generation via DOMPDF.
 *
 * Renders the invoice HTML template, then converts to PDF.
 * The resulting PDF is then passed to GOFACTOX_FacturX_Merger for PDF/A-3 conversion.
 *
 * @package FacturX_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

use Dompdf\Dompdf;
use Dompdf\Options;

class GOFACTOX_PDF_Generator {

    /**
     * Generate a PDF from invoice data.
     *
     * @param array $data Invoice data from GOFACTOX_Invoice::get_invoice_data().
     * @return string Path to the generated PDF file.
     */
    public static function generate( array $data ): string {
        $html = self::render_template( $data );

        $options = new Options();
        $options->set( 'isHtml5ParserEnabled', true );
        $options->set( 'isRemoteEnabled', false );
        $options->set( 'defaultFont', 'DejaVu Sans' );
        $options->set( 'isFontSubsettingEnabled', true );

        // Allow DOMPDF to read images from the WP uploads directory (logo, QR codes).
        // Without expanding the chroot, image tags pointing inside wp-content/uploads
        // are silently dropped from the rendered PDF.
        $upload_dir = wp_upload_dir();
        $options->set( 'chroot', [ $upload_dir['basedir'], GOFACTOX_PLUGIN_DIR ] );

        $dompdf = new Dompdf( $options );
        $dompdf->loadHtml( $html );
        $dompdf->setPaper( 'A4', 'portrait' );
        $dompdf->render();

        // Save to temp file (will be merged into PDF/A-3 by GOFACTOX_FacturX_Merger).
        $upload_dir = wp_upload_dir();
        $tmp_dir    = $upload_dir['basedir'] . '/wfx-invoices/tmp';
        wp_mkdir_p( $tmp_dir );

        $filename = 'tmp-' . sanitize_file_name( $data['invoice_number'] ) . '.pdf';
        $filepath = $tmp_dir . '/' . $filename;

        file_put_contents( $filepath, $dompdf->output() );

        return $filepath;
    }

    /**
     * Render the invoice HTML template.
     *
     * Routes to the credit note template when is_credit_note is set, otherwise to
     * the standard invoice template. Allows theme overrides under woocommerce/facturx/.
     */
    private static function render_template( array $data ): string {
        $is_credit_note = ! empty( $data['is_credit_note'] );
        $template_name  = $is_credit_note ? 'credit-note-default.php' : 'invoice-default.php';

        $template = locate_template( 'woocommerce/facturx/' . $template_name );

        if ( ! $template ) {
            $template = GOFACTOX_PLUGIN_DIR . 'templates/' . $template_name;
        }

        /**
         * Filter the absolute path of the PDF template file.
         *
         * Useful for themes or addon plugins that ship a custom layout without
         * forking GoFactoX or overriding via locate_template().
         *
         * @param string $template Default template path.
         * @param array  $data     Invoice/credit note data.
         * @param bool   $is_credit_note Whether this document is a credit note.
         */
        $template = apply_filters( 'gofactox_pdf_template_path', $template, $data, $is_credit_note );

        // Extract data for the template.
        $invoice = $data;

        ob_start();
        include $template;
        return ob_get_clean();
    }
}
