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

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

enrep_require_user();

$clientnumber = enrep_request_int('clientnumber');
$wsnumber = enrep_request_int('wsnumber');
$mode = enrep_request_enum('mode', ['full', 'internal', 'single'], 'single');
$itemsRaw = enrep_request_string('items', '', 1000000);
$tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : $tenant;

if ($clientnumber < 1 || $wsnumber < 1 || $tenantDir === '') {
    enrep_fail(400, 'Invalid written scheme zip request');
}

$reportPath = '../../../' . $tenantDir . '/output/reports/' . $clientnumber . '/';
$wsPath = '../../../' . $tenantDir . '/output/wsfiles/' . $clientnumber . '/';

if (!is_dir($wsPath)) {
    enrep_fail(400, 'Written scheme output folder not found');
}

$files = glob($reportPath . '*.zip') ?: [];
foreach ($files as $file) {
    $target = realpath($file);
    $reportBase = realpath($reportPath);
    if ($target !== false && $reportBase !== false && strpos($target, $reportBase . DIRECTORY_SEPARATOR) === 0 && is_file($target)) {
        unlink($target);
    }
}

$arrays = preg_split('/[|,\s]+/', $itemsRaw, -1, PREG_SPLIT_NO_EMPTY);
$safeReports = [];
foreach ($arrays as $item) {
    $item = trim((string)$item);
    if (preg_match('/\A[0-9]+_[0-9]+\z/', $item)) {
        $safeReports[] = $item;
    }
}

$theZip = ($mode === 'single') ? 'WS' . $wsnumber . '_ws.zip' : 'WS' . $wsnumber . '_full.zip';
$zip = new ZipArchive;
if ($zip->open($wsPath . $theZip, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
    $mainWs = $wsPath . 'WS' . $wsnumber . '.pdf';
    if (is_file($mainWs)) {
        $zip->addFile($mainWs, 'WS' . $wsnumber . '.pdf');
    }

    if ($mode === 'full' || $mode === 'internal') {
        $cover = $wsPath . 'WS' . $wsnumber . '_reportcover.pdf';
        if (is_file($cover)) {
            $zip->addFile($cover, 'WS' . $wsnumber . '_reportcover.pdf');
        }
    }

    if ($mode !== 'internal') {
        $revisions = $wsPath . 'WS' . $wsnumber . '_revisions.pdf';
        if (is_file($revisions)) {
            $zip->addFile($revisions, 'WS' . $wsnumber . '_revisions.pdf');
        }
    }

    if ($mode === 'full' || $mode === 'internal') {
        foreach ($safeReports as $report) {
            $file = $reportPath . $report . '.pdf';
            if (is_file($file)) {
                $zip->addFile($file, $report . '.pdf');
            }
        }
    }

    $zip->close();
    echo $theZip;
} else {
    echo "error";
}
