<?php
$btnPath = 'index.php?t=includes/master&p=jump.php';
$filePath = ROOT_URL . '/includes/jump/';

require_once($filePath . 'jump_functions.php');
?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const nav = document.getElementById('navBox');
    if (nav) {
        nav.innerHTML =
            '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li>' +
            '<li class="breadcrumb-item active">Jump List Management</li>';
    }

    if (typeof mdb !== 'undefined' && mdb.Tooltip) {
        document.querySelectorAll('[data-mdb-tooltip-init]').forEach((el) => {
            try {
                if (mdb.Tooltip.getInstance && mdb.Tooltip.getInstance(el)) return;
            } catch (e) {}
            try {
                new mdb.Tooltip(el);
            } catch (e) {}
        });
    }
});
</script>

<div class="container-fluid px-0">
    <div class="note note-secondary"
        data-help-topic="<?= (($_REQUEST['mode'] ?? 'plant') === 'phrase') ? 'jump_standard_phrases' : 'jump_plant_list' ?>">
        <span class="mb-1">Modify the content of the lists available throughout your system. Items added to the groups here will be available to you in addition to the preset options</span>
        <?php if (($_REQUEST['mode'] ?? 'plant') === 'phrase') { ?>
            <small class="d-block mt-1 text-muted">Phrase codes are limited to 10 characters. CSV imports skip rows where the code is longer, duplicated in the file, or already exists.</small>
        <?php } ?>
    </div>

    <div class="row mt-3">
        <div class="col-12 d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div class="btn-group">
                <a id="plantBtn" href="<?= $btnPath ?>&mode=plant" class="btn btn-secondary navBtn"
                   data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View plant list">Plant List</a>
                <a id="phraseBtn" href="<?= $btnPath ?>&mode=phrase" class="btn btn-secondary navBtn"
                   data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="View standard phrases">Standard Phrases</a>
            </div>

            <button type="button"
                    id="jumpNewEntryBtn"
                    class="btn btn-info"
                    onclick="openJumpNewEntryModal()"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Create a new jump entry">
                <i class="fad fa-plus-circle me-2" aria-hidden="true"></i>
                <?= (($_REQUEST['mode'] ?? 'plant') === 'phrase') ? 'New Phrase' : 'New Plant' ?>
            </button>
        </div>
    </div>

    <div class="mt-3">
        <?php
        switch ($_REQUEST['mode'] ?? 'plant') {
            default:
            case 'plant':
                require_once($filePath . 'jump_plant.php');
                break;
            case 'phrase':
                require_once($filePath . 'jump_phrases.php');
                break;
        }
        ?>
    </div>
</div>

<div id="loadingObject" style="position: fixed; top:50%; width:100%; display:none;">
    <h1 class="text-center">
        <i class="fad fa-flux-capacitor fa-spin fa-3x fa-fw" style="--fa-primary-color:#0055A6; --fa-secondary-color:gray;"></i><br>
        Loading Data <br><small>Please wait</small>
    </h1>
</div>

<script>
function postFormUrlEncoded(url, dataObj) {
    const body = new URLSearchParams();
    Object.keys(dataObj || {}).forEach((k) => body.append(k, dataObj[k]));
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body
    }).then((r) => r.text());
}

function postMultipart(url, formData) {
    return fetch(url, {
        method: 'POST',
        body: formData
    }).then((r) => r.text());
}

function getJumpMode() {
    return '<?= htmlspecialchars((string)($_REQUEST['mode'] ?? 'plant')) ?>';
}

function openJumpNewEntryModal(modeOverride) {
    const currentMode = String(modeOverride || getJumpMode() || 'plant').trim().toLowerCase();
    const type = currentMode === 'phrase' ? 'phrases' : 'plant';
    const title = type === 'phrases' ? 'New Phrase' : 'New Plant';

    const target = ROOT_URL + '/includes/jump/jump_new_form.php';
    const dest = encodeURI(target + '?type=' + type + '&tenant=' + TENANT_URL);

    loadModalContent(dest, 'popupBox', 'modal-lg', 1060, 'true', title);
}

