<?php 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');
if (!function_exists('enrep_itemdetails_pressure_from_record')) {
    require_once __DIR__ . '/../itemdetails_json.php';
}

$wrapper_Start = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="packages/bootstrap/bootstrap.gen.css" rel="stylesheet">
</head>

<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="font-size:10px!important">
    ';

$wrapper_End = '</body>

</html>';

function getWsItemReportDetails($repnumber, $type)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `reptype`,`insdate`,`repdate` FROM `reportitems` WHERE `repnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $repnumber);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
    switch ($type) {
        case "REPNO":
            return $cd['reptype'];
            break;
        case "EXAM_DATE":
            return date('d-m-Y', $cd['insdate']);
            break;
        case "REPORT_DATE":
            return date('d-m-Y', $cd['insdate']);
            break;
    }
}

function getWsSurveyorDetails($surveyor, $type)
{
    $stmt2 = $GLOBALS['con']->prepare("SELECT `surname`,`forename`,`qual` FROM `surveyor` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
    $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;
    }
}
//GET WS DETAILS

$wsno = "WS" . $_REQUEST['wsnumber'];
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `writtenscheme` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['wsnumber']);
$stmt->execute();
$ws = $stmt->get_result();
$stmt->close();
$wsd = mysqli_fetch_array($ws);


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

//CHECK DIR AND POPULATE
if (!file_exists('../../../' . TENANT_URL . '/output/wsfiles/' . $_REQUEST['clientnumber'])) {
    mkdir('../../../' . TENANT_URL . '/output/wsfiles/' . $_REQUEST['clientnumber']);
}

//BUILD ITEM LIST
$c = 1;


$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsitems` WHERE `wsnumber`=? AND `type`='1'") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['wsnumber']);
$stmt->execute();
$wsi = $stmt->get_result();
$stmt->close();
$isOne = mysqli_num_rows($wsi);
if ($isOne == 1 && $_REQUEST['type'] == "single") {
    $isSingle = "yes";
} else {
    $isSingle = "no";
}

while ($wsid = mysqli_fetch_array($wsi)) {
    $a = 0;
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`desc`,`serialnumber`,`plantnumber`,`locnumber`,`manf`,`subloc`,`dateofmanf`,`swl`,`plantnumber`,`pressure_data` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error("ITEM RECALL: " . $GLOBALS['con']));
    $stmt->bind_param('i', $wsid['itemnumber']);
    $stmt->execute();
    $icx = $stmt->get_result();
    $stmt->close();
    $itd = mysqli_fetch_array($icx);
    if (is_array($itd)) {
        $itd = array_replace($itd, enrep_itemdetails_pressure_from_record($itd));
    }

    if ($itd['thorough'] == "999") {
        $itd['thorough'] = "(N)";
    } else {
        $itd['thorough'] = $itd['thorough'];
    }
    if ($itd['intermediate'] == "999") {
        $itd['intermediate'] = "(N)";
    } else {
        $itd['intermediate'] = $itd['intermediate'];
    }

    $swsItemDetails = array_filter([
        $wsid['itemnumber'] . '-' . ($itd['desc'] ?? ''),
        $itd['plantnumber'] ?? '',
        $itd['serialnumber'] ?? '',
        $itd['manf'] ?? '',
        $itd['dateofmanf'] ?? '',
        $itd['subloc'] ?? '',
        $itd['vessel_volume'] ?? '',
    ], static function ($value) {
        return trim((string)$value) !== '' && trim((string)$value) !== '-';
    });
    $swsPeriods = [];
    if (trim((string)($itd['thorough'] ?? '')) !== '') {
        $swsPeriods[] = $itd['thorough'] . ' (T)';
    }
    if (trim((string)($itd['intermediate'] ?? '')) !== '') {
        $swsPeriods[] = $itd['intermediate'] . ' (W)';
    }

    $swsList .= '
<tr valign="top">
<td>' . implode('<br />', $swsItemDetails) . '</td>
<td align="center">' . $wsd['wSol'] . '</td>
<td align="center">' . implode('<br />', $swsPeriods) . '</td>
</tr>';

