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

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

$clientnumber = (int)$manifest['clientnumber'];
$files = delivery_unique_files($payload['files'] ?? []);
$wsResult = delivery_written_scheme_result($manifest, $tenant);
$files = array_merge($files, $wsResult['files']);
$files = delivery_unique_files($files);

$path = delivery_output_path($tenant, $clientnumber);
if (!is_dir($path)) {
    mkdir($path, 0755, true);
}

$zipName = $clientnumber . '_' . random_int(100000, 999999) . '.zip';
$zip = new ZipArchive();

if ($zip->open($path . $zipName, ZipArchive::CREATE) !== true) {
    enrep_fail(500, 'Unable to create ZIP');
}

$tenantDir = delivery_tenant_dir($tenant);
$added = [];

foreach ($files as $file) {
    $source = trim((string)$file['source'], '/');
    $name = delivery_safe_file((string)$file['file']);
    $absolute = '../../../' . $tenantDir . '/' . $source . '/' . $name;
    if (!is_file($absolute)) {
        continue;
    }
    if (isset($added[$name])) {
        continue;
    }
    $zip->addFile($absolute, $name);
    $added[$name] = true;
}

$zip->close();

delivery_response([
    'ok' => true,
    'files' => [delivery_file_entry($clientnumber, $zipName, 'zip', null, [
        'contents' => $files,
    ])],
    'included' => array_keys($added),
    'warnings' => $wsResult['warnings'],
]);
