<?php
// In production, disable displaying errors to prevent output before PDF
error_reporting(E_ALL);
ini_set('display_errors', 0); // Log errors instead of displaying them
ini_set('log_errors', 1);     // Ensure errors are logged
ini_set('error_log', __DIR__ . '/php_errors.log'); // Specify log file

// Start output buffering to capture and control all output
ob_start();

try {
    /**
     * Generate PDF from XML file
     * @param string $filepath Path to the XML file
     * @throws Exception If XML validation fails
     */
    function run_brukld($filepath) {
        // Read XML file content
        $fp = fopen($filepath, 'r');
        $xmlfilecontent = fread($fp, filesize($filepath));
        fclose($fp);
        $filename = basename($filepath, '.xml');
        $project_type = NULL;

        // Include necessary function files
        include_once __DIR__ . '/general_funcs.inc';
        include_once __DIR__ . '/pdf_funcs.inc';
        include_once __DIR__ . '/mapping_funcs.inc';
        include_once __DIR__ . '/objects_funcs.inc';
        include_once __DIR__ . '/calculation_funcs.inc';
        include_once __DIR__ . '/compliance_funcs.inc';

        // Validate XML against schema
        $validation = validate_xml_against_schema_brukld($xmlfilecontent);
        if (strlen($validation) > 0) {
            throw new Exception('Schema validation errors: ' . $validation);
        }

        // Generate PDF bytes
        $pdfBytes = project_BRUKLD_PDFreport($xmlfilecontent, $filename, $project_type);

        // Set headers for PDF download
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
        header('Content-Length: ' . strlen($pdfBytes));

        // Output PDF bytes
        echo $pdfBytes;
    }

    // Check if sap_xml is posted
    if (!empty($_POST['sap_xml'])) {
        // Create a temporary XML file
        $tmpFile = __DIR__ . '/temp_' . time() . '.xml';
        file_put_contents($tmpFile, $_POST['sap_xml']);

        // Generate and output the PDF
        run_brukld($tmpFile);

        // Clean up temporary file
        @unlink($tmpFile);

        // Send only the clean PDF output to the browser
        ob_end_flush();
        exit();
    } else {
        // No XML data provided
        ob_end_clean(); // Clear buffer since no PDF is generated
        header('HTTP/1.1 400 Bad Request');
        echo "Error: No 'sap_xml' data posted.";
        exit();
    }

} catch (Throwable $ex) {
    // If an error occurs, discard any buffered output
    ob_end_clean();
    header('HTTP/1.1 500 Internal Server Error');
    echo "Error: " . $ex->getMessage();
    // Log the full stack trace for debugging
    error_log("Exception: " . $ex->getMessage() . "\n" . $ex->getTraceAsString());
    exit();
}
?>