<?php ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$view = $_REQUEST['view'] ?? 'list';

switch ($view) {
    default:
    case 'list':
        require_once(ROOT_URL . "/includes/requests/requests_list.php");
        break;
}
?>

<script>
function requestAdminOpenDetail(requestId) {
    const payload = {
        id: requestId
    };
    const string = encodeURIComponent(JSON.stringify(payload));
    const target = ROOT_URL + '/includes/requests/requests_detail.php';
    const dest = encodeURI(`${target}?data=${string}&tenant=${TENANT_URL}`);

    loadModalContent(
        dest,
        'requestAdminDetailBox',
        'modal-xl',
        1060,
        'true',
        'Portal Request Details'
    );
}

function requestAdminApplyFilters() {
    const status = document.getElementById('request_admin_status') ? document.getElementById('request_admin_status')
        .value : '';
    const type = document.getElementById('request_admin_type') ? document.getElementById('request_admin_type').value :
        '';
    const actionFlag = document.getElementById('request_admin_action_flag') ? document.getElementById(
        'request_admin_action_flag').value : '';
    const keyword = document.getElementById('request_admin_keyword') ? document.getElementById('request_admin_keyword')
        .value.trim() : '';

    const params = new URLSearchParams();
    params.append('tenant', TENANT_URL);
    params.append('status', status);
    params.append('request_type', type);
    params.append('action_flag', actionFlag);
    params.append('keyword', keyword);

    fetch('<?= ROOT_URL ?>/includes/requests/requests_list.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: params.toString()
        })
        .then(response => response.text())
        .then(html => {
            const holder = document.getElementById('requestAdminListContainer');
            if (holder) {
                holder.innerHTML = html;
            }
        })
        .catch(() => {
            showResponse('danger', 'There was an error loading the request list');
        });
}

function requestAdminClearFilters() {
    const status = document.getElementById('request_admin_status');
    const type = document.getElementById('request_admin_type');
    const actionFlag = document.getElementById('request_admin_action_flag');
    const keyword = document.getElementById('request_admin_keyword');

    if (status) status.value = '';
    if (type) type.value = '';
    if (actionFlag) actionFlag.value = '';
    if (keyword) keyword.value = '';

    requestAdminApplyFilters();
}
</script>