<?php
/**
 * PDF Helper
 * --------------------------------------------------------------
 * Converts an HTML string into a real downloadable PDF file using
 * DOMPDF (installed via: composer require dompdf/dompdf).
 *
 * If DOMPDF is not installed, falls back to outputting the HTML
 * directly with window.print() auto-triggered, so the user can
 * still save as PDF via the browser's print dialog - the app
 * keeps working either way, just with a true one-click download
 * once DOMPDF is present.
 * --------------------------------------------------------------
 */

$autoload = __DIR__ . '/../vendor/autoload.php';
if (file_exists($autoload)) {
    require_once $autoload;
}

class PdfHelper {

    /**
     * Output a PDF to the browser (downloads or opens inline).
     *
     * @param string $html       Full HTML document string to render
     * @param string $filename   Suggested filename, e.g. "purchase_report.pdf"
     * @param bool   $download   true = force download, false = inline view
     */
    public static function output($html, $filename, $download = true) {
        if (class_exists('Dompdf\Dompdf')) {
            try {
                $pdfContent = self::renderToString($html);
                $disposition = $download ? 'attachment' : 'inline';
                header('Content-Type: application/pdf');
                header("Content-Disposition: $disposition; filename=\"$filename\"");
                header('Cache-Control: private, max-age=0, must-revalidate');
                header('Pragma: public');
                echo $pdfContent;
                exit;
            } catch (Exception $e) {
                error_log('DOMPDF Error: ' . $e->getMessage());
                // Fall through to HTML fallback below
            }
        }

        // Fallback: serve as printable HTML with auto-print
        header('Content-Type: text/html; charset=UTF-8');
        echo '<!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8">
        <title>' . htmlspecialchars($filename) . '</title>
        <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        @media print {
            body { padding: 0; }
        }
        </style>
        </head>
        <body onload="window.print();">
        ' . $html . '
        <script>
        setTimeout(function() {
            if (!window.print) {
                window.close();
            }
        }, 5000);
        </script>
        </body>
        </html>';
        exit;
    }

    /**
     * Generate PDF as a binary string (for email attachments).
     * Returns the raw PDF bytes, or null if DOMPDF is not available.
     *
     * @param string $html   Full HTML document string to render
     * @return string|null   PDF binary content, or null on failure
     */
    public static function generateString($html) {
        if (!class_exists('Dompdf\Dompdf')) {
            return null;
        }
        try {
            return self::renderToString($html);
        } catch (Exception $e) {
            error_log('DOMPDF generateString Error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Whether true PDF generation is available (DOMPDF installed).
     */
    public static function isAvailable() {
        return class_exists('Dompdf\Dompdf');
    }

    // -------------------------------------------------------
    // Private: shared DOMPDF rendering logic
    // -------------------------------------------------------
    private static function renderToString($html) {
        $options = new \Dompdf\Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', false);
        $options->set('defaultFont', 'DejaVu Sans');
        $options->set('isFontSubsettingEnabled', true);
        $options->set('tempDir', sys_get_temp_dir());

        $dompdf = new \Dompdf\Dompdf($options);
        $dompdf->setPaper('A4', 'portrait');
        $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
        $dompdf->loadHtml($html);
        $dompdf->render();
        return $dompdf->output();
    }
}