$wsList .= '
<tr valign="top">
<td style="vertical-align:top">00' . $c . ' </td>
<td style="vertical-align:top">' . implode('<br />', $swsItemDetails) . '</td>
<td align="center" style="vertical-align:top">' . $itd['swl'] . '</td>
<td align="center" style="vertical-align:top">' . $itd['thorough'] . '</td>
<td align="center" style="vertical-align:top">' . $itd['intermediate'] . '</td>
<td style="vertical-align:top">PSR/01</td>
</tr>
';

    if ($itd['valve'] != "") {
        $ar = array();
        $ar = enrep_itemdetails_decode_legacy_list($itd['valve']);
        if (is_array($ar)) {
            foreach ($ar as $ad) {
                $char = $string[$a++];
                $wsList .= '
<tr valign="top">
<td style="vertical-align:top">00' . $c . $char . '</td>
<td style="vertical-align:top"><b>Safety Valve</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['range'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['TEP'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['IEP'] . '</td>
<td style="vertical-align:top">PSR/02</td>
</tr>
';

                $swsList .= '
<tr valign="top">
<td><b>Safety Valve</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
<td align="center">' . $ad['range'] . '</td>
<td align="center">' . $ad['TEP'] . ' (T)<br>' . $ad['IEP'] . ' (W)</td>
</tr>
';
            }
        }
    }

    if ($itd['gauge'] != "") {
        $ar = array();
        $ar = enrep_itemdetails_decode_legacy_list($itd['gauge']);
        if (is_array($ar)) {
            foreach ($ar as $ad) {
                $char = $string[$a++];
                $wsList .= '
<tr valign="top">
<td style="vertical-align:top">00' . $c . $char . '</td>
<td style="vertical-align:top"><b>Pressure Gauge</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['range'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['TEP'] . '</td>
<td align="center" style="vertical-align:top">' . $ad['IEP'] . '</td>
<td style="vertical-align:top">PSR/02</td>
</tr>
';

                $swsList .= '
<tr valign="top">
<td><b>Pressure Gauge</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
<td align="center">' . $ad['range'] . '</td>
<td align="center">' . $ad['TEP'] . ' (T)<br>' . $ad['IEP'] . ' (W)</td>
</tr>
';
            }
        }
        $char++;
    }

    if ($itd['burst'] != "") {
        $ar = array();
        $ar = enrep_itemdetails_decode_legacy_list($itd['burst']);
        if (is_array($ar)) {
            foreach ($ar as $ad) {
                $char = $string[$a++];
                $wsList .= '
    <tr valign="top">
    <td style="vertical-align:top">00' . $c . $char . '</td>
    <td style="vertical-align:top"><b>Burst Disk</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
    <td align="center" style="vertical-align:top">' . $ad['range'] . '</td>
    <td align="center" style="vertical-align:top">' . $ad['TEP'] . '</td>
    <td align="center" style="vertical-align:top">' . $ad['IEP'] . '</td>
    <td style="vertical-align:top">PSR/02</td>
    </tr>
    ';

                $swsList .= '
    <tr valign="top">
    <td><b>Burst Disk</b><br>' . $ad['serial'] . '<br>' . $ad['make'] . '</td>
    <td align="center">' . $ad['range'] . '</td>
    <td align="center">' . $ad['TEP'] . ' (T)<br>' . $ad['IEP'] . ' (W)</td>
    </tr>
    ';
            }
        }
    }

    $c++;
}

//BUILD EXCLUSION LIST
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsitems` WHERE `wsnumber`=? AND `type`='0'") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['wsnumber']);
$stmt->execute();
$wsi = $stmt->get_result();
$stmt->close();
while ($wsid = mysqli_fetch_array($wsi)) {
    $wsexList .= '
<tr valign="top">
<td>00' . $c . ' </td>
<td>' . $wsid['desc'] . '</td>
<td>' . $wsid['swl'] . '</td>
</tr>
';
    $c++;
}

//BUILD REVISION LIST
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `wsrevisions` WHERE `wsnumber`=? ORDER BY ABS(date) DESC") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['wsnumber']);
$stmt->execute();
$wsi = $stmt->get_result();
$stmt->close();
while ($wsid = mysqli_fetch_array($wsi)) {
    $revList .= '
<tr valign="top">
<td>' . date('d-m-Y', $wsid['date']) . ' </td>
<td>' . $wsid['description'] . '</td>
<td><img src="../../../' . TENANT_URL . '/images/signatures/' . $wsid['surveyor'] . '.jpg" style="width:120px; margin: 0; padding: 0;" /></td>
</tr>
';
}
if (!is_dir('../../../' . TENANT_URL . '/output/wsfiles/' . $_REQUEST['clientnumber'])) {
    mkdir('../../../' . TENANT_URL . '/output/wsfiles/' . $_REQUEST['clientnumber']);
}

$filestore = '../../../' . TENANT_URL . '/output/wsfiles/' . $_REQUEST['clientnumber'] . '/' . $wsno . '.pdf';
include('../../includes/engines/ws.pdf.engine');
