<?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');}
if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();
require_once(__DIR__ . '/../deliveryModules/reportListHelpers.php');


$clientnumber = enrep_request_int('clientnumber');
if ($clientnumber < 1) {
    enrep_fail(400, 'Invalid client');
}
$tenantDir = defined('TENANT_URL') ? trim((string)TENANT_URL, "/\\") : $tenant;
$path='../../../'.$tenantDir.'/output/reports/'.$clientnumber.'/';
$count=0;
$defectListRaw = enrep_request_string('defectList', '', 1000000);
$arrays = delivery_report_list_tokens($defectListRaw);
$theZip=$clientnumber.'-defect_'.random_int(100000, 999999).'.zip';
$zip = new ZipArchive;
if ($zip->open($path.$theZip, ZipArchive::CREATE) === TRUE)
{
foreach($arrays as $a){
$items = delivery_report_token_parts($a);
if(!empty($items['repnumber']) && preg_match('/\A[A-Za-z0-9_ -]+\z/', (string)$items['repnumber'])){
$fileName = $items['repnumber'].'.pdf';
if (is_file($path.$fileName)) { $zip->addFile($path.$fileName,$fileName); }
$count++;
}
}
$zip->close();
echo $theZip.$defectListRaw;
}
else{echo "error";}
?>
