<?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('../../includes/master/form_functions.php');

$wsnumber = enrep_request_int('wsnumber');
if ($wsnumber < 1) {
    enrep_fail(400, 'Invalid written scheme');
}

$wsno="WS".$wsnumber;
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `writtenscheme` WHERE `id`=?")or die(mysqli_error($e="GET WS ENTRY: ".$GLOBALS['con']));
$stmt->bind_param('i',$wsnumber);$stmt->execute();$ws=$stmt->get_result();$stmt->close();
$wsd=mysqli_fetch_array($ws);
if (!$wsd) {
    enrep_fail(404, 'Written scheme not found');
}
$clientnumber = (int)$wsd['clientnumber'];

//GET CLIENT DETAILS
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname`,`address1`,`address2`,`town`,`county`,`postcode`,`contract_number` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $clientnumber);
$stmt->execute();$cc=$stmt->get_result();$stmt->close();
$cd=mysqli_fetch_array($cc);

//CHECK DIR AND POPULATE
$outputDir = '../../../'.TENANT_URL.'/output/wsfiles/'.$clientnumber;
if(!is_dir($outputDir)){
mkdir($outputDir, 0775, true);	
}

function getWsSurveyorDetails($surveyor,$type){
$stmt2 = $GLOBALS['con']->prepare("SELECT `surname`,`forename`,`qual` FROM `surveyor` WHERE `id`=?")or die(mysqli_error("getSurveyorDetails: ".$GLOBALS['con']));
$surveyor = (int)$surveyor;
$stmt2->bind_param('i',$surveyor);$stmt2->execute();$sc=$stmt2->get_result();$stmt2->close();	
$sd=mysqli_fetch_array($sc);
switch($type){	
case"SURVEYOR_NAME":return $sd['forename']." ".$sd['surname'];break;
case"SURVEYOR_QUAL":return $sd['qual'];break;
case"SURVEYOR_SIGNITURE":return $surveyor;break;
}
}

//BUILD REVISION LIST
$revList = '';
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsrevisions` WHERE `wsnumber`=? ORDER BY ABS(date) DESC")or die(mysqli_error($e="GET WSE ENTRY: ".$GLOBALS['con']));
$stmt->bind_param('i',$wsnumber);$stmt->execute();$wsi=$stmt->get_result();$stmt->close();
while($wsid=mysqli_fetch_array($wsi)){
$revisionDate = !empty($wsid['date']) ? date('d-m-Y',(int)$wsid['date']) : '';
$revisionDescription = htmlspecialchars((string)$wsid['description'], ENT_QUOTES, 'UTF-8');
$revisionSurveyor = (int)$wsid['surveyor'];
$revList.='
<tr valign="top">
<td>'.$revisionDate.' </td>
<td>'.$revisionDescription.'</td>
<td><img src="../images/signatures/'.$revisionSurveyor.'.jpg" style="width:120px; margin: 0; padding: 0;" /></td>
</tr>
';

}
if(!is_dir($outputDir)){mkdir($outputDir, 0775, true);}

$filestore=$outputDir.'/'.$wsno.'_revisions.pdf';
include('../../includes/engines/ews.pdf.engine');	
?>
