<?php
switch ($_REQUEST['view']) {
    default:
        break;
    case 'new':
        require_once(ROOT_URL . '/includes/surveyor/surveyor_new.php');
        break;

    case "load":
        require_once(ROOT_URL . '/includes/surveyor/surveyor_load.php');
        break;

    case 'edit':
        require_once(ROOT_URL . '/includes/surveyor/surveyor_edit.php');

        break;

    case "list":
        require_once(ROOT_URL . '/includes/surveyor/surveyor_list.php');
        break;

    case "archive":
        require_once(ROOT_URL . '/includes/surveyor/surveyor_archive.php');
        break;

    case "choose":
        require_once(ROOT_URL . '/includes/master/form_functions.php');
        require_once(ROOT_URL . '/includes/surveyor/surveyor_choose.php');
        break;

    case "asset":
        require_once(ROOT_URL . '/includes/master/form_functions.php');
        require_once(ROOT_URL . '/includes/surveyor/surveyor_asset.php');
        break;

    case "assign":
        require_once(ROOT_URL . '/includes/surveyor/surveyor_assign.php');
        break;
}
?>
<script>
function showDetails(target) {
    var element = document.getElementById(target);
    if (element) {
        if (element.style.display === "none" || element.style.display === "") {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
    }
}

document.body.addEventListener('click', function(event) { // Event delegation on body
    if (event.target.classList.contains('emailButton')) {
        const target = event.target.dataset.href;
        const string = event.target.dataset.values;
        var dest = encodeURI(target + "?data=" + string + "&tenant=" + TENANT_URL);
        loadModalContent(dest, "mailerBox", "modal-xl", 1060, "true", "Direct Mailer");

    }
});

function archiveSurveyor(t, c, i, s, f) {
    $.post(ROOT_URL + "/includes/surveyor/" + s, {
        FUNCTION: f,
        [c]: i,
        tenant: TENANT_URL
    }, function(ret) {
        const r = $.trim(ret);
        if (r === "s") {
            showResponse("success", t + " archived successfully");
            window.location.href = 'index.php?t=includes/master&p=surveyor.php&view=list';
            return;
        }
        if (r.startsWith("lock")) {
            const secs = parseInt(r.split("|")[1] || "0", 10);
            const h = Math.floor(secs / 3600);
            const m = Math.floor((secs % 3600) / 60);
            const label = h > 0 ? (h + "h " + m + "m") : (m + "m");
            showResponse("warning", t + " is locked from archiving. " + label + " remaining.");
            // optional: do not redirect so the user can see the message
            // window.location.href = 'index.php?t=includes/master&p=surveyor.php&view=list';
            return;
        }
        showResponse("danger", "Unexpected response: " + r);
    });
}


function reinstateSurveyor(title, column, id, script, func) {
    const formData = new FormData();
    formData.append('FUNCTION', func);
    formData.append(column, id);
    formData.append('tenant', TENANT_URL);

    fetch(`${ROOT_URL}/includes/surveyor/${script}`, {
            method: 'POST',
            body: formData
        })
        .then(r => r.text())
        .then(txt => {
            const res = txt.trim();

            if (res === 's') {
                showResponse('success', `${title} reinstated successfully`);
                window.location.href = 'index.php?t=includes/master&p=surveyor.php&view=list';
                return;
            }

            if (res === 'capacity' || res.startsWith('capacity')) {
                showResponse('warning', 'Surveyor capacity reached. Deactivate someone or request a boost.');
                //if (typeof openBoostRequest === 'function') openBoostRequest();
                return;
            }

            if (res.startsWith('lock|')) {
                const secs = parseInt(res.split('|')[1] || '0', 10);
                const h = Math.floor(secs / 3600);
                const m = Math.floor((secs % 3600) / 60);
                const label = h > 0 ? `${h}h ${m}m` : `${m}m`;
                showResponse('danger', `24-hour lock active. ${label} remaining.`);
                return;
            }

            if (res === 'lock') {
                showResponse('danger', '24-hour lock active.');
                return;
            }

            showResponse('danger', `Error: ${res}`);
        })
        .catch(err => {
            showResponse('danger', `Request failed: ${err.message}`);
            console.error(err);
        });
}
</script>