<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}

if($_REQUEST['mode']=="hse"){

$path='../../../'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/';

$arrays=explode('|',$_REQUEST['items']);


$theZip=$_REQUEST['clientnumber'].'_'.rand().'_hse.zip';
$zip = new ZipArchive;
if ($zip->open($path.$theZip, ZipArchive::CREATE) === TRUE)
{
//$zip->addFile($path.'report_cover.pdf','report_cover.pdf');
foreach($arrays as $a){
$items=explode('-',$a);
if(!empty($items[0])){
$zip->addFile($path.$items[0].'_'.$items[1].'.pdf',$items[0].'_'.$items[1].'.pdf');
}
}
$zip->close();
echo $_REQUEST['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('../../../'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/*.zip');
foreach($files as $file){
//if(is_file($file))
//unlink($file);
}
$ziparray=array();
$path='../../../'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/';
$wspath='../../../'.TENANT_URL.'/output/wsfiles/'.$_REQUEST['clientnumber'].'/';

$arrays=explode('|',$_REQUEST['items']);
$wsarray=explode('|',$_REQUEST['ws']);
$theZip=$_REQUEST['clientnumber'].'_'.rand().'.zip';
$zip = new ZipArchive;
if ($zip->open($path.$theZip, ZipArchive::CREATE) === TRUE)
{
$zip->addFile($path.'report_cover.pdf','report_cover.pdf');

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

if($_REQUEST['ws']!='bypass'){
    foreach($wsarray as $a){
    $wsitems=explode('-',$a);       
    $pssr=getPssrNo($wsitems[1]);
    if($pssr=="None found"){}
    else{
        if(in_array($pssr,$ziparray)){}
        else{
        $zip->addFile($wspath.'WS'.$pssr.'.pdf','WS'.$pssr.'.pdf');
        $ziparray[]=$pssr;
        }
    }
    }
}

foreach($arrays as $a){
$items=explode('-',$a);

if(!empty($items[0])){
if(stripos($items[0],'multi')){$m="yes";
$zip->addFile($path.$items[0].'.pdf',$items[0].'.pdf');
}
else{
$zip->addFile($path.$items[0].'_'.$items[1].'.pdf',$items[0].'_'.$items[1].'.pdf');
}

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

}
?>