<?php //ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);
// finance_out_edit.php 
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 = (int)($_REQUEST['id'] ?? 0);
if ($id <= 0) {
    ?>
<div class="modal-body">
    <div class="alert alert-danger mb-0">Invalid record reference.</div>
</div>
<?php
    exit;
}

$stmt = $GLOBALS['con']->prepare("
    SELECT `id`,`date`,`payee`,`type`,`code`,`desc`,`totals`,`amount`,`vatrate`,`payment_method`,`chequeNo`
    FROM `expenses`
    WHERE `id`=? AND `payment_type`='Outgoings'
");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

if (!$row) {
    ?>
<div class="modal-body">
    <div class="alert alert-danger mb-0">Record not found.</div>
</div>
<?php
    exit;
}

$tv    = explode('|', $row['totals'] ?? '0|0');
$net   = (float)($tv[0] ?? 0);
$vat   = (float)($tv[1] ?? 0);
// amount column stores GROSS
$gross = (float)($row['amount'] ?? 0);

$dateStr      = date('d-m-Y', (int)$row['date']);
$method       = $row['payment_method'] ?? 'BACS';
$cheque       = $row['chequeNo'] ?? '';
$vatrate      = $row['vatrate'] ?? '0.20';
$currentCode  = (string)($row['code'] ?? '');
$currentPayee = (string)($row['payee'] ?? '');

// Detect linked commission/invoice from existing row
$linkedInvoiceNo = 0;
$linkedInvoiceLabel = '';
$linkedInvoiceStatus = null;

$isCommissionOutgoing = (
    strcasecmp((string)($row['type'] ?? ''), 'Commission') === 0 ||
    strcasecmp((string)($row['code'] ?? ''), 'Commission') === 0
);
$descText = (string)($row['desc'] ?? '');

if ($isCommissionOutgoing && $descText !== '' && preg_match('/invoice\s+(\d{1,10})/i', $descText, $m)) {
    $linkedInvoiceLabel = $m[1];
    $linkedInvoiceNo = (int)ltrim($linkedInvoiceLabel, '0');

    if ($linkedInvoiceNo > 0) {
        $stmtInv = $GLOBALS['con']->prepare("SELECT `invNo`,`status` FROM `invoices` WHERE `invNo`=?");
        if ($stmtInv) {
            $stmtInv->bind_param('i', $linkedInvoiceNo);
            if ($stmtInv->execute()) {
                $resInv = $stmtInv->get_result();
                if ($invRow = $resInv->fetch_assoc()) {
                    $linkedInvoiceStatus = isset($invRow['status']) ? (int)$invRow['status'] : null;
                }
            }
            $stmtInv->close();
        }
    }
}

if ($linkedInvoiceNo > 0 && $linkedInvoiceLabel === '') {
    $linkedInvoiceLabel = str_pad((string)$linkedInvoiceNo, 6, '0', STR_PAD_LEFT);
}

// Initial VAT state: if stored VAT > 0, VAT ON; else NO VAT
$vatApplied = $vat > 0;
?>


<form id="outEditForm" autocomplete="off">
    <div class="row g-2">
        <!-- Date -->
        <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="control-label" for="edit_date">Date</label>
            <input
                   type="text"
                   id="edit_date"
                   name="date"
                   class="form-control"
                   value="<?= htmlspecialchars($dateStr) ?>"
                   placeholder="dd-mm-yyyy"
                   data-mdb-confirmDateOnSelect
                   data-mdb-toggle="datepicker">
        </div>

        <!-- Payee -->
        <div class="col-12 col-md-4"><?=$currentPayee?>
            <label for="edit_payee">Payee</label>
            
            <select class="form-control form-control-sm" id="payee" name="payee" data-placeholder="Select Payee">
                                    <?= listPayee('out',$currentPayee) ?>
                                </select>
            
        </div>


        <!-- Code / Type -->
        <div class="col-12 col-md-4">
            <label>Type</label>
            <select class="form-control-sm w-100" id="type" name="type" data-placeholder="Select Type">
                                    <?= listCodes('payee','desc',$row['type']) ?>
                                </select>
            <input type="hidden" name="code" value="<?= htmlspecialchars($currentCode) ?>">
            
        </div>
    </div>

    <!-- Payee + Amount / VAT / Total -->
    <div class="row g-2 mt-2">
        <div class="col-12 col-md-4">
            <label for="edit_amount">Amount (gross)</label>
            <input
                   type="text"
                   id="edit_amount"
                   name="amount_display"
                   class="form-control"
                   value="<?= htmlspecialchars(number_format($gross, 2, '.', '')) ?>"
                   inputmode="decimal"
                   placeholder="0.00">
            <div id="edit_vatHelper" class="form-text text-muted small"></div>
        </div>

        <div class="col-6 col-md-2" id="edit_vat_row" style="<?= $vatApplied ? '' : 'display:none' ?>">
            <label for="edit_vat">VAT</label>
            <input
                   type="text"
                   id="edit_vat"
                   name="vat"
                   class="form-control"
                   value="<?= $vatApplied ? htmlspecialchars(number_format($vat, 2, '.', '')) : '' ?>"
                   inputmode="decimal"
                   placeholder="0.00">
            <button type="button" id="btnEditResetVat"
                    class="btn btn-link btn-sm p-0 mt-1"
                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                    title="Reset VAT to auto-calculated value">
                Reset VAT
            </button>
        </div>

        <div class="col-6 col-md-2">
            <label for="edit_gross">Net</label>
            <input
                   type="text"
                   id="edit_gross"
                   class="form-control"
                   value="<?= htmlspecialchars(number_format($net, 2, '.', '')) ?>"
                   inputmode="decimal"
                   placeholder="0.00"
                   readonly>
        </div>

        <!-- VAT toggle -->
        <div class="col-12 col-md-4">
            <label class="control-label d-block mb-1">VAT</label>
            <div class="btn-group" role="group" aria-label="VAT toggle">
                <?php
                    $vatOn  = $vatApplied;
                    $vatOff = !$vatApplied;
                    ?>
                <input
                       type="radio"
                       class="btn-check"
                       name="vat_toggle"
                       id="vat_on_edit"
                       autocomplete="off"
                       <?= $vatOn ? 'checked' : '' ?>>
                <label
                       class="btn btn-sm <?= $vatOn ? 'btn-info' : 'btn-secondary' ?>"
                       for="vat_on_edit"
                       data-mdb-tooltip-init
                       data-mdb-placement="top"
                       data-mdb-trigger="hover"
                       title="Apply VAT automatically">
                    <i class="fad fa-percentage me-1"></i>Apply VAT
                </label>

                <input
                       type="radio"
                       class="btn-check"
                       name="vat_toggle"
                       id="vat_off_edit"
                       autocomplete="off"
                       <?= $vatOff ? 'checked' : '' ?>>
                <label
                       class="btn btn-sm <?= $vatOff ? 'btn-info' : 'btn-secondary' ?>"
                       for="vat_off_edit"
                       data-mdb-tooltip-init
                       data-mdb-placement="top"
                       data-mdb-trigger="hover"
                       title="No VAT">
                    <i class="fad fa-ban me-1"></i>No VAT
                </label>
            </div>
        </div>
    </div>

    <!-- Hidden VAT rate (no display, keeps DB consistent) -->
    <input type="hidden" id="edit_vatrate" name="vatrate" value="<?= htmlspecialchars($vatrate) ?>">

    <!-- Method + Cheque -->
    <div class="mt-3">
        <label class="control-label d-block mb-1">Method</label>
        <div class="btn-group" role="group" aria-label="Method">
            <?php
                $methods = [
                    'BACS'   => 'fa-university',
                    'Card'   => 'fa-credit-card',
                    'Cheque' => 'fa-money-check',
                    'Cash'   => 'fa-money-bill-wave'
                ];
                foreach ($methods as $val => $icon):
                    $idAttr   = 'edit_method_' . strtolower($val);
                    $isActive = (strtolower($method) === strtolower($val)) ? 'btn-info' : 'btn-secondary';
                    $checked  = (strtolower($method) === strtolower($val)) ? 'checked' : '';
                    ?>
            <input
                   type="radio"
                   class="btn-check"
                   name="payment_method"
                   id="<?= $idAttr ?>"
                   value="<?= $val ?>"
                   <?= $checked ?>>
            <label
                   class="btn <?= $isActive ?>"
                   for="<?= $idAttr ?>"
                   data-mdb-tooltip-init
                   data-mdb-placement="top"
                   data-mdb-trigger="hover"
                   title="<?= $val ?> payment">
                <i class="fad <?= $icon ?> me-1"></i><?= $val ?>
            </label>
            <?php endforeach; ?>
        </div>

        <div
             id="edit_cheque_row"
             class="mt-2"
             style="<?= (strtolower($method) === 'cheque') ? '' : 'display:none' ?>">
            <label class="control-label" for="edit_cheque">Cheque number</label>
            <input
                   type="text"
                   id="edit_cheque"
                   name="chequeNo"
                   class="form-control"
                   placeholder="Cheque number"
                   value="<?= htmlspecialchars($cheque) ?>">
        </div>
    </div>

    <!-- Details -->
    <div class="mt-2">
        <?php if ($linkedInvoiceNo > 0): ?>
        <div class="alert alert-warning py-2 mb-2">
            <i class="fad fa-link me-2"></i>
            This commission payment is linked to invoice
            <strong><?= htmlspecialchars($linkedInvoiceLabel) ?></strong>.
            <?php if ($linkedInvoiceStatus === 3): ?>
            <br>
            <small>
                Note: this invoice is already marked as paid.
                Updating this entry can affect the commission figures recorded against that invoice.
            </small>
            <?php endif; ?>
        </div>
        <div class="form-check mb-2">
            <input class="form-check-input" type="checkbox"
                   id="update_invoice"
                   name="update_invoice"
                   value="1">
            <label class="form-check-label" for="update_invoice">
                Update the linked invoice commission amount when saving
            </label>
        </div>
        <?php endif; ?>
        <label for="edit_desc">Details</label>
        <textarea
                  class="form-control"
                  id="edit_desc"
                  name="desc"
                  rows="3"
                  placeholder="Details"><?= htmlspecialchars($row['desc']) ?></textarea>
    </div>

    <!-- Hidden fields -->
    <input type="hidden" name="FUNCTION" value="update_outgoing">
    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
    <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
</form>


<div class="row">
    <div class="col-12 mt-4">
        <button
                type="button"
                id="btnSaveOutgoingEdit"
                class="btn btn-info d-inline float-start"
                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"
                class="btn btn-secondary d-inline float-end"
                onclick="killModal('popupBox')"
                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                title="Cancel">
            <i class="fad fa-times me-2"></i>Cancel
        </button>
    </div>
</div>
<script>
(function() {
    const form = document.getElementById('outEditForm');
    const amountEl = document.getElementById('edit_amount');
    const vatEl = document.getElementById('edit_vat');
    const grossEl = document.getElementById('edit_gross');
    const rateEl = document.getElementById('edit_vatrate');
    const helperEl = document.getElementById('edit_vatHelper');
    const resetVatBtn = document.getElementById('btnEditResetVat');
    const vatRowEl = document.getElementById('edit_vat_row');

    const vatOnBtn = document.getElementById('vat_on_edit');
    const vatOffBtn = document.getElementById('vat_off_edit');

    const chequeRow = document.getElementById('edit_cheque_row');
    const chequeEl = document.getElementById('edit_cheque');

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

function getVatRatePercent() {
    const raw = rateEl?.value || '0';
    const v = parseFloat(String(raw).replace(',', '.'));

    if (isNaN(v) || v <= 0) return 20;

    // Stored as fraction (0.2 = 20%)
    if (v > 0 && v < 1.01) return v * 100;

    // Stored as multiplier (1.2 = 20%, 1.05 = 5%)
    // Treat values close to 1.x as multiplier, not percent.
    if (v >= 1 && v < 3) return (v - 1) * 100;

    // Otherwise assume already percent (e.g. 20)
    return v;
}


    function isVatApplied() {
        return !!vatOnBtn?.checked;
    }

    let userVatOverride = false;

    function updateVatToggleUI() {
        const onLbl = document.querySelector('label[for="vat_on_edit"]');
        const offLbl = document.querySelector('label[for="vat_off_edit"]');
        const apply = isVatApplied();

        if (apply) {
            vatRowEl?.style?.setProperty('display', '');
            onLbl?.classList.add('btn-info');
            onLbl?.classList.remove('btn-secondary');
            offLbl?.classList.remove('btn-info');
            offLbl?.classList.add('btn-secondary');
        } else {
            vatRowEl?.style?.setProperty('display', 'none');
            offLbl?.classList.add('btn-info');
            offLbl?.classList.remove('btn-secondary');
            onLbl?.classList.remove('btn-info');
            onLbl?.classList.add('btn-secondary');
        }
    }

    function recalc() {
        // Amount input is GROSS
        const gross = toNumber(amountEl?.value);
        let vat = toNumber(vatEl?.value);
        const rate = getVatRatePercent();
        const apply = isVatApplied();

        let net = gross;

        if (apply) {
            if (!userVatOverride) {
                const divisor = 1 + (rate / 100);
                net = divisor > 0 ? (gross / divisor) : gross;
                net = Math.round(net * 100) / 100;
                vat = gross - net;
                vat = Math.round(vat * 100) / 100;
                if (vatEl) vatEl.value = vat.toFixed(2);
            } else {
                vat = toNumber(vatEl?.value);
                net = gross - vat;
                if (net < 0) net = 0;
                net = Math.round(net * 100) / 100;
            }
        } else {
            vat = 0;
            net = gross;
            if (vatEl) vatEl.value = '';
        }

        if (grossEl) grossEl.value = net.toFixed(2);

        if (helperEl) {
            if (apply) {
                helperEl.textContent = `£${gross.toFixed(2)} gross / £${net.toFixed(2)} net / £${vat.toFixed(2)} VAT`;
            } else {
                helperEl.textContent = '';
            }
        }
    }

    // Amount change
    amountEl?.addEventListener('input', () => {
        if (isVatApplied() && !userVatOverride) {
            // keep auto-calc behaviour
        }
        recalc();
    });

    // VAT rate change (if ever changed)
    rateEl?.addEventListener('input', () => {
        userVatOverride = false;
        recalc();
    });

    // VAT toggle
    vatOnBtn?.addEventListener('change', () => {
        if (vatOnBtn.checked) {
            vatOffBtn.checked = false;
        }
        updateVatToggleUI();
        recalc();
    });
    vatOffBtn?.addEventListener('change', () => {
        if (vatOffBtn.checked) {
            vatOnBtn.checked = false;
        }
        updateVatToggleUI();
        recalc();
    });

    // VAT input manual override
    vatEl?.addEventListener('input', () => {
        const val = toNumber(vatEl?.value);
        if (val > 0) {
            if (vatOffBtn) vatOffBtn.checked = false;
            if (vatOnBtn) vatOnBtn.checked = true;
            userVatOverride = true;
        } else {
            userVatOverride = false;
        }
        updateVatToggleUI();
        recalc();
    });

    // Reset VAT -> calculated from amount & rate
    resetVatBtn?.addEventListener('click', (e) => {
        e.preventDefault();
        userVatOverride = false;
        recalc();
    });

    // Method toggle (show/hide cheque field)
    document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
        radio.addEventListener('change', () => {
            const val = radio.value.toLowerCase();
            if (val === 'cheque') {
                chequeRow?.style?.setProperty('display', '');
            } else {
                chequeRow?.style?.setProperty('display', 'none');
                if (chequeEl) chequeEl.value = '';
            }
        });
    });

    // Initial UI sync
  function calcVatFromGross(gross) {
    const rate = getVatRatePercent();
    const divisor = 1 + (rate / 100);
    let net = divisor > 0 ? (gross / divisor) : gross;
    net = Math.round(net * 100) / 100;
    let vat = gross - net;
    vat = Math.round(vat * 100) / 100;
    return vat;
}

function initVatOverrideFromStored() {
    if (!isVatApplied()) {
        userVatOverride = false;
        return;
    }

    const gross = toNumber(amountEl?.value);
    const storedVat = toNumber(vatEl?.value);

    // If there is a stored VAT value, decide if it’s an override by comparing to calculated VAT
    if (storedVat > 0) {
        const calcVat = calcVatFromGross(gross);
        userVatOverride = Math.abs(storedVat - calcVat) > 0.01;
    } else {
        userVatOverride = false;
    }
}

// Initial UI sync
updateVatToggleUI();
initVatOverrideFromStored();
recalc();

    // Submit
    document.getElementById('btnSaveOutgoingEdit')?.addEventListener('click', async () => {
        if (!form) return;
        const body = new URLSearchParams(new FormData(form));

        const gross = toNumber(amountEl?.value);
        const vat = isVatApplied() ? toNumber(vatEl?.value) : 0;
        let net = toNumber(grossEl?.value);
        if (!net && net !== 0) net = gross;

        // For PHP: totals = net|vat, amount = gross
        body.set('totals', net.toFixed(2) + '|' + vat.toFixed(2));
        body.set('amount', gross.toFixed(2));

        if (!body.get('tenant')) body.set('tenant', TENANT_URL);

        try {
            const res = await fetch(ROOT_URL + '/includes/finance/outgoings/finance_outgoing_functions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body
            });
            const txt = (await res.text()).trim();
            if (txt === 'success' || txt === 's') {
                showResponse('success', 'Outgoing updated');
                killModal('popupBox');
                if (typeof window.reloadList === 'function') {
                    window.reloadList();
                }
            } else {
                showResponse('danger', txt || 'Update failed');
            }
        } catch (e) {
            showResponse('danger', 'Network error');
        }
    });
})();
</script>