document.addEventListener('jump:new:done', (event) => {
    const type = String((event.detail && event.detail.type) || '').trim().toLowerCase();
    const mode = type === 'phrases' ? 'phrase' : 'plant';
    window.location.href = '<?= $btnPath ?>&mode=' + encodeURIComponent(mode);
});

function update(formId) {
    const form = document.getElementById(formId);
    if (!form) return;

    const fd = new FormData(form);
    if (!fd.has('tenant')) fd.append('tenant', TENANT_URL);

    postMultipart(ROOT_URL + '/includes/jump/jump_functions.php', fd)
        .then((result) => {
            const ret = (result || '').trim();
            if (ret === 's') {
                showResponse('success', 'Your entry has been updated successfully');
                document.dispatchEvent(new CustomEvent('jump:update:done', {
                    detail: { formId }
                }));
            } else if (ret === 'e') {
                showResponse('warning', 'The code is already in the system');
            } else {
                showResponse('danger', ret || 'Update failed');
            }
        })
        .catch(() => showResponse('danger', 'Update failed'));
}

function delItem(table, id) {
    postFormUrlEncoded(ROOT_URL + '/includes/jump/jump_functions.php', {
        FUNCTION: 'remove',
        table,
        id,
        tenant: TENANT_URL
    }).then((result) => {
        const ret = (result || '').trim();
        if (ret.startsWith('s')) {
            showResponse('success', 'Your entry has been removed successfully');
            document.dispatchEvent(new CustomEvent('jump:remove:done', {
                detail: { table, id }
            }));
            if (typeof killModal === 'function') killModal('confirmBox');
        } else {
            showResponse('danger', ret || 'Delete failed');
        }
    }).catch(() => showResponse('danger', 'Delete failed'));
}

function remove(table, id) {
    const dest = '<p class="text-center">Sure you wish to remove this entry?</p>';
    loadModalContent(dest, 'confirmBox', 'modal-md', 1060, 'true', 'Confirm Removal', 'cancelConfirm', () => delItem(table, id));
}

function edit(id) {
    const target = ROOT_URL + '/includes/jump/jump_edit-plant.php';
    const dest = encodeURI(target + '?id=' + id + '&tenant=' + TENANT_URL);
    loadModalContent(dest, 'editBox', 'modal-xl', 1060, 'true', 'Edit Entry');
}

function uploadPlantDoc(plantId) {
    const input = document.getElementById('plantDocInput_' + plantId);
    if (!input || !input.files || !input.files[0]) {
        showResponse('warning', 'Please select a file first');
        return;
    }

    const fd = new FormData();
    fd.append('FUNCTION', 'uploadPlantDoc');
    fd.append('id', plantId);
    fd.append('tenant', TENANT_URL);
    fd.append('doc', input.files[0]);

    postMultipart(ROOT_URL + '/includes/jump/jump_functions.php', fd)
        .then((res) => {
            const ret = (res || '').trim();
            if (ret === 's') {
                showResponse('success', 'Document uploaded');
                document.dispatchEvent(new CustomEvent('jump:plantdoc:done', {
                    detail: { id: plantId }
                }));
            } else {
                showResponse('danger', ret || 'Upload failed');
            }
        })
        .catch(() => showResponse('danger', 'Upload failed'));
}

function deletePlantDoc(plantId) {
    const dest = '<p>Remove the attached document from this plant record?</p>';
    loadModalContent(dest, 'confirmBox', 'modal-md', 1060, 'true', 'Confirm Removal', 'cancelConfirm', () => {
        postFormUrlEncoded(ROOT_URL + '/includes/jump/jump_functions.php', {
            FUNCTION: 'deletePlantDoc',
            id: plantId,
            tenant: TENANT_URL
        }).then((res) => {
            const ret = (res || '').trim();
            if (ret === 's') {
                showResponse('success', 'Document removed');
                document.dispatchEvent(new CustomEvent('jump:plantdoc:done', {
                    detail: { id: plantId }
                }));
                if (typeof killModal === 'function') killModal('confirmBox');
            } else {
                showResponse('danger', ret || 'Remove failed');
            }
        }).catch(() => showResponse('danger', 'Remove failed'));
    });
}
</script>
