<?php //ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);
if (file_exists('../../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) {
    require_once('../../../../' . $_REQUEST['tenant'] . '/config.php'); 
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
?>
<div class="container-fluid py-2">
    <form id="expenseFormInline" autocomplete="off">
        <div class="row g-2">
            <div class="col-4">
                <label for="code" class="form-label">Code</label>
                <input id="code" name="code" type="text" class="form-control form-control-sm" placeholder="e.g. MIL">
            </div>
            <div class="col-12">
                <label for="descNew" class="form-label">Desc</label>
                <input id="descNew" name="desc" type="text" class="form-control" placeholder="e.g. Mileage">
            </div>
        </div>

        <!-- required posts -->
        <input type="hidden" name="mode" value="expenses">
        <input type="hidden" name="FUNCTION" value="save">
        <input type="hidden" name="sub" value="expenses">
        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
    </form>
</div>
<button type="button" id="btnConfirm" class="btn btn-info me-2"
        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save">
    <i class="fad fa-save me-2"></i>Save</button>
<button type="button" id="btnCancel" class="btn btn-danger float-end"
        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Cancel">
    <i class="fad fa-times me-2"></i>Cancel</button>
<script>
// --- Wire buttons
document.getElementById('btnCancel')?.addEventListener('click', () => {
    if (typeof killModal === 'function') killModal('popupBox');
});

document.getElementById('btnConfirm')?.addEventListener('click', () => {
    const code = document.querySelector('#expenseFormInline input[name="code"]')?.value.trim() || '';
    if (!code) {
        (parent.showResponse || window.alert)('danger', 'YOU MUST ENTER A CODE');
        return;
    }
    submitExpenseType();
});

// --- Submit handler (pure JS)
async function submitExpenseType() {
    const form = document.getElementById('expenseFormInline');
    const desc = document.getElementById('descNew')?.value.trim() || '';
    const body = new URLSearchParams(new FormData(form));

    try {
        const res = await fetch(ROOT_URL + '/includes/finance/jump_functions.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body
        });
        const txt = (await res.text()).trim();

        if (txt === 's') {
            // success toast in parent
            if (parent && typeof parent.showResponse === 'function') parent.showResponse('success', 'Your Expense has been saved successfully');
            // prefer the provided hook
            if (parent && typeof parent.onNewExpenseTypeSaved === 'function') {
                parent.onNewExpenseTypeSaved(desc);
            } else {
                // fallback: append option + reinit MDB Select
                const sel = parent?.document.getElementById('type');
                if (sel) {
                    // add if missing
                    let opt = Array.from(sel.options).find(o => o.value === desc);
                    if (!opt) {
                        opt = parent.document.createElement('option');
                        opt.value = desc;
                        opt.textContent = desc;
                        sel.appendChild(opt);
                    }
                    sel.value = desc;

                    try {
                        parent.mdb.Select.getInstance(sel)?.dispose();
                    } catch {}
                    try {
                        new parent.mdb.Select(sel, {
                            filter: true,
                            container: "body"
                        });
                    } catch {}
                }
            }

            if (typeof killModal === 'function') killModal('popupBox');
        } else {
            if (parent && typeof parent.showResponse === 'function') parent.showResponse('danger', 'The code is already in the system');
        }
    } catch (e) {
        if (parent && typeof parent.showResponse === 'function') parent.showResponse('danger', 'Network error saving expense');
    }
}
</script>