<?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('../asset/asset_functions.php');
?>
<div class="col-md-12">
    <form id="wsForm">
        <div class="form-group row">
            <label class="col-12 control-label col-md-2" for="wsDesc">WSE Type</label>
            <div class="col-12 col-md-2 mb-3">
                <div class="form-check">
                    <input type="radio" class="form-check-input" id="wstypeInternal" name="wstype" value="0" checked>
                    <label class="form-check-label" for="wstypeInternal">EnRep</label>
                </div>
            </div>
            <div class="col-12 col-md-2 mb-3">
                <div class="form-check">
                    <input type="radio" class="form-check-input" id="wstypeExisting" name="wstype" value="1">
                    <label class="form-check-label" for="wstypeExisting">Existing</label>
                </div>
            </div>
        </div>

        <div class="form-group row mb-3">
            <label class="col-12 col-md-2 control-label" for="wsDesc">Site</label>
            <div class="col-12 col-md-5"><?= getSites3($_REQUEST['clientnumber'], '') ?></div>
        </div>

        <div class="form-group row mb-3">
            <label class="col-12 col-md-2 control-label" for="wsDesc">Location on Site</label>
            <div class="col-12 col-md-6">
                <input class="form-control form-control-sm" type="text" name="wsDesc" id="wsDesc" value="" />
            </div>
        </div>

        <div class="row">
            <div class="col-12 text-center">
                <button type="submit" class="btn btn-info" id="wsSubmitBtn">Create entry</button>
                <input type="hidden" name="mode" value="setWS">
                <input type="hidden" name="clientnumber" value="<?= (int)$_REQUEST['clientnumber'] ?>">
                <input type="text" name="tenant" value="<?= TENANT_URL ?>">
            </div>
        </div>
    </form>
</div>

<script>
    (function() {
        const form = document.getElementById('wsForm');
        const btn = document.getElementById('wsSubmitBtn');

        if (!form) return;

        form.addEventListener('submit', async function(e) {
            e.preventDefault();

            const descEl = document.getElementById('wsDesc');
            const locEl = document.getElementById('WSlocnumber'); // generated by getSites3()

            const desc = (descEl ? descEl.value : '').trim();
            const loc = (locEl ? locEl.value : '').trim();

            if (desc === '') {
                showResponse('warning', 'YOU MUST SET A DESCRIPTION FOR YOUR WRITTEN SCHEME');
                return;
            }
            if (loc === '') {
                showResponse('warning', 'YOU MUST SELECT A SITE FOR YOUR WRITTEN SCHEME');
                return;
            }

            btn.disabled = true;

            try {
                const body = new URLSearchParams(new FormData(form));

                const res = await fetch(ROOT_URL + '/includes/master/ws_functions.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body
                });

                const text = (await res.text()).trim();

                let ok = false;
                let insertId = 0;

                if (text.startsWith('{')) {
                    try {
                        const j = JSON.parse(text);
                        ok = (j.status === 'success' || j.result === 'success');
                        insertId = parseInt(j.id || j.insert_id || 0, 10) || 0;
                    } catch (_) {}
                }

                if (!ok) {
                    const parts = text.split('|');
                    if (parts[0] === 'success') {
                        ok = true;
                        insertId = parseInt(parts[1] || 0, 10) || 0;
                    } else if (text === 'success') {
                        ok = true;
                    }
                }

                if (ok) {
                    showResponse('success', 'THE WS HAS BEEN CREATED SUCCESSFULLY');

                    if (typeof window.relWs === 'function') {
                        try {
                            window.relWs();
                        } catch (_) {}
                    }

                    if (insertId > 0 && typeof window.pssrAddWsOption === 'function') {
                        window.pssrAddWsOption(insertId, desc);
                    }

                    killModal("wsBox");
                } else {
                    showResponse('danger', 'THERE WAS AN ERROR CREATING THE WS');
                }

            } catch (err) {
                showResponse('danger', 'THERE WAS AN ERROR CREATING THE WS');
            } finally {
                btn.disabled = false;
            }
        });
    })();
</script>