<?php
ini_set('max_execution_time', '90');
ini_set('memory_limit', '512M');
if (function_exists('set_time_limit')) {
    set_time_limit(90);
}

require_once __DIR__ . '/helpers.php';

$payload = delivery_json_input();
$tenant = delivery_load_tenant();
$manifest = delivery_manifest($payload);
$reports = array_values(array_filter(array_map('delivery_report_normalise', $payload['reports'] ?? [])));
$form = (int)($payload['form'] ?? 0);
$maxMultiBatch = 500;

if (count($reports) < 1 || $form < 1) {
    enrep_fail(400, 'Invalid multi report request');
}

if (count($reports) > $maxMultiBatch) {
    enrep_fail(400, 'Multi PDF batch too large. Please reduce the selected reports for this form and surveyor.');
}

if (count($reports) === 1) {
    $file = delivery_report_file($reports[0]);
    delivery_response([
        'ok' => true,
        'files' => [delivery_file_entry((int)$manifest['clientnumber'], $file, 'pdf', null, $reports[0])],
    ]);
}

$_REQUEST['tenant'] = $tenant;
$_REQUEST['clientnumber'] = (string)$manifest['clientnumber'];
$_REQUEST['items'] = array_map('delivery_report_token', $reports);
$_REQUEST['form'] = (string)$form;
$_REQUEST['mode'] = '';

$name = delivery_generator_include('genMultiPDF.php');
$name = trim(preg_replace('/[^A-Za-z0-9_ -]/', '', $name));
if ($name === '') {
    enrep_fail(500, 'Unable to generate multi PDF');
}

delivery_response([
    'ok' => true,
    'files' => [delivery_file_entry((int)$manifest['clientnumber'], $name . '.pdf', 'mpdf', null, [
        'contents' => $reports,
    ])],
]);
