<?php 
ini_set('max_execution_time', '90');
ini_set('memory_limit', '512M');
if (function_exists('set_time_limit')) {
    set_time_limit(90);
}

if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}
 require_once('../../includes/master/form_functions.php');
 require_once('../../packages/phpqrcode/qrlib.php');

$customImages = [];
$customImagesFile = '../../..' . TENANT_URL . '/output/custom_images.php';
if (is_file($customImagesFile)) {
    $customImagesReturn = include $customImagesFile;
    if (is_array($customImagesReturn)) {
        $customImages = $customImagesReturn;
    } elseif (!isset($customImages) || !is_array($customImages)) {
        $customImages = [];
    }
}

$reportImageDefaults = [
    'main_logo' => 40,
    'client_logo' => 40,
    'affiliation_logo' => 40,
];
$reportImageSettings = $reportImageDefaults;

$stmtImg = $GLOBALS['con']->prepare("SELECT `report_image_settings` FROM `system` WHERE `id` = 1 LIMIT 1");
if ($stmtImg) {
    $stmtImg->execute();
    $resImg = $stmtImg->get_result();
    $rowImg = $resImg ? $resImg->fetch_assoc() : null;
    $stmtImg->close();

    if (!empty($rowImg['report_image_settings'])) {
        $tmpImg = json_decode((string)$rowImg['report_image_settings'], true);
        if (is_array($tmpImg)) {
            foreach ($reportImageDefaults as $imageKey => $defaultHeight) {
                $reportImageSettings[$imageKey] = isset($tmpImg[$imageKey]) && preg_match('/^\d{1,2}$/', (string)$tmpImg[$imageKey])
                    ? (int)$tmpImg[$imageKey]
                    : $defaultHeight;
            }
        }
    }
}

