<?php
if (defined('PSSR_DATA_RENDERED')) {
    return;
}
define('PSSR_DATA_RENDERED', true);

if (!function_exists('enrep_itemdetails_pressure_from_record')) {
    require_once __DIR__ . '/../../functions/itemdetails_json.php';
}
if (isset($cd) && is_array($cd)) {
    $cd = array_replace($cd, enrep_itemdetails_pressure_from_record($cd));
}

$pssrClientNumber = (int)($d[0] ?? ($_REQUEST['clientnumber'] ?? 0));
$pssrItemNumber = (int)($d[2] ?? ($_REQUEST['asset'] ?? 0));

if (!function_exists('pssrDataWsAttachment')) {
    function pssrDataWsAttachment(int $itemnumber, int $clientnumber): array
    {
        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.`wstype`, w.`scheme_number_alt`
      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 : [];
    }
}

if (!function_exists('pssrDataWsLabel')) {
    function pssrDataWsLabel(array $wsAttachment): string
    {
        $parts = [];
        $schemeNo = trim((string)($wsAttachment['no'] ?? ''));
        $schemeTitle = trim((string)($wsAttachment['title'] ?? ''));

        if ($schemeNo !== '') {
            $parts[] = $schemeNo;
        }
        if ($schemeTitle !== '') {
            $parts[] = $schemeTitle;
        }

        return trim(implode(' ', $parts));
    }
}

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

        $stmt = $GLOBALS['con']->prepare("SELECT `id`, `wstype` FROM `writtenscheme` WHERE `clientnumber` = ?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        $stmt->close();

        $map = [];
        while ($row = mysqli_fetch_array($res)) {
            $map[(string)(int)$row['id']] = (string)(int)($row['wstype'] ?? 0);
        }
        return $map;
    }
}

