<?php
if (!function_exists('enrep_itemdetails_pressure_from_record')) {
    require_once __DIR__ . '/../../functions/itemdetails_json.php';
}

function wsDataAttachment($itemnumber, $clientnumber): array
{
    $itemnumber = (int)$itemnumber;
    $clientnumber = (int)$clientnumber;
    if ($itemnumber <= 0 || $clientnumber <= 0 || empty($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
        return [];
    }

    $stmt = $GLOBALS['con']->prepare("
        SELECT wi.`wsnumber`, w.`no`, w.`title`, w.`wSol`, w.`wCat`
        FROM `wsitems` wi
        LEFT JOIN `writtenscheme` w ON wi.`wsnumber` = w.`id`
        WHERE wi.`itemnumber` = ?
        LIMIT 1
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_array($res);
    return is_array($row) ? $row : [];
}

function wsDataNotAttachedHtml($clientnumber): string
{
    return '<div class="row"><div class="col-8 alert alert-warning p-1">Item not attached to WS yet, please complete the item registration first.</div>' . listWSE((int)$clientnumber) . '</div>';
}

$wsd = ['wSol' => '', 'wCat' => ''];
if (($_REQUEST['new'] ?? '') !== "yes") {
    $wsd = array_merge($wsd, wsDataAttachment((int)($cd['itemnumber'] ?? 0), (int)($cd['clientnumber'] ?? ($d[0] ?? 0))));
} else {
    $tenant = $_REQUEST['tenant'];

    if (file_exists('../../../' . $tenant . '/config.php')) {
        require('../../../' . $tenant . '/config.php');
    }
    if (file_exists('/config.php')) {
        require('/config.php');
    };

    $d = [
        (int)($_REQUEST['clientnumber'] ?? 0),
        0,
        (int)($_REQUEST['itemnumber'] ?? ($_REQUEST['asset'] ?? 0)),
    ];
    $cd = [
        'itemnumber' => $d[2],
        'clientnumber' => $d[0],
        'thorough' => '',
        'intermediate' => '',
        'valve' => '',
        'gauge' => '',
        'burst' => '',
    ];
    if ($d[2] > 0 && !empty($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $d[2]);
        $stmt->execute();
        $res = $stmt->get_result();
        $stmt->close();
        $row = mysqli_fetch_array($res);
        if (is_array($row)) {
            $cd = array_merge($cd, $row);
        }
    }
    $wsd = array_merge($wsd, wsDataAttachment($d[2], $d[0]));

    function listWSE($client)
    {
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `writtenscheme` WHERE `clientnumber`='" . $client . "' ORDER BY abs(no) ASC ") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $cc = $stmt->get_result();
        $stmt->close();
        $ret = '<div class="col-4"><select id="wsSelect" name="wsSelect" class="form-control autocomplete">';
        $ret .= '<option value="">SELECT SCHEME</option>';
        while ($cd = mysqli_fetch_array($cc)) {
            $ret .= '<option value="' . $cd['id'] . '" data-wstype="' . htmlspecialchars((string)($cd['wstype'] ?? ''), ENT_QUOTES, 'UTF-8') . '">' . $cd['no'] . ':' . $cd['title'] . '</option>';
        }
        $ret .= '</select></div>';
        return $ret;
    }

    function getPssrNo($itemnumber, $clientnumber)
    {
        //check for instance
        $e = wsDataAttachment($itemnumber, $clientnumber);
        if (empty($e['wsnumber'])) {
            return wsDataNotAttachedHtml($clientnumber);
        }
        $schemeParts = [];
        if (trim((string)($e['no'] ?? '')) !== '') {
            $schemeParts[] = trim((string)$e['no']);
        }
        if (trim((string)($e['title'] ?? '')) !== '') {
            $schemeParts[] = trim((string)$e['title']);
        }
        $schemeLabel = trim(implode(' ', $schemeParts));
        $schemeSuffix = $schemeLabel !== '' ? ' <strong>' . htmlspecialchars($schemeLabel, ENT_QUOTES, 'UTF-8') . '</strong>' : ' a Written Scheme';
        return '<div class="alert alert-success">Item is attached to' . $schemeSuffix . '</div>';
    }

    if (($_REQUEST['skip_pssr'] ?? '') !== '1') {
        require('pssr_data.php');
    }
}
if (isset($cd) && is_array($cd)) {
    $cd = array_replace($cd, enrep_itemdetails_pressure_from_record($cd));
}
?>
<div class="clearfix"></div>
<div id="WSIDATA" style="width:100%">
    <div class="col-xl-12">
        <div class="card">
            <div class="card-header">Written Scheme Information</div>
            <div class="card-body">


                <div class="row mb-4">
                    <div class="col-12 col-md-2 mb-3">
                        <label class="control-label" for="thorough">Thorough Examination period of part</label>
                        <select class="form-control" type="text" name="pressure[thorough]" id="thorough" data-mdb-select-init
                            data-mdb-filter="true">
                            <option <?php if ($cd['thorough'] == "") { ?>SELECTED<?php } ?>>SELECT</option>
                            <option value="6" <?php if ($cd['thorough'] == "6") { ?> SELECTED<?php } ?>>6</option>
                            <option value="12" <?php if ($cd['thorough'] == "12" || $cd['thorough'] == "0") { ?>
                                SELECTED<?php } ?>>12</option>
                            <option value="13" <?php if ($cd['thorough'] == "13") { ?> SELECTED<?php } ?>>13</option>
                            <option value="18" <?php if ($cd['thorough'] == "18") { ?> SELECTED<?php } ?>>18</option>
                            <option value="24" <?php if ($cd['thorough'] == "24") { ?> SELECTED<?php } ?>>24</option>
                            <option value="26" <?php if ($cd['thorough'] == "26") { ?> SELECTED<?php } ?>>26</option>
                            <option value="60" <?php if ($cd['thorough'] == "60") { ?> SELECTED<?php } ?>>60</option>
                            <option value="72" <?php if ($cd['thorough'] == "72") { ?> SELECTED<?php } ?>>72</option>
                            <option value="120" <?php if ($cd['thorough'] == "120") { ?> SELECTED<?php } ?>>120</option>
                            <option value="999" <?php if ($cd['thorough'] == "999") { ?> SELECTED<?php } ?>>Desiccant
                            </option>
                        </select>
                    </div>

                    <div class="col-12 col-md-4 mb-3">
                        <label class="control-label" for="currdate">Intermediate Examination period of part</label>
                        <select class="form-control" type="text" name="pressure[intermediate]" id="intermediate"
                            data-mdb-select-init data-mdb-filter="true">
                            <option <?php if ($cd['intermediate'] == "") { ?>SELECTED<?php } ?>>SELECT</option>
                            <option value="12" <?php if ($cd['intermediate'] == "12") { ?> SELECTED<?php } ?>>12
                            <option value="6" <?php if ($cd['intermediate'] == "6" || $cd['intermediate'] == "0") { ?>
                                SELECTED<?php } ?>>6</option>
                            <option value="12" <?php if ($cd['intermediate'] == "12") { ?> SELECTED<?php } ?>>12
                            </option>
                            <option value="13" <?php if ($cd['intermediate'] == "13") { ?> SELECTED<?php } ?>>13
                            </option>
                            <option value="18" <?php if ($cd['intermediate'] == "18") { ?> SELECTED<?php } ?>>18
                            </option>
                            <option value="24" <?php if ($cd['intermediate'] == "24") { ?> SELECTED<?php } ?>>24
                            </option>
                            <option value="26" <?php if ($cd['intermediate'] == "26") { ?> SELECTED<?php } ?>>26
                            </option>
                            <option value="60" <?php if ($cd['intermediate'] == "60") { ?> SELECTED<?php } ?>>60
                            </option>
                            <option value="72" <?php if ($cd['intermediate'] == "72") { ?> SELECTED<?php } ?>>72
                            </option>
                            <option value="120" <?php if ($cd['intermediate'] == "120") { ?> SELECTED<?php } ?>>120
                            </option>
                            <option value="999" <?php if ($cd['intermediate'] == "999") { ?> SELECTED<?php } ?>>
                                Desiccant</option>
                        </select>
                    </div>

                    <div class="col-12 col-md-3 mb-3">
                        <label class="control-label" for="wSol">Safe operating Limit<small class="text-muted"
                                style="font-size:12px"> (Minimum value across the scheme)</small></label>
                        <input type="text" class="form-control" name="wSol" id="wSol" value="<?= $wsd['wSol'] ?>"
                            readonly placeholder="Completed by attached written scheme" />
                    </div>

                    <div class="col-12 col-md-2"><label class="control-label" for="wCat">Pressure system
                            category</label>
                        <input type="text" class="form-control" value="<?= $wsd['wCat'] ?>" readonly
                            placeholder="Completed by attached written scheme" />
                        <input type="hidden" class="form-control" name="wCat" id="wCat" value="<?= $wsd['wCat'] ?>" />
                    </div>



                    <div class="col-md-2"><label class="control-label" for="vessel_volume">Vessel Volume <small>(If
                                applicable)</small></label>
                        <input class="form-control" type="text" name="pressure[vessel_volume]" id="vessel_volume"
                            value="<?= $cd['vessel_volume'] ?>" />
                    </div>

                </div>
                <div class="row">

                    <!-- VALVES -->
                    <div class="col-12 col-md-4 card mb-3">
                        <div class="card-body">
                            <?php $ca = 0;
                            if ($cd['valve'] != "") {
                                $checked = "checked";
                                $av = array();
                                $av = enrep_itemdetails_decode_legacy_list($cd['valve']);
                                if (is_array($av)) {
                                    foreach ($av as $ad) {
                                        $storedValve .= '<div id="valveRow' . $ca . '" class="row border m-0 p-1 mb-3" style="background-color:#f0f0f0"><div class="col-12"><b>VALVE Record</b></div>
                        <div class="col-6">
                        <label class="control-label" for="valveRange">Range</label>
                        <input type="text" class="form-control" name="pressure[valve][' . $ca . '][range]" id="valveRange' . $ca . '" value="' . $ad['range'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="valveSerial">Serial</label>
                        <input type="text" class="form-control" name="pressure[valve][' . $ca . '][serial]" id="valveSerial' . $ca . '" value="' . $ad['serial'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="valveMake">Make</label>
                        <input type="text" class="form-control" name="pressure[valve][' . $ca . '][make]" id="valveMake' . $ca . '" value="' . $ad['make'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="valveTEP">TEP</label>
                        <input type="text" class="form-control" name="pressure[valve][' . $ca . '][TEP]" id="valveTEP' . $ca . '" value="' . $ad['TEP'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="valveIEP">IEP</label>
                        <input type="text" class="form-control" name="pressure[valve][' . $ca . '][IEP]" id="valveIEP' . $ca . '" value="' . $ad['IEP'] . '" />
                        </div>
                        <div class="col-6"><a class="btn btn-danger mt-4" href="javascript:void(0)" onclick="removeRow(\'valveRow' . $ca . '\')"><i class="fad fa-trash"></i></a></div>
                        
                        </div>';
                                        $ca++;
                                    }
                                }
                            } else {
                                $checked = "";
                            } ?>
                            <div class="row mb-3">

                                <div class="col-12 col-md-6 form-check form-switch">
                                    <label class="form-check-label" for="valve">Has safety valve</label>
                                    <input class="form-check-input" type="checkbox" <?= $checked ?> name="pressure[valve_enabled]"
                                        id="valve">
                                </div>

                                <div class="col-12 col-md-6">
                                    <div class="vAmount input-group">
                                        <label class="control-label" for="vNo">Required</label>&nbsp;&nbsp;
                                        <input type="text" class="form-control" id="vNo" />
                                        <button class="btn btn-info" type="button">apply</button>
                                    </div>
                                    <input type="hidden" class="form-control" id="vStart"
                                        value="<?= $ca ?>" />
                                </div>

                            </div>

                            <div id="valveRow" class="row"><?= $storedValve ?></div>
                        </div>
                    </div>

                    <!-- GAUGES -->

                    <div class="col-12 col-md-4 card mb-3">
                        <div class="card-body">
                            <?php $cb = 0;
                            if ($cd['gauge'] != "") {
                                $checked = "checked";
                                $ar = array();
                                $ar = enrep_itemdetails_decode_legacy_list($cd['gauge']);
                                if (is_array($ar)) {
                                    foreach ($ar as $ad) {
                                        $storedGauge .= '<div id="gaugeRow' . $cb . '" class="row border m-0 p-1 mb-3" style="background-color:#f0f0f0"><div class="col-12"><b>GAUGE Record</b></div>
                        <div class="col-6">
                        <label class="control-label" for="guageRange">Range</label>
                        <input type="text" class="form-control" name="pressure[gauge][' . $cb . '][range]" id="gaugeRange' . $cb . '" value="' . $ad['range'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="guageSerial">Serial</label>
                        <input type="text" class="form-control" name="pressure[gauge][' . $cb . '][serial]" id="gaugeSerial' . $cb . '" value="' . $ad['serial'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="geuageMake">Make</label>
                        <input type="text" class="form-control" name="pressure[gauge][' . $cb . '][make]" id="gaugeMake' . $cb . '" value="' . $ad['make'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="guageTEP">TEP</label>
                        <input type="text" class="form-control" name="pressure[gauge][' . $cb . '][TEP]" id="gaugeTEP' . $cb . '" value="' . $ad['TEP'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="gaugeIEP">IEP</label>
                        <input type="text" class="form-control" name="pressure[gauge][' . $cb . '][IEP]" id="gaugeIEP' . $cb . '" value="' . $ad['IEP'] . '" />
                        </div>
                        <div class="col-6"><a class="btn btn-danger mt-4" href="javascript:void(0)" onclick="removeRow(\'gaugeRow' . $cb . '\')"><i class="fad fa-trash"></i></a></div></div>';
                                        $cb++;
                                    }
                                }
                            } else {
                                $checked = "";
                            } ?>

                            <div class="row mb-3">
                                <div class="col-12 col-md-6 form-check form-switch">
                                    <label class="form-check-label" for="gauge">Has pressure gauge</label>
                                    <input class="form-check-input" type="checkbox" <?= $checked ?> name="pressure[gauge_enabled]"
                                        id="gauge">
                                </div>

                                <div class="col-12 col-md-6">
                                    <div class="gAmount input-group">
                                        <label class="control-label" for="gNo">Required</label>&nbsp;&nbsp;
                                        <input type="text" class="form-control" id="gNo" />
                                        <button class="btn btn-info" type="button">Add</button>
                                    </div>
                                    <input type="hidden" class="form-control" id="gStart"
                                        value="<?= $cb ?>" />
                                </div>
                            </div>

                            <div id="gaugeRow" class="row"><?= $storedGauge ?></div>
                        </div>
                    </div>


                    <div class="col-12 col-md-4 card mb-3">
                        <div class="card-body">
                            <?php $cb = 0;
                            if ($cd['burst'] != "") {
                                $checked = "checked";
                                $ar = array();
                                $ar = enrep_itemdetails_decode_legacy_list($cd['burst']);
                                if (is_array($ar)) {
                                    foreach ($ar as $ad) {
                                        $storedBurst .= '<div id="burstRow' . $cb . '" class="row border m-0 p-1 mb-3" style="background-color:#f0f0f0"><div class="col-12"><b>BURST Record</b></div>
                        <div class="col-6">
                        <label class="control-label" for="burstRange">Range</label>
                        <input type="text" class="form-control" name="pressure[burst][' . $cb . '][range]" id="burstRange' . $cb . '" value="' . $ad['range'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="burstSerial">Serial</label>
                        <input type="text" class="form-control" name="pressure[burst][' . $cb . '][serial]" id="burstSerial' . $cb . '" value="' . $ad['serial'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="burstMake">Make</label>
                        <input type="text" class="form-control" name="pressure[burst][' . $cb . '][make]" id="burstMake' . $cb . '" value="' . $ad['make'] . '" />
                        </div>
                        <div class="col-6">
                        <label class="control-label" for="burstTEP">TEP</label>
                        <input type="text" class="form-control" name="pressure[burst][' . $cb . '][TEP]" id="burstTEP' . $cb . '" value="' . $ad['TEP'] . '" />
                        </div>
                        <div class="col-6">         
                        <label class="control-label" for="burstIEP">IEP</label>
                        <input type="text" class="form-control" name="pressure[burst][' . $cb . '][IEP]" id="burstIEP' . $cb . '" value="' . $ad['IEP'] . '" />
                        </div>
                        <div class="col-6 mt-4"><a class="btn btn-danger" href="javascript:void(0)" onclick="removeRow(\'burstRow' . $cb . '\')"><i class="fad fa-trash"></i></a></div></div>';
                                        $cb++;
                                    }
                                }
                            } else {
                                $checked = "";
                            } ?>

                            <div class="row mb-3">
                                <div class="col-12 col-md-6 form-check form-switch">
                                    <label class="form-check-label" for="burst">Has burst disk</label>
                                    <input class="form-check-input" type="checkbox" <?= $checked ?> name="pressure[burst_enabled]"
                                        id="burst">
                                </div>

                                <div class="col-12 col-md-6">
                                    <div class="bAmount input-group">
                                        <label class="control-label" for="bNo">Required</label>&nbsp;&nbsp;
                                        <input type="text" class="form-control" id="bNo" />
                                        <button class="btn btn-info" type="button">Add</button>
                                    </div>
                                    <input type="hidden" class="form-control" id="bStart"
                                        value="<?= $cb ?>" />
                                </div>
                            </div>

                            <div id="burstRow" class="row"><?= $storedBurst ?></div>
                        </div>
                    </div>
                </div>


            </div>
        </div>
    </div>
    <input type="hidden" name="isWS" value="1" />
    <div class="spacer">&nbsp;</div>
</div>
<script>
function editWSC(i) {
    var dest = ROOT_URL + '/includes/master/ws_edit.php?ws=' + i + '&tenant=' + TENANT_URL;
    loadModalContent(dest, "wsBox", "modal-xxl", 1060, "true", "Editing Written Scheme");
}


document.getElementById('vNo').addEventListener('change', function() {
    genRow('valve', this.value, document.getElementById('vStart').value);
});

document.getElementById('gNo').addEventListener('change', function() {
    genRow('gauge', this.value, document.getElementById('gStart').value);
});

document.getElementById('bNo').addEventListener('change', function() {
    genRow('burst', this.value, document.getElementById('bStart').value);
});

checkAndToggleElement('valve', 'vNo', 'valveRow', 'vAmount');
checkAndToggleElement('gauge', 'gNo', 'gaugeRow', 'gAmount');
checkAndToggleElement('burst', 'bNo', 'burstRow', 'bAmount');


document.getElementById('valve').addEventListener('click', function() {
    toggleElement('valve', 'vNo', 'valveRow', 'vAmount');
});

document.getElementById('gauge').addEventListener('click', function() {
    toggleElement('gauge', 'gNo', 'gaugeRow', 'gAmount');
});

document.getElementById('burst').addEventListener('click', function() {
    toggleElement('burst', 'bNo', 'burstRow', 'bAmount');
});

function genRow(t, c, s) {
    var x = (+c + +s);
    var r = '';
    for (var n = s; n < x; n++) {
        r += '<div id="' + t + 'Row' + n + '" class="row border m-0 p-1 mb-3" style="background-color:#f0f0f0">';
        r += '<div class="col-12"><b>' + t.toUpperCase() + ' Record</b></div>';
        r += '<div class="col-6"><label class="control-label" for="' + t + 'Range">Range</label>';
        r += '<input type="text" class="form-control" name="pressure[' + t + '][' + n + '][range]" id="' + t + 'Range' + n +
            '" value="" /></div>';
        r += '<div class="col-6"><label class="control-label" for="' + t + 'Serial">Serial</label>';
        r += '<input type="text" class="form-control" name="pressure[' + t + '][' + n + '][serial]" id="' + t + 'Serial' + n +
            '" value="" /></div>';
        r += '<div class="col-6"><label class="control-label" for="' + t + 'Make">Make</label>';
        r += '<input type="text" class="form-control" name="pressure[' + t + '][' + n + '][make]" id="' + t + 'Make' + n +
            '" value="" /></div>';
        r += '<div class="col-6"><label class="control-label" for="' + t + 'TEP">TEP</label>';
        r += '<input type="text" class="form-control" name="pressure[' + t + '][' + n + '][TEP]" id="' + t + 'TEP' + n +
            '" value="" /></div>';
        r += '<div class="col-6"><label class="control-label" for="' + t + 'IEP">IEP</label>';
        r += '<input type="text" class="form-control" name="pressure[' + t + '][' + n + '][IEP]" id="' + t + 'IEP' + n +
            '" value="" /></div>';
        r += '</div>';
    }
    document.getElementById(t + "Row").insertAdjacentHTML('beforeend', r);
}

function removeRow(i) {
    var element = document.getElementById(i);
    if (element) {
        element.style.transition = 'opacity 0.3s';
        element.style.opacity = '0';
        setTimeout(function() {
            if (element) {
                element.remove();
            }
        }, 300);
    }
}

function checkAndToggleElement(checkboxId, inputId, rowId, amountClass) {
    var checkbox = document.getElementById(checkboxId);
    if (!checkbox.checked) {
        document.getElementById(rowId).innerHTML = '';
        document.getElementById(inputId).value = '';
        hideElementsByClass(amountClass);
    } else {
        showElementsByClass(amountClass);
    }
}

function toggleElement(checkboxId, inputId, rowId, amountClass) {
    var checkbox = document.getElementById(checkboxId);
    if (!checkbox.checked) {
        document.getElementById(rowId).innerHTML = '';
        document.getElementById(inputId).value = '';
        hideElementsByClass(amountClass);
    } else {
        showElementsByClass(amountClass);
    }
}

function hideElementsByClass(className) {
    var elements = document.getElementsByClassName(className);
    Array.prototype.forEach.call(elements, function(el) {
        el.style.visibility = 'hidden';
    });
}

function showElementsByClass(className) {
    var elements = document.getElementsByClassName(className);
    Array.prototype.forEach.call(elements, function(el) {
        el.style.visibility = 'visible';
    });
}
</script>
