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

$payload = delivery_json_input();
$tenant = delivery_load_tenant();
$manifest = delivery_manifest($payload);

$coverTemplate = trim((string)($manifest['options']['coverTemplate'] ?? 'default'));
if ($coverTemplate === '') {
    $coverTemplate = 'default';
}

$_REQUEST['tenant'] = $tenant;
$_REQUEST['clientnumber'] = (string)$manifest['clientnumber'];
$_REQUEST['site'] = (string)$manifest['site'];
$_REQUEST['mode'] = 'split';
$_REQUEST['cover_template'] = $coverTemplate;
$_POST['cover_template'] = $coverTemplate;

$generatorOutput = delivery_generator_include('genShed.php');
if ($generatorOutput !== '') {
    @file_put_contents(
        __DIR__ . '/error_log',
        '[' . date('Y-m-d H:i:s') . '] genShed.php unexpected output: ' . $generatorOutput . PHP_EOL,
        FILE_APPEND
    );
    enrep_fail(500, 'Unable to generate schedule');
}

$file = $manifest['clientnumber'] . '_schedule.pdf';
delivery_response([
    'ok' => true,
    'files' => [delivery_file_entry($manifest['clientnumber'], $file, 'sch')],
]);
