<?php
require_once __DIR__ . '/../security.php';

// Load configuration
$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.php');
}
if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();
require_once(__DIR__ . '/../deliveryModules/reportListHelpers.php');

echo "start";

// Load the FPDI library (you should have FPDI installed or included properly)
require_once('../../packages/fpdi/autoload.php'); // Adjust this path as needed
require_once('../../packages/fpdi/fpdf.php'); // Make sure you include FPDF as well

use setasign\Fpdi\Fpdi;

$destClient = enrep_request_int('dest');
if ($destClient < 1) {
    enrep_fail(400, 'Invalid destination');
}
$tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : $tenant;

// Remove any existing reports.pdf file
$files = glob('../../../' . $tenantDir . '/output/reports/' . $destClient . '/reports.pdf');
foreach ($files as $file) {
    if (is_file($file)) {
        unlink($file);
    }
}

// Decode files from the request. New flow sends a JSON array; legacy pipe strings are still accepted.
$files = delivery_report_list_tokens(enrep_request_string('files', '', 1000000));
$dest = '../../../' . $tenantDir . '/output/reports/' . $destClient . "/";

// Initialize FPDI
$pdf = new Fpdi();

try {
    // Add the cover page first
    $pdf->AddPage('L');
    $pdf->setSourceFile($dest . 'report_cover.pdf');
    $tplIdx = $pdf->importPage(1); // Adjust if cover has multiple pages
    $pdf->useTemplate($tplIdx);

    // Loop through the report files
    foreach ($files as $file) {
        // Check if the file contains a hyphen (-) or not
        if (strpos($file, '-') !== false) {
            // Hyphenated format, e.g., 1725045448-56299-500-60
            $f = delivery_report_token_parts($file);
            if (!ctype_digit((string)($f['repnumber'] ?? '')) || !ctype_digit((string)($f['itemnumber'] ?? ''))) {
                continue;
            }
            $reportPath = $dest . $f['repnumber'] . '_' . $f['itemnumber'] . '.pdf';
        } else {
            // Direct filename format, e.g., 1725572144_multi_66
            if (!preg_match('/\A[A-Za-z0-9_ -]+\z/', (string)$file)) {
                continue;
            }
            $reportPath = $dest . $file . '.pdf';
        }
    
        // Check if the file exists
        if (file_exists($reportPath)) {
            $pageCount = $pdf->setSourceFile($reportPath);
            
            // Import each page from the PDF
            for ($i = 1; $i <= $pageCount; $i++) {
                $pdf->AddPage();
                $tplIdx = $pdf->importPage($i);
                $pdf->useTemplate($tplIdx);
            }
        } else {
            echo "File not found";
        }
    }

    // Handle attaching WS if requested (assuming some WS handling logic is needed here)
    if (enrep_request_string('ws', '', 20) == "attach") {
        // Add logic to attach WS documents if needed
    }

    // Save the merged PDF to the destination
    $outputFile = $dest . 'report.pdf';
    $pdf->Output('F', $outputFile); // Save the merged file

    echo "done";

} catch (Exception $e) {
    // Output any exceptions for debugging purposes
    echo 'Error: Unable to generate PDF', "\n";
}

?>


1725045448-56299-500-60|1725572142_multi_60|1725572144_multi_66|


1725101916-56291--60|1725101916-52352--60|1725045448-56299-500-60|1725034219-56294-503-66|1725034219-56293-503-66|1725014734-56292-503-60|1725014734-56290-503-60|
