<?php
if (file_exists('../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
?>
<form id="payeeForm" autocomplete="off">
    <div class="col-md-8">
        <div class="form-group row">
            <label for="payee_name">Payee Name</label>
            <div class="input-group">
                <input type="text" class="form-control col-md-12" name="payee_name" id="payee_name" />
            </div>
        </div>
    </div>

    <input type="hidden" name="type" id="payee_type" value="out">
    <input type="hidden" name="FUNCTION" value="createPayee">
    <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
</form>

<script>
(function initNewPayeeModal() {
    const modal = document.getElementById('popupBox');
    if (!modal || modal.dataset.inited === '1') return;
    modal.dataset.inited = '1';

    // Header/Footer
    const header = modal.querySelector('.modal-header');
    const footer = modal.querySelector('.modal-footer');
    if (header) header.innerHTML = '<a href="javascript:void(0)" class="sa">New Payee</a>';
    if (footer) {
        footer.innerHTML =
            '<button id="btnConfirm" type="button" class="btn btn-info me-2"><i class="fad fa-save me-2"></i>Save</button>' +
            '<button id="btnCancel"  type="button" class="btn btn-danger"><i class="fad fa-times me-2"></i>Cancel</button>';
    }

    const form = document.getElementById('payeeForm');
    const nameInput = document.getElementById('payee_name');
    const typeInput = document.getElementById('payee_type');
    const btnConfirm = document.getElementById('btnConfirm');
    const btnCancel = document.getElementById('btnCancel');

    // Mode from URL (?type=out|exp)
    let mode = 'out';
    try {
        const u = new URL(window.location.href);
        const m = (u.searchParams.get('type') || '').toLowerCase();
        if (m === 'exp' || m === 'out') mode = m;
    } catch {}
    typeInput.value = mode;

    btnCancel?.addEventListener('click', () => {
        if (typeof killModal === 'function') killModal('popupBox');
    });

    btnConfirm?.addEventListener('click', () => {
        const name = (nameInput.value || '').trim();
        if (!name) {
            (parent.showResponse || alert)('danger', 'Please enter a payee name');
            return;
        }
        form.requestSubmit ? form.requestSubmit() : form.submit();
    });

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const name = (nameInput.value || '').trim();
        if (!name) {
            (parent.showResponse || alert)('danger', 'Please enter a payee name');
            return;
        }

        btnConfirm.setAttribute('disabled', 'disabled');

        try {
            const fd = new FormData(form);
            fd.set('FUNCTION', 'createPayee');
            fd.set('tenant', '<?= TENANT_URL ?>');
            fd.set('type', mode);
            fd.set('payee_name', name);

            const body = new URLSearchParams();
            for (const [k, v] of fd.entries()) body.append(k, v);

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

            const raw = (await resp.text()).trim();
            let data = null;
            try {
                data = JSON.parse(raw);
            } catch {}

            // fallback: success|id|name
            if (!data && /^success(\|.*)?$/i.test(raw)) {
                const p = raw.split('|');
                data = {
                    status: 'ok',
                    id: (p[1] || ''),
                    name: (p[2] || name)
                };
            }

            if (!data || data.status !== 'ok') {
                (parent.showResponse || alert)('danger', (data && data.message) || raw || 'Error saving payee');
                btnConfirm.removeAttribute('disabled');
                return;
            }

            const newName = String(data.name || name).trim();

            // Update parent select #payee and select it
            const pdoc = parent.document;
            const sel = pdoc.getElementById('payee');
            if (sel) {
                // add option if missing
                let opt = Array.from(sel.options).find(o => o.value === newName);
                if (!opt) {
                    opt = pdoc.createElement('option');
                    opt.value = newName;
                    opt.textContent = newName;
                    sel.appendChild(opt);
                } else {
                    opt.textContent = newName;
                }
                sel.value = newName;

                // Refresh parent MDB Select with filter
                try {
                    parent.mdb.Select.getInstance(sel)?.dispose();
                } catch {}
                try {
                    const inst = new parent.mdb.Select(sel, {
                        filter: true,
                        container: 'body'
                    });
                    if (typeof inst.setValue === 'function') inst.setValue(newName);
                } catch {}
            }

            if (typeof parent.showResponse === 'function') parent.showResponse('success', 'Payee added');
            if (typeof killModal === 'function') killModal('popupBox');

        } catch (err) {
            (parent.showResponse || alert)('danger', 'Network or server error while saving payee');
            btnConfirm.removeAttribute('disabled');
        }
    });
})();
</script>