<?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');
}

require_once('../finance_functions.php');

$id = isset($_REQUEST['id']) ? (int)$_REQUEST['id'] : 0;
if ($id <= 0) {
    echo '<div class="alert alert-danger mb-0">Invalid expense reference.</div>';
    exit;
}

$stmt = $GLOBALS['con']->prepare("SELECT `id`,`employee`,`type`,`desc`,`date`,`amount`,`totals`,`payment_method`,`vatrate`,`vMileage` FROM `expenses` WHERE `id`=? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res ? $res->fetch_assoc() : null;
$stmt->close();

if (!$row) {
    echo '<div class="alert alert-danger mb-0">Expense not found.</div>';
    exit;
}

if ((int)($row['vMileage'] ?? 0) === 1) {
    echo '<div class="alert alert-warning mb-0"><strong>Mileage entries cannot be edited here.</strong><br>Delete and re-enter if required.</div>';
    exit;
}

// totals: "net|vat"
$parts = explode('|', (string)($row['totals'] ?? '0|0'));
$net   = isset($parts[0]) ? (float)$parts[0] : 0.0;
$vat   = isset($parts[1]) ? (float)$parts[1] : 0.0;
$gross = (float)($row['amount'] ?? ($net + $vat));

$vatOn = ($vat > 0.00001);
$dateDMY = date('d-m-Y', (int)($row['date'] ?? time()));

$employee = (string)($row['employee'] ?? '');
$type     = (string)($row['type'] ?? '');
$details  = (string)($row['desc'] ?? '');
$method   = (string)($row['payment_method'] ?? 'BACS');
$vatrate  = (string)($row['vatrate'] ?? '0.20');
?>
<div id="expEditRoot">
    <form id="expEditForm" autocomplete="off">
        <input type="hidden" id="exp_id" value="<?= (int)$id ?>">
        <input type="hidden" id="exp_vatrate" value="<?= htmlspecialchars($vatrate) ?>">

        <div class="row g-3">
            <div class="col-12 col-md-4 date-picker"
                 data-date-type="open"
                 data-format="dd-mm-yyyy"
                 data-mdb-toggle-button="false">
                <label class="form-label" for="edit_date">Date</label>
                <input class="form-control" type="text" id="edit_date" name="date"
                       value="<?= htmlspecialchars($dateDMY) ?>"
                       placeholder="dd-mm-yyyy"
                       data-mdb-confirmDateOnSelect
                       data-mdb-toggle="datepicker" />
            </div>

            <div class="col-12 col-md-4">
                <label class="form-label" for="edit_employee">Employee</label>
                <input class="form-control" type="text" id="edit_employee" value="<?= htmlspecialchars($employee) ?>">
            </div>

            <div class="col-12 col-md-4">
                <label class="form-label" for="edit_type">Type</label>
                <input class="form-control" type="text" id="edit_type" value="<?= htmlspecialchars($type) ?>">
            </div>

            <div class="col-12">
                <label class="form-label" for="edit_details">Details</label>
                <textarea class="form-control" id="edit_details" rows="2"><?= htmlspecialchars($details) ?></textarea>
            </div>

            <div class="col-12 col-md-4">
                <div class="d-flex justify-content-between align-items-center">
                    <label class="form-label mb-0" for="edit_net">Net</label>
                    <div class="btn-group btn-group-sm" role="group" aria-label="VAT mode">
                        <input type="radio" class="btn-check" name="vat_mode" id="vat_on" autocomplete="off" <?= $vatOn ? 'checked' : '' ?>>
                        <label class="btn btn-info" for="vat_on"
                               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                               title="Apply VAT to this expense">Apply VAT</label>

                        <input type="radio" class="btn-check" name="vat_mode" id="vat_off" autocomplete="off" <?= !$vatOn ? 'checked' : '' ?>>
                        <label class="btn btn-secondary" for="vat_off"
                               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                               title="Record this expense without VAT">No VAT</label>
                    </div>

                </div>
                <input class="form-control" type="number" step="0.01" id="edit_net" value="<?= htmlspecialchars(number_format($net, 2, '.', '')) ?>">
                <div id="vatCalcText" class="form-text">
                    <!-- populated by JS -->
                </div>

            </div>

            <div class="col-12 col-md-4">
                <label class="form-label" for="edit_vat">VAT</label>
                <input class="form-control" type="number" step="0.01" id="edit_vat" value="<?= htmlspecialchars(number_format($vat, 2, '.', '')) ?>">
            </div>

            <div class="col-12 col-md-4">
                <label class="form-label" for="edit_gross">Gross</label>
                <input class="form-control" type="number" step="0.01" id="edit_gross" value="<?= htmlspecialchars(number_format($gross, 2, '.', '')) ?>">
            </div>

            <div class="col-12 col-md-6">
                <label class="form-label" for="edit_method">Method</label>
                <select class="form-select" id="edit_method">
                    <?php
                    $methods = ['Cash','BACS','Card','Cheque'];
                    foreach ($methods as $m) {
                        $sel = (strcasecmp($method, $m) === 0) ? 'selected' : '';
                        echo '<option value="'.htmlspecialchars($m).'" '.$sel.'>'.htmlspecialchars($m).'</option>';
                    }
                    // keep legacy value if it isn't in the standard list
                    if ($method !== '' && !in_array($method, $methods, true)) {
                        echo '<option value="'.htmlspecialchars($method).'" selected>'.htmlspecialchars($method).'</option>';
                    }
                    ?>
                </select>
            </div>
        </div>
    </form>
</div>

<script>
(function() {
    const root = document.getElementById('expEditRoot');
    if (!root) return;

    // Set modal chrome
    (function initModalChrome() {
        const modal = document.getElementById('popupBox');
        if (!modal) return;
        const hdr = modal.querySelector('.modal-header');
        const ftr = modal.querySelector('.modal-footer');
        if (hdr) hdr.innerHTML = '<span class="sa">Edit Expense</span>';
        if (ftr) {
            ftr.innerHTML =
                '<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 changes">' +
                '<i class="fad fa-save me-2"></i>Save</button>' +
                '<button type="button" id="btnCancel" class="btn btn-danger" ' +
                'data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Cancel">' +
                '<i class="fad fa-times me-2"></i>Cancel</button>';
        }
    })();

    // Init tooltips (MDB)
    root.querySelectorAll('[data-mdb-tooltip-init]').forEach((el) => {
        try {
            new mdb.Tooltip(el);
        } catch (e) {}
    });

    function formatGBP(value) {
        const num = Number(value) || 0;
        return '£' + num.toLocaleString('en-GB', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }

    function initDatepickers() {
        const modalElement = document.getElementById('popupBox') || document;
        const datepickerElements = modalElement.querySelectorAll(".date-picker");
        datepickerElements.forEach((datepickerEl) => {
            try {
                const options = {
                    confirmDateOnSelect: true,
                    format: "dd-mm-yyyy"
                };
                new mdb.Datepicker(datepickerEl, options);
            } catch (e) {}
        });
    }
    initDatepickers();

    const vatOnEl = document.getElementById('vat_on');
    const vatOffEl = document.getElementById('vat_off');
    const vatCalcText = document.getElementById('vatCalcText');
    const netEl = document.getElementById('edit_net');
    const vatEl = document.getElementById('edit_vat');
    const grossEl = document.getElementById('edit_gross');


    function toNum(v) {
        const n = parseFloat(String(v).replace(/[^0-9.\-]/g, ''));
        return isNaN(n) ? 0 : n;
    }

    function round2(n) {
        return Math.round((n + Number.EPSILON) * 100) / 100;
    }

    function isVatOn() {
        return !!(vatOnEl && vatOnEl.checked);
    }

    function applyVatRules(source) {
        const addVat = isVatOn();

        const net = toNum(netEl.value);
        let vat = toNum(vatEl.value);

        if (!addVat) {
            vat = 0;
            vatEl.value = vat.toFixed(2);
            grossEl.value = round2(net).toFixed(2);
        } else {
            const rate = toNum(document.getElementById('exp_vatrate')?.value || '0.20') || 0.20;

            if (source === 'net' || source === 'toggle') {
                vat = round2(net * rate);
                vatEl.value = vat.toFixed(2);
            } else if (source === 'vat') {
                vat = round2(vat);
                vatEl.value = vat.toFixed(2);
            }

            grossEl.value = round2(net + toNum(vatEl.value)).toFixed(2);
        }

        // Always show the requested helper text format
        const netOut = round2(toNum(netEl.value));
        const vatOut = round2(toNum(vatEl.value));
        const grossOut = round2(toNum(grossEl.value));
        if (vatCalcText) {
            vatCalcText.textContent =
                `${formatGBP(netOut)} net / ${formatGBP(vatOut)} VAT / ${formatGBP(grossOut)} gross`;
        }
    }


    vatOnEl.addEventListener('change', () => applyVatRules('toggle'));
    vatOffEl.addEventListener('change', () => applyVatRules('toggle'));
    netEl.addEventListener('input', () => applyVatRules('net'));
    vatEl.addEventListener('input', () => applyVatRules('vat'));

    (function syncInitialVatMode() {
        const loadedVat = round2(toNum(vatEl.value));
        if (loadedVat <= 0) {
            if (vatOffEl) vatOffEl.checked = true;
        } else {
            if (vatOnEl) vatOnEl.checked = true;
        }
    })();
    applyVatRules('init');

    const btnCancel = document.getElementById('btnCancel');
    if (btnCancel) {
        btnCancel.addEventListener('click', () => killModal('popupBox'));
    }

    const btnConfirm = document.getElementById('btnConfirm');
    if (btnConfirm) {
        btnConfirm.addEventListener('click', () => {
            const id = toNum(document.getElementById('exp_id').value);

            const post = new URLSearchParams();
            post.append('FUNCTION', 'update_expense');
            post.append('id', String(id));
            post.append('tenant', TENANT_URL);

            post.append('date', (document.getElementById('edit_date').value || '').trim());
            post.append('employee', (document.getElementById('edit_employee').value || '').trim());
            post.append('type', (document.getElementById('edit_type').value || '').trim());
            post.append('desc', (document.getElementById('edit_details').value || '').trim());
            post.append('payment_method', (document.getElementById('edit_method').value || '').trim());

            let net = round2(toNum(netEl.value));
            let vat = round2(toNum(vatEl.value));
            let gross = round2(toNum(grossEl.value));

            const addVat = isVatOn();

            // authoritative rules at point of save
            if (!addVat) {
                vat = 0;
                gross = net;

                // keep UI consistent
                vatEl.value = vat.toFixed(2);
                grossEl.value = gross.toFixed(2);
            } else {
                // keep gross consistent when VAT is on
                gross = round2(net + vat);
                grossEl.value = gross.toFixed(2);
            }

            post.append('net', net.toFixed(2));
            post.append('vat', vat.toFixed(2));
            post.append('gross', gross.toFixed(2));
            post.append('add_vat', addVat ? '1' : '0');

            fetch(`${ROOT_URL}/includes/finance/expenses/finance_expense_functions.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: post.toString()
                })
                .then(r => r.text())
                .then(t => {
                    const resp = (t || '').trim();
                    if (resp === 'success') {
                        if (typeof showResponse === 'function') showResponse('success', 'Expense updated.');
                        killModal('popupBox');
                        // Reload list container if present
                        if (typeof loadList === 'function') {
                            const fromEl = document.getElementById('flt_from');
                            const toEl = document.getElementById('flt_to');

                            const from = fromEl ? (fromEl.value || '').trim() : '';
                            const to = toEl ? (toEl.value || '').trim() : '';
                            loadList(from, to);
                        } else {
                            // fallback: refresh current data block if it exists
                            const el = document.getElementById('expenseData');
                            if (el) el.dispatchEvent(new Event('refresh'));
                        }
                    } else {
                        if (typeof showResponse === 'function') showResponse('danger', resp || 'Update failed.');
                    }
                })
                .catch(() => {
                    if (typeof showResponse === 'function') showResponse('danger', 'Network error updating expense.');
                });
        });
    }
})();
</script>