<?php
require_once __DIR__ . '/security.php';
require_once '../packages/fpdi/fpdf.php';
require_once '../packages/fpdi/autoload.php';

use setasign\Fpdi\Fpdi;

$files = json_decode($_REQUEST['files'] ?? '[]', true);
$client = preg_replace('/[^0-9]/', '', (string)($_REQUEST['client'] ?? ''));
$tenant = enrep_tenant_segment($_REQUEST['tenant'] ?? '');

if (!is_array($files) || $client === '' || $tenant === '') {
    http_response_code(400);
    echo 'Invalid print request';
    exit;
}

$output = enrep_tenant_path($tenant, 'output/reports/' . $client . '/reports.pdf');

function printMergeResolveTenantFile(string $tenant, string $file): string
{
    $file = trim(str_replace('\\', '/', $file));
    $file = preg_replace('#^\.\./#', '', $file);
    $file = ltrim((string)$file, '/');

    if ($file === '' || strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'pdf') {
        return '';
    }

    return enrep_tenant_path($tenant, $file);
}

$pdf = new Fpdi();
$pdf->SetAutoPageBreak(false);

foreach ($files as $file) {
    $file = printMergeResolveTenantFile($tenant, (string)$file);
    if ($file === '' || !is_file($file)) {
        continue;
    }

    $pageCount = $pdf->setSourceFile($file);
    for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
        $template = $pdf->importPage($pageNo);
        $size = $pdf->getTemplateSize($template);
        $width = $size['width'] ?? $size['w'];
        $height = $size['height'] ?? $size['h'];
        $orientation = $width > $height ? 'L' : 'P';

        $pdf->AddPage($orientation, [$width, $height]);
        $pdf->useTemplate($template);
    }
}

if ($pdf->PageNo() < 1) {
    http_response_code(400);
    echo 'No printable PDFs found';
    exit;
}

$outputDir = dirname($output);
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0755, true);
}

$pdf->Output('F', $output);
echo 's';
