<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load configuration
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
} elseif (file_exists('/config.php')) {
    require_once('/config.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;

// Remove any existing reports.pdf file
$files = glob('../../../' . TENANT_URL . '/output/reports/' . $_REQUEST['dest'] . '/reports.pdf');
foreach ($files as $file) {
    if (is_file($file)) {
        unlink($file);
    }
}

// Explode files from the request
$files = explode('|', $_REQUEST['files']);
$dest = '../../../' . TENANT_URL . '/output/reports/' . $_REQUEST['dest'] . "/";

// 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 = explode('-', $file);
            $reportPath = $dest . $f[0] . '_' . $f[1] . '.pdf';
        } else {
            // Direct filename format, e.g., 1725572144_multi_66
            $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: " . $reportPath;
        }
    }

    // Handle attaching WS if requested (assuming some WS handling logic is needed here)
    if ($_REQUEST['ws'] == "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: ',  $e->getMessage(), "\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|