function genMultiPdfWriteQr(string $data, string $itemId): void {
    $itemId = preg_replace('/[^A-Za-z0-9_-]/', '', $itemId);
    if ($data === '' || $itemId === '') {
        return;
    }

    $tenantRoot = realpath('../../..' . TENANT_URL);
    if ($tenantRoot === false || !is_dir($tenantRoot)) {
        error_log('Multi PDF QR generation skipped: tenant root not found');
        return;
    }

    $imageDir = $tenantRoot . DIRECTORY_SEPARATOR . 'images';
    if (!is_dir($imageDir) && !mkdir($imageDir, 0775, true) && !is_dir($imageDir)) {
        error_log('Multi PDF QR generation skipped: unable to create image directory');
        return;
    }

    QRcode::png($data, $imageDir . DIRECTORY_SEPARATOR . $itemId . '.png', 'L', 4, 2);
}

 if(!file_exists('../../..'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'])){
    mkdir('../../..'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'], 0775, true);	
    }
//$_REQUEST['repnumber']=1499725635;
//$_REQUEST['item']=315;
//$_REQUEST['form']=503;


foreach($_REQUEST['items'] as $item){ 
    
$tda=explode("-",$item);

$rno=getItemReportType($tda[0]);

$rx=mysqli_query($GLOBALS['con'],"SELECT * FROM `reportitems` WHERE `repnumber`='".$tda[0]."' AND `itemnumber`='".$tda[1]."' ")or die(mysqli_error($GLOBALS['con']));
$cx=mysqli_fetch_array($rx);
$rd = enrepReportDataFromRow($cx ?? []);

$contract=getItemOwner($cx['itemnumber']);
$clt=explode("|",$contract);
$details=getItemDetailed($tda[0],$cx['itemnumber']);
$det=explode("|",$details);
$post='
<table class="tableClientDetails" width="100%">
<tr valign="top">
<td width="30%" valign="top">
<table width="100%">
<tr><th width="25%" class="themeColour">Owner</th><td>'.strtoupper($clt[0]).'</td></tr>
<tr valign="top"><th valign="top"></th><td valign="top">'.getClientAddress($cx['clientnumber'],'address').'</td></tr>
</table>
</td>

<td valign="top">
<table id="clientDetails" width="100%">
<tr valign="top"><th width="20%" class="themeColour">Location</th><td>'.strtoupper(getItemLocation($tda[1],'name')).'</td></tr>
<tr valign="top"><th valign="top"></th><td valign="top">'.getItemLocation($tda[1],'address').'</td></tr>
</table>
</td>

<td valign="top">
<table id="repDetails" class="table-sm" width="100%">
<tr><td align="right"><i>'.nl2br(getItemReportDesc($tda[0],'regs')).'</i></td></tr>
<tr><td align="right" style="font-size:12px"><strong>'.getItemReportDesc($tda[0],'formtype').'</strong></td></tr>
<tr><td align="right"><small><i>Contract Number:</i> '.$clt[1].'</small></td></tr>
<tr><td align="right"><small><i>Report Number:</i> '.$tda[0].'</small></td></tr>
</table>
</td>
</tr>
</table>
';
if($rno=="503"){
    
 $multirow='
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Dates</strong><br>Last (if known)<br>Current<br>Next<br>Item Ref:</td>
<td style="border-right:1px solid #000000" valign="top"><strong>Item Details</strong><br>1: Description; 2: Plant Number; 3: Serial Number; 4:Manufacturer; 5: Date of Manufacture; 6: Model; 7: Sublocation; 8: Detailed Location</td>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Safe Working Load</strong></td>
</tr>
</table>
</td>

<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td valign="top"><b>Reason(s) for being reported as "Not Available"</b> </td>
</tr>
</table>
</td>
</tr>
</table>
<br>
';   
}
if($rno=="502"){
    
 $multirow='
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Dates</strong><br>Last (if known)<br>Current<br>Next<br>Item Ref:</td>
<td style="border-right:1px solid #000000" valign="top"><strong>Item Details</strong><br>1: Description; 2: Plant Number; 3: Serial Number; 4:Manufacturer; 5: Date of Manufacture; 6: Model; 7: Sublocation; 8: Detailed Location</td>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Safe Working Load</strong></td>
</tr>
</table>
</td>

<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td valign="top"><b>A:</strong> Defects which could cause danger to persons. Details of repairs, renewals or alterations necessary to rectify such defects and the time in which they should be completed.<br>
<strong>B:</strong> Other Defects requiring attention.<br>
<strong>C:</strong> Observations and Recommendations.<br>
<b>*Reason(s) for being reported as "Partial"</b> </td>
</tr>
</table>
</td>
</tr>
</table>
<br>
';   
}
if($rno!="502" && $rno!="503"){
$multirow='
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Dates</strong><br>Last (if known)<br>Current<br>Next<br>Item Ref:</td>
<td style="border-right:1px solid #000000" valign="top"><strong>Item Details</strong><br>1: Description; 2: Plant Number; 3: Serial Number; 4:Manufacturer; 5: Date of Manufacture; 6: Model; 7: Sublocation; 8: Detailed Location</td>
<td style="border-right:1px solid #000000" width="20%" valign="top"><strong>Safe Working Load</strong></td>
</tr>
</table>
</td>

<td width="50%" valign="top">
<table id="repText" style="width:100%" cellpadding="2">
<tr>
<td valign="top"><b>A:</strong> Defects which could cause danger to persons. Details of repairs, renewals or alterations necessary to rectify such defects and the time in which they should be completed.<br>
<strong>B:</strong> Other Defects requiring attention.<br>
<strong>C:</strong> Observations and Recommendations.</td>
</tr>
</table>
</td>
</tr>
</table>
<br>
';
}}
$pdf.'
<div style="display:block; border-top: 1px solid #06C; margin-top:20px;  margin-bottom:20px"></div>

';

foreach($_REQUEST['items'] as $item){
$tda=explode("-",$item);

$rno=getItemReportType($tda[0]);
$rx=mysqli_query($GLOBALS['con'],"SELECT * FROM `reportitems` WHERE `repnumber`='".$tda[0]."' AND `itemnumber`='".$tda[1]."' ")or die(mysqli_error($GLOBALS['con']));
$cx=mysqli_fetch_array($rx);
$rd = enrepReportDataFromRow($cx ?? []);

$ix=mysqli_query($GLOBALS['con'],"SELECT * FROM `itemdetails` WHERE `itemnumber`='".$tda[1]."' ")or die(mysqli_error($GLOBALS['con']));
$id=mysqli_fetch_array($ix);

$lx=mysqli_query($GLOBALS['con'],"SELECT `locname` FROM `locations` WHERE `locnumber`='".$id['locnumber']."' ")or die(mysqli_error($GLOBALS['con']));
$ld=mysqli_fetch_array($lx);

/////////////////////////

   
$data = getCompanyDetails('web') . '/preview.php?repnumber=' . $tda[0];
$itemId = $tda[1];
genMultiPdfWriteQr($data, (string)$itemId);

$pdf.='
<table width="100%" style="margin-bottom:20px">
<tbody>
<tr class="rowtitle">
<td class="celltitle">Item Number: <strong>'.$cx['itemnumber'].'</strong></td>
<td class="celltitle" align="right">Report Number: <strong><a class="celllink" href="https://[REPORT_PATH]/preview.php?repnumber='.$cx['repnumber'].'" alt="View Individual Report" title="View Individual Report">'.$cx['repnumber'].'</a></strong></td></tr>
<tr>

<td width="50%" valign="top" style="border:1px solid #1B316E;">
<table id="repText" width="100%">
<tbody>
<tr>
<td style="border-right:1px solid #1B316E" rowspan="8"  width="20%" valign="top">';
if($cx['olddate']!="Not Known" && $cx['olddate']!="" && $cx['olddate']!="0"){$pdf.=date('d-m-Y',$cx['olddate']).'<br>';}else{$pdf.='Not Known<br>';}
if($cx['insdate']!="" && $cx['insdate']!="0"){$pdf.=date('d-m-Y',$cx['insdate']).'<br>';}else{$pdf.='Not Known<br>';}
if($cx['nextDate']!="" && $cx['nextDate']!="0"){$pdf.=date('d-m-Y',$cx['nextDate']).'<br>';}else{$pdf.='Not Known<br>';}

$pdf.='
<img src="../../..' . TENANT_URL . '/images/' . $itemId . '.png" height="40px">
</td>
<td style="border-right:1px solid #1B316E">1: '.$id['desc'].'</td>
<td rowspan="8"  width="20%" valign="top">'.$id['swl'].'</td>
</tr>
<tr><td style="border-right:1px solid #1B316E">2: '.$id['plantnumber'].'</td></tr>
<tr><td style="border-right:1px solid #1B316E">3: '.$id['serialnumber'].'</td></tr>
<tr><td style="border-right:1px solid #1B316E">4: '.$id['manf'].'</td></tr>
<tr><td style="border-right:1px solid #1B316E">5: ';
if($id['dateofmanf']!=""){$pdf.=$id['dateofmanf'];}
else{$pdf.='None Recorded';}
$pdf.='</td></tr>';

$pdf.='
<tr><td style="border-right:1px solid #1B316E">6: '.$id['model'].'</td></tr>
<tr><td style="border-right:1px solid #1B316E">7: '.$id['subloc'].'</td></tr>
<tr><td style="border-right:1px solid #1B316E">8: '.$ld['locname'].'</td></tr>
</tbody>
</table>
</td>
';
if($rno=="503"){
    $pdf.='
<td width="50%" valign="top" height="100%" style="border:1px solid #1B316E; height:100%">
<table id="repText"  width="100%" height="100%">
<tr><td> '.nl2br((string)($rd['pnareason'] ?? '')).'</td></tr>
</table> 
</td>
';

}
if($rno=="502"){
    $pdf.='
<td width="50%" valign="top" height="100%" style="border:1px solid #1B316E; height:100%">
<table id="repText"  width="100%" height="100%">
<tr><td>A: '.nl2br((string)($rd['adefect'] ?? '')).'</td></tr>
<tr><td>B: '.nl2br((string)($rd['bdefect'] ?? '')).'</td></tr>
<tr><td>C: '.nl2br((string)($rd['obs'] ?? '')).'</td></tr>
<tr><td><br>*'.nl2br((string)($rd['partialReason'] ?? '')).'</td></tr>
</table> 
</td>
';

}
if($rno!="502" && $rno!="503"){
$pdf.='
<td width="50%" valign="top" height="100%" style="border:1px solid #1B316E; height:100%">
<table id="repText"  width="100%" height="100%">
<tr><td>A: '.nl2br((string)($rd['adefect'] ?? '')).'</td></tr>
<tr><td>B: '.nl2br((string)($rd['bdefect'] ?? '')).'</td></tr>
<tr><td>C: '.nl2br((string)($rd['obs'] ?? '')).'</td></tr>
</table> 
</td>
';

}
$pdf.='
</tr>
</tbody>
</table>
';

$_REQUEST['repnumber']=$cx['repnumber'];
}

if($rno=="503"){
    $orientation="P";
    $footerTemplate="footer_pna.php";
}
else{
    $orientation="P";
    $footerTemplate="footer_generic.php";   
}

$multiSuffix = preg_replace('/[^A-Za-z0-9_-]/', '', (string)($cx['esname'] ?? '0'));
if ($multiSuffix === '') {
    $multiSuffix = '0';
}
$multipath=strtotime('now').'_'.random_int(1000, 9999).'_multi_'.$multiSuffix;

if($cx['olddate']=="" || $cx['olddate']=="Not Known"){$olddate="Not Known";}
else{$olddate=date('d-m-Y',$cx['olddate']) ;}

if($_REQUEST['mode']=="preview"){
$filestore='../../..'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/preview.pdf';
$orientation="L";
}
else{
if($_REQUEST['mode']=="hse"){
$filestore='../../..'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/'.$_REQUEST['repnumber'].'_'.$cx['esname'].'_HSE.pdf';
$orientation="L";
}
else{
$filestore='../../..'.TENANT_URL.'/output/reports/'.$_REQUEST['clientnumber'].'/'.$multipath.'.pdf';
}
}


$_REQUEST['repnumber']=$cx['repnumber'];
include('../../includes/engines/ext.pdf.engine');
echo $multipath;

?>