if (!function_exists('pssrDataWsStatusHtml')) {
    function pssrDataWsStatusHtml(array $wsAttachment, int $clientnumber): string
    {
        if (empty($wsAttachment['wsnumber'])) {
            $select = function_exists('listWSE') ? listWSE($clientnumber) : '';
            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>' . $select . '</div>';
        }

        $schemeLabel = pssrDataWsLabel($wsAttachment);
        $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 (empty($cd['system_type'])) {
    $cd['system_type'] = "Compressed Air (Minor System)";
}
if (!empty($_REQUEST['clientnumber'])) {
    $d[0] = $_REQUEST['clientnumber'];
    $pssrClientNumber = (int)$_REQUEST['clientnumber'];
}
if (empty($cd['changeScheme'])) {
    $cd['changeScheme'] = "No";
}
if (empty($cd['lease_or_hire'])) {
    $cd['lease_or_hire'] = "No";
}
if (empty($cd['history'])) {
    $cd['history'] = "Makers test when new.";
}
if (empty($cd['lastReport'])) {
    $cd['lastReport'] = "Yes";
}

$pssrWsAttachment = pssrDataWsAttachment($pssrItemNumber, $pssrClientNumber);
$pssrAttachedToWs = !empty($pssrWsAttachment['wsnumber']);
$pssrShowExistingSchemeControls = !$pssrAttachedToWs || (int)($pssrWsAttachment['wstype'] ?? 1) !== 0;
$pssrWsTypeMap = pssrDataWsTypeMap($pssrClientNumber);
?>

<div id="PSSRDATA" class="col-12 mb-5">
    <div class="card">
        <div class="card-header">PSSR Data</div>
        <div class="card-body">
            <div class="row">
                <div class="col-12">

                    <div class="row mb-3 align-items-center">

                        <div class="col-md-6">
                            <label class="control-label" for="scheme_number">Scheme Number</label>
                            <div id="pssrWsStatus"><?= pssrDataWsStatusHtml($pssrWsAttachment, $pssrClientNumber) ?>
                            </div>
                        </div>

                        <?php if (!empty($pssrWsAttachment['wsnumber'])) { ?>
                        <div class="col-md-4">
                            <a href="javascript:void(0)" onclick="editWSC('<?= (int)$pssrWsAttachment['wsnumber'] ?>')"
                                data-mdb-tooltip-init data-mdb-placement="left" data-mdb-trigger="hover"
                                title="Manage WS" class="btn btn-info">
                                <i class="fad fa-cog"></i>&nbsp;View
                                <?= htmlspecialchars(pssrDataWsLabel($pssrWsAttachment) ?: 'Written Scheme', ENT_QUOTES, 'UTF-8') ?>
                            </a>
                        </div>
                        <input type="hidden" name="wsnumber" value="<?= (int)$pssrWsAttachment['wsnumber'] ?>">
                        <?php } ?>

                        <div class="col-md-2 text-end" id="pssrCreateWsWrap"
                            style="<?= $pssrAttachedToWs ? 'display:none' : '' ?>">
                            <a href="javascript:void(0)" class="btn btn-secondary btn-sm" onclick="addWS()"
                                data-mdb-tooltip-init data-mdb-placement="left" data-mdb-trigger="hover"
                                title="New Written Scheme"><i class="fad fa-plus"></i> Create New WS</a>
                        </div>

                    </div>

                    <!-- wsSelect is added dynamically after a successful WS create -->
                    <div class="row mb-3" id="wsSelectRow" style="display:none">
                        <div class="col-md-2">
                            <label class="control-label" for="wsSelect">Written Scheme</label>
                        </div>
                        <div class="col-md-6" id="wsSelectHolder"></div>
                    </div>

                    <div class="row mb-3" id="pssrExistingSchemeRow"
                        style="<?= $pssrShowExistingSchemeControls ? '' : 'display:none' ?>">
                        <div class="col-md-2"><label class="control-label" for="scheme_number">Use Existing Scheme &
                                Number</label></div>
                        <div class="col-md-3"><input class="form-control" type="text" name="pressure[scheme_number_alt]"
                                id="scheme_number_alt" value="<?= $cd['scheme_number_alt'] ?>" /></div>
                        <div class="col-md-3 form-check form-switch">
                            <input type="checkbox" class="form-check-input" name="pressure[select_for_scheme]"
                                id="select_for_scheme" <?php if ($cd['select_for_scheme'] == 1) { ?>checked<?php } ?>>
                            <label class="form-check-label" for="select_for_scheme">Use Existing Scheme Number</label>
                        </div>
                    </div>

                    <div class="row mb-3" id="pssrSystemTypeRow">
                        <div class="col-md-2"><label class="control-label" for="system_type">System Type</label></div>
                        <div class="col-md-3"><input class="form-control" type="text" name="pressure[system_type]"
                                id="system_type" value="<?= $cd['system_type'] ?>" /></div>

                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
const PSSR_WS_TYPES = <?= json_encode($pssrWsTypeMap, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;

document.addEventListener('DOMContentLoaded', function() {
    const selectForScheme = document.getElementById('select_for_scheme');
    const wsidata = document.getElementById('WSIDATA');
    const noneButton = document.getElementById('none');

    if (selectForScheme && wsidata) {
        const toggleWSIDATA = () => {
            wsidata.style.display = selectForScheme.checked ? 'none' : 'block';
        };
        toggleWSIDATA();
        selectForScheme.addEventListener('change', toggleWSIDATA);
    }

    if (noneButton) {
        noneButton.addEventListener('click', function() {
            const el = document.getElementById('lastReport');
            if (el) el.value = 'Not Seen';
        });
    }
});

function addWS() {
    const dest = encodeURI(
        ROOT_URL +
        "/includes/client/client_ws.php" +
        "?clientnumber=<?= $pssrClientNumber ?>" +
        "&itemnumber=<?= $pssrItemNumber ?>" +
        "&tenant=" + TENANT_URL
    );

    loadModalContent(dest, "wsBox", "modal-xl", 1060, "true", "New Written Scheme");
}

/**
 * Called by the WS modal after a successful create.
 * Ensures a <select id="wsSelect"> exists and adds/selects the new option.
 */
window.pssrAddWsOption = function(insertId, locationLabel, wstype) {
    const idNum = parseInt(insertId, 10);
    if (!idNum || !locationLabel) return;
    const schemeType = String(typeof wstype === 'undefined' || wstype === null || wstype === '' ? '0' : wstype);

    const row = document.getElementById('wsSelectRow');
    const holder = document.getElementById('wsSelectHolder');
    if (!row || !holder) return;

    let sel = document.getElementById('wsSelect');
    if (!sel) {
        sel = document.createElement('select');
        sel.id = 'wsSelect';
        sel.name = 'wsSelect';
        sel.className = 'form-select form-select-sm';

        const ph = document.createElement('option');
        ph.value = '';
        ph.textContent = 'Select Written Scheme';
        sel.appendChild(ph);

        holder.appendChild(sel);
    }

    // avoid duplicates
    const existing = Array.from(sel.options).some(o => String(o.value) === String(idNum));
    if (!existing) {
        const opt = document.createElement('option');
        opt.value = String(idNum);
        opt.textContent = locationLabel;
        opt.dataset.wstype = schemeType;
        sel.appendChild(opt);
    }

    sel.value = String(idNum);
    row.style.display = '';
    window.pssrSetPendingWs(idNum, locationLabel, schemeType);
};

window.pssrSetPendingWs = function(wsId, label, wstype) {
    const status = document.getElementById('pssrWsStatus');
    if (!status || !wsId || !label) return;

    const safeLabel = pssrEscapeHtml(label);
    status.innerHTML = `<div class="alert alert-success">Item is attached to <strong>${safeLabel}</strong></div>`;
    window.pssrSetWsFormValue(wsId);
    window.pssrToggleCreateWsButton(true);
    window.pssrToggleExistingSchemeRow(wstype);
    window.pssrLoadWsData();
};

window.pssrToggleCreateWsButton = function(attached) {
    const wrap = document.getElementById('pssrCreateWsWrap');
    if (wrap) wrap.style.display = attached ? 'none' : '';
};

window.pssrSetWsFormValue = function(wsId) {
    const form = document.getElementById('assetForm');
    if (!form || !wsId) return;

    let hidden = document.getElementById('pending_wsnumber');
    if (!hidden) {
        hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.id = 'pending_wsnumber';
        hidden.name = 'pending_wsnumber';
        form.appendChild(hidden);
    }
    hidden.value = String(wsId);

    let hiddenSelect = document.getElementById('assetFormWsSelect');
    if (!hiddenSelect) {
        hiddenSelect = document.createElement('input');
        hiddenSelect.type = 'hidden';
        hiddenSelect.id = 'assetFormWsSelect';
        hiddenSelect.name = 'wsSelect';
        form.appendChild(hiddenSelect);
    }
    hiddenSelect.value = String(wsId);
};

window.pssrToggleExistingSchemeRow = function(wstype) {
    const row = document.getElementById('pssrExistingSchemeRow');
    if (!row || typeof wstype === 'undefined' || wstype === null || wstype === '') return;
    const hide = String(wstype) === '0';
    if (row) row.style.display = hide ? 'none' : '';

    if (hide) {
        const alt = document.getElementById('scheme_number_alt');
        const toggle = document.getElementById('select_for_scheme');
        if (alt) alt.value = '';
        if (toggle) toggle.checked = false;
    }
};

window.pssrLoadWsData = function() {
    if (document.getElementById('WSIDATA')) return;

    const target = document.getElementById('additionalContent');
    if (!target || typeof loadContentAndExecuteScripts !== 'function') return;

    const url = ROOT_URL +
        "/forms/elements/ws_data.php?new=yes" +
        "&clientnumber=<?= $pssrClientNumber ?>" +
        "&itemnumber=<?= $pssrItemNumber ?>" +
        "&skip_pssr=1" +
        "&tenant=" + encodeURIComponent(TENANT_URL);

    loadContentAndExecuteScripts(url, 'additionalContent');
};

function pssrEscapeHtml(value) {
    return String(value || '').replace(/[&<>"']/g, function(chr) {
        return ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        } [chr]);
    });
}

document.addEventListener('change', function(event) {
    const sel = event.target && event.target.id === 'wsSelect' ? event.target : null;
    if (!sel || !sel.value || !sel.options[sel.selectedIndex]) return;
    const option = sel.options[sel.selectedIndex];
    const schemeType = option.dataset.wstype || PSSR_WS_TYPES[String(sel.value)] || '';
    if (schemeType !== '') {
        option.dataset.wstype = schemeType;
    }
    window.pssrSetPendingWs(sel.value, option.text, schemeType);
});

<?php if (!empty($pssrWsAttachment['wsnumber'])) { ?>
setTimeout(function() {
    if (typeof window.pssrLoadWsData === 'function') {
        window.pssrLoadWsData();
    }
}, 0);
<?php } ?>
</script>
