<?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;
$mode = enrep_request_enum('mode', ['hse', ''], '');

function genzip_safe_pdf_name(string $name): string
{
    if (!preg_match('/\A[A-Za-z0-9_ -]+\z/', $name)) {
        enrep_fail(400, 'Invalid report file');
    }
    return $name . '.pdf';
}

function genzip_cover_files(string $raw): array
{
    if (trim($raw) === '') {
        return [];
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        return [];
    }

    $files = [];
    foreach ($decoded as $entry) {
        $file = is_array($entry) ? (string)($entry['file'] ?? '') : (string)$entry;
        $file = enrep_safe_filename($file);
        if (!preg_match('/\Areport_cover(?:_[A-Za-z0-9_-]+)?\.pdf\z/', $file)) {
            enrep_fail(400, 'Invalid cover file');
        }
        $files[] = $file;
    }

    return array_values(array_unique($files));
}

function genzip_add_cover_files(ZipArchive $zip, string $path, array $coverFiles): void
{
    if (empty($coverFiles)) {
        $coverFiles = ['report_cover.pdf'];
    }

    foreach ($coverFiles as $coverFile) {
        if (is_file($path . $coverFile)) {
            $zip->addFile($path . $coverFile, $coverFile);
        }
    }
}

$coverFiles = genzip_cover_files(enrep_request_string('covers', '', 1000000));

if($mode=="hse"){

$path='../../../'.$tenantDir.'/output/reports/'.$clientnumber.'/';

$arrays = delivery_report_list_tokens(enrep_request_string('items', '', 1000000));


$theZip=$clientnumber.'_'.random_int(100000, 999999).'_hse.zip';
$zip = new ZipArchive;
if ($zip->open($path.$theZip, ZipArchive::CREATE) === TRUE)
{
genzip_add_cover_files($zip, $path, $coverFiles);
foreach($arrays as $a){
$items = delivery_report_token_parts($a);
if (!empty($items['repnumber']) && ctype_digit((string)$items['repnumber']) && ctype_digit((string)$items['itemnumber'])) {
$fileName = $items['repnumber'].'_'.$items['itemnumber'].'.pdf';
if (is_file($path.$fileName)) { $zip->addFile($path.$fileName,$fileName); }
}
}
$zip->close();
echo $clientnumber."|".$theZip;
}
else{echo "error";}

}
else{
    function getPssrNo($itemnumber){
        //check for instance
        $stmt = $GLOBALS['con']->prepare("SELECT `wsnumber` FROM `wsitems` WHERE `itemnumber`=?")or die($error=mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i',$itemnumber);$stmt->execute();$res=$stmt->get_result();$stmt->close();
        $d=mysqli_fetch_array($res);
           
        if(empty($d['wsnumber'])){return 'None found';}
        else{return $d['wsnumber'];}
    }



$files = glob('../../../'.$tenantDir.'/output/reports/'.$clientnumber.'/*.zip');
foreach($files as $file){
//if(is_file($file))
//unlink($file);
}
$ziparray=array();
$path='../../../'.$tenantDir.'/output/reports/'.$clientnumber.'/';
$wspath='../../../'.$tenantDir.'/output/wsfiles/'.$clientnumber.'/';

$arrays = delivery_report_list_tokens(enrep_request_string('items', '', 1000000));
$wsarray = delivery_report_list_tokens(enrep_request_string('ws', '', 1000000));
$wsMode = enrep_request_string('ws', '', 1000000);
$schMode = enrep_request_enum('schMode', ['attach', ''], '');
$theZip=$clientnumber.'_'.random_int(100000, 999999).'.zip';
$zip = new ZipArchive;
if ($zip->open($path.$theZip, ZipArchive::CREATE) === TRUE)
{
genzip_add_cover_files($zip, $path, $coverFiles);

if($schMode=="attach"){
$scheduleFile = $clientnumber.'_schedule.pdf';
if (is_file($path.$scheduleFile)) { $zip->addFile($path.$scheduleFile,$scheduleFile); }
}

if($wsMode!='bypass'){
    foreach($wsarray as $a){
    $wsitems = delivery_report_token_parts($a);       
    $pssr=getPssrNo((int)$wsitems['itemnumber']);
    if($pssr=="None found"){}
    else{
        if(in_array($pssr,$ziparray)){}
        else{
        $wsFile = 'WS'.preg_replace('/[^A-Za-z0-9_-]/', '', (string)$pssr).'.pdf';
        if (is_file($wspath.$wsFile)) { $zip->addFile($wspath.$wsFile,$wsFile); }
        $ziparray[]=$pssr;
        }
    }
    }
}

foreach($arrays as $a){
$items = delivery_report_token_parts($a);

if(!empty($items['repnumber'])){
if(stripos($items['repnumber'],'multi') !== false){$m="yes";
$fileName = genzip_safe_pdf_name((string)$items['repnumber']);
if (is_file($path.$fileName)) { $zip->addFile($path.$fileName,$fileName); }
}
else if (ctype_digit((string)$items['repnumber']) && ctype_digit((string)$items['itemnumber'])){
$fileName = $items['repnumber'].'_'.$items['itemnumber'].'.pdf';
if (is_file($path.$fileName)) { $zip->addFile($path.$fileName,$fileName); }
}

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

}
?>
