<?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');
}
// includes/finance/finance_rcp_edit.php

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

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

$stmt = $GLOBALS['con']->prepare("
    SELECT `id`,`pType`,`payee`,`details`,`vat`,`totals`,
           `commission`,`method`,`invoice`,`chequeNo`,`date`
      FROM `receipts`
     WHERE `id` = ?
");
$stmt->bind_param('i', $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

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

function money_to_float($val): float {
    $s = trim((string)$val);
    if ($s === '') return 0.0;

    // UK-style DB strings: "2,560.00" => "2560.00"
    $s = str_replace([',', '£', ' '], '', $s);

    // Keep only digits, dot, minus (safety)
    $s = preg_replace('/[^0-9.\-]/', '', $s);

    // If there are multiple dots, keep the last as decimal separator
    if (substr_count($s, '.') > 1) {
        $last = strrpos($s, '.');
        $s = str_replace('.', '', substr($s, 0, $last)) . substr($s, $last);
    }

    return (float)$s;
}

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

$hasVat     = $vat > 0.0001;
$payee      = $row['payee'] ?? '';
$details    = $row['details'] ?? '';
$ptype      = $row['pType'] ?? '';
$method     = $row['method'] ?? 'BACS';
$cheque     = $row['chequeNo'] ?: '';
$invoices   = $row['invoice'] ?? '';
$commission = (float)($row['commission'] ?? 0);
$dateDMY    = date('d-m-Y', (int)$row['date']);

// Commission rate based on NET
$commissionRate = ($net > 0 && $commission > 0)
    ? ($commission / $net * 100)
    : 0.0;

// Linked invoice handling (first invoice only)
$linkedInvoiceId     = 0;
$linkedInvoicePretty = '';
$linkedInvoiceStatus = null; // null = unknown, 1=Unpaid,3=Paid,...

$invStr = trim($invoices);
if ($invStr !== '') {
    // Take the first value before any comma
    $invParts = preg_split('/\s*,\s*/', $invStr);
    $firstRaw = $invParts[0] ?? '';
    $firstRaw = trim($firstRaw);

    if ($firstRaw !== '') {
        // Preserve pretty-printed value with zero-padding
        $linkedInvoicePretty = $firstRaw;

        // Convert to int ID (strip leading zeros)
        $numeric = ltrim($firstRaw, '0');
        if ($numeric === '') {
            $numeric = '0';
        }
        if (ctype_digit($numeric)) {
            $linkedInvoiceId = (int)$numeric;
        }
    }

    // If we have a numeric invoice id, fetch its status
    if ($linkedInvoiceId > 0) {
        $stmtInv = $GLOBALS['con']->prepare("SELECT `status` FROM `invoices` WHERE `invNo` = ? LIMIT 1");
        if ($stmtInv) {
            $stmtInv->bind_param('i', $linkedInvoiceId);
            $stmtInv->execute();
            $resInv = $stmtInv->get_result();
            if ($rowInv = $resInv->fetch_assoc()) {
                $linkedInvoiceStatus = (int)$rowInv['status'];
            }
            $stmtInv->close();
        }
    }
}
?>

<form id="rcpEditForm" autocomplete="off" class="mb-3">

    <!-- Row 1: Date / Payee / Commission -->
    <div class="row g-3">
        <!-- Date -->
        <div class="col-12 col-md-3 date-picker datepicker"
             data-date-type="open"
             data-format="dd-mm-yyyy"
             data-mdb-toggle-button="false">
            <label class="control-label" for="edit_date">Receipt 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>


        <!-- Payee -->
        <div class="col-12 col-md-5">
            <label class="control-label" for="edit_payee">Payee</label>
            <input
                   class="form-control"
                   type="text"
                   id="edit_payee"
                   name="payee"
                   value="<?= htmlspecialchars($payee) ?>" />
        </div>

        <!-- Commission (amount + rate + reset) -->
        <div class="col-12 col-md-4">
            <label class="control-label" for="edit_commission">Commission (amount)</label>
            <input
                   type="text"
                   id="edit_commission"
                   name="commission"
                   class="form-control"
                   value="<?= htmlspecialchars(number_format($commission, 2, '.', '')) ?>"
                   inputmode="decimal"
                   placeholder="0.00" />

            <div class="d-flex align-items-end mt-2">
                <div class="flex-grow-1 me-2">
                    <label class="control-label small mb-1" for="edit_commission_rate">Commission rate (%)</label>
                    <input
                           type="text"
                           id="edit_commission_rate"
                           class="form-control form-control-sm"
                           value="<?= htmlspecialchars(number_format($commissionRate, 2, '.', '')) ?>"
                           readonly />
                </div>
                <div class="mt-4">
                    <button
                            type="button"
                            id="btnCommissionReset"
                            class="btn btn-link btn-sm p-0"
                            data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                            title="Reset commission to original rate">
                        Reset
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Row 2: Amount / VAT / Total -->
    <div class="row g-3 mt-3">
        <!-- Amount (NET) + helper + VAT/Total figures -->
        <div class="col-12 col-lg-4">
            <label class="control-label" for="edit_amount">Amount (NET)</label>
            <input
                   type="text"
                   id="edit_amount"
                   name="amount_net"
                   class="form-control"
                   value="<?= htmlspecialchars(number_format($net, 2, '.', '')) ?>"
                   inputmode="decimal"
                   placeholder="0.00" />
            <small id="edit_vat_helper" class="text-muted d-block mt-1"></small>

            <div class="mt-2">
                <label class="control-label small mb-1" for="edit_vat_amount">VAT amount</label>
                <input
                       type="text"
                       id="edit_vat_amount"
                       class="form-control form-control-sm"
                       value="<?= htmlspecialchars(number_format($vat, 2, '.', '')) ?>"
                       readonly />
            </div>

            <div class="mt-2">
                <label class="control-label small mb-1" for="edit_total">Total (gross)</label>
                <input
                       type="text"
                       id="edit_total"
                       class="form-control form-control-sm"
                       value="<?= htmlspecialchars(number_format($gross, 2, '.', '')) ?>"
                       readonly />
            </div>
        </div>

        <!-- VAT toggle -->
        <div class="col-12 col-lg-4">
            <label class="control-label d-block mb-1">VAT</label>
            <div class="btn-group" role="group" aria-label="VAT mode">
                <input
                       type="radio"
                       class="btn-check"
                       name="use_vat"
                       id="edit_vat_on"
                       value="applyvat"
                       autocomplete="off"
                       <?= $hasVat ? 'checked' : '' ?>>
                <label
                       class="btn <?= $hasVat ? 'btn-info' : 'btn-secondary' ?>"
                       for="edit_vat_on"
                       data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                       title="Apply VAT (20%)">
                    <i class="fad fa-percentage me-1"></i>VAT
                </label>

                <input
                       type="radio"
                       class="btn-check"
                       name="use_vat"
                       id="edit_vat_off"
                       value="novat"
                       autocomplete="off"
                       <?= !$hasVat ? 'checked' : '' ?>>
                <label
                       class="btn <?= !$hasVat ? 'btn-info' : 'btn-secondary' ?>"
                       for="edit_vat_off"
                       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>
            <input type="hidden" id="edit_vatrate" name="vatrate" value="0.20">
        </div>
    </div>

    <!-- Row 3: Method + Cheque -->
    <div class="row g-3 mt-3">
        <div class="col-12 col-md-8">
            <label class="control-label d-block mb-1">Method</label>
            <div class="btn-group" role="group" aria-label="Method">
                <?php
                $methods = [
                    'BACS'   => 'fa-building-columns',
                    'Cheque' => 'fa-money-check-alt',
                    'Cash'   => 'fa-coins',
                    'Card'   => 'fa-credit-card',
                    'Other'  => 'fa-ellipsis-h'
                ];
                foreach ($methods as $val => $icon):
                    $idAttr   = 'm_' . strtolower($val) . '_edit';
                    $checked  = (strtolower($method) === strtolower($val)) ? 'checked' : '';
                    $isActive = $checked ? 'btn-info' : 'btn-secondary';
                    ?>
                <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>

        <div class="col-12 col-md-4">
            <div id="edit_cheque_row" 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"
                       value="<?= htmlspecialchars($cheque) ?>"
                       placeholder="Cheque number" />
            </div>
        </div>
    </div>

    <!-- Row 4: Linked invoices + update option -->
    <div class="mt-3">
        <label class="control-label" for="edit_invoices">Linked invoices (comma-separated)</label>
        <input
               type="text"
               id="edit_invoices"
               name="invoices"
               class="form-control form-control-sm"
               value="<?= htmlspecialchars($invoices) ?>"
               placeholder="e.g. 000123, 000124" />

        <?php if ($linkedInvoiceId > 0): ?>
        <div class="form-check mt-2">
            <input
                   class="form-check-input"
                   type="checkbox"
                   id="update_invoice"
                   name="update_invoice"
                   value="1">
            <label class="form-check-label small" for="update_invoice">
                Also update linked invoice #<?= htmlspecialchars($linkedInvoicePretty) ?> totals
                (net, VAT and commission) to match this receipt.
            </label>
        </div>

        <?php if ($linkedInvoiceStatus === 3): ?>
        <div class="mt-1 small text-warning">
            <i class="fad fa-exclamation-triangle me-1"></i>
            Warning: This invoice is currently marked as paid. Updating financial values may cause
            discrepancies with previous records and reports.
        </div>
        <?php endif; ?>

        <input type="hidden" name="invoice_id" value="<?= (int)$linkedInvoiceId ?>">
        <?php endif; ?>
    </div>

    <!-- Row 5: Details -->
    <div class="mt-3">
        <label class="control-label" for="edit_details">Details</label>
        <textarea
                  id="edit_details"
                  name="details"
                  class="form-control"
                  rows="3"
                  placeholder="Description of receipt"><?= htmlspecialchars($details) ?></textarea>
    </div>

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

<div class="row mt-2">
    <div class="col-12 d-flex justify-content-between">
        <button
                type="button"
                class="btn btn-secondary"
                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>
        <button
                type="button"
                id="btnSaveReceiptEdit"
                class="btn btn-info"
                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>
    </div>
</div>

<script>
(function() {
    const form = document.getElementById('rcpEditForm');
    const amountEl = document.getElementById('edit_amount');
    const helperEl = document.getElementById('edit_vat_helper');
    const vatOnEl = document.getElementById('edit_vat_on');
    const vatOffEl = document.getElementById('edit_vat_off');
    const vatrateEl = document.getElementById('edit_vatrate');
    const chequeRow = document.getElementById('edit_cheque_row');
    const vatAmountEl = document.getElementById('edit_vat_amount');
    const totalEl = document.getElementById('edit_total');

    const commEl = document.getElementById('edit_commission');
    const commRateEl = document.getElementById('edit_commission_rate');
    const commResetBtn = document.getElementById('btnCommissionReset');

    let initialCommissionRate = 0; // decimal, e.g. 0.20 for 20%
    let commissionOverride = false;

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

    function fmtGBP(n) {
        return '£' + (Number(n || 0)).toFixed(2);
    }

    function getVatRate() {
        let v = (vatrateEl?.value || '0.20').trim().replace(',', '.');
        let f = parseFloat(v);
        if (isNaN(f) || f <= 0) f = 0.20;
        return f;
    }

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

    function updateVatHelper() {
        if (!amountEl || !helperEl) return;

        const net = num(amountEl.value);
        const vatOn = isVatOn();
        const rate = getVatRate();

        let vat = 0;
        let gross = net;

        if (vatOn && net > 0) {
            vat = +(net * rate).toFixed(2);
            gross = +(net + vat).toFixed(2);
            helperEl.textContent =
                `${fmtGBP(net)} net / ${fmtGBP(vat)} VAT / ${fmtGBP(gross)} gross`;
        } else {
            helperEl.textContent = '';
        }

        if (vatAmountEl) vatAmountEl.value = vat.toFixed(2);
        if (totalEl) totalEl.value = gross.toFixed(2);
    }

    // ----- Commission helpers -----
    function initCommissionRate() {
        if (!amountEl || !commEl) return;
        const net = num(amountEl.value);
        const comm = num(commEl.value);
        if (net > 0 && comm > 0) {
            initialCommissionRate = comm / net; // decimal
        } else {
            initialCommissionRate = 0;
        }
        updateCommissionRateDisplay();
    }

    function updateCommissionRateDisplay() {
        if (!amountEl || !commEl || !commRateEl) return;
        const net = num(amountEl.value);
        const comm = num(commEl.value);
        let pct = 0;
        if (net > 0 && comm > 0) {
            pct = (comm / net) * 100;
        }
        commRateEl.value = pct.toFixed(2);
    }

    function updateCommissionFromNet() {
        if (!amountEl || !commEl) return;
        const net = num(amountEl.value);
        if (!commissionOverride && net > 0 && initialCommissionRate > 0) {
            const comm = +(net * initialCommissionRate).toFixed(2);
            commEl.value = comm.toFixed(2);
        }
        updateCommissionRateDisplay();
    }

    // Bind amount + VAT + commission recalcs
    amountEl?.addEventListener('input', () => {
        updateVatHelper();
        updateCommissionFromNet();
    });

    vatOnEl?.addEventListener('change', () => {
        const onLab = document.querySelector('label[for="edit_vat_on"]');
        const offLab = document.querySelector('label[for="edit_vat_off"]');
        if (vatOnEl.checked) {
            onLab?.classList.add('btn-info');
            onLab?.classList.remove('btn-secondary');
            offLab?.classList.add('btn-secondary');
            offLab?.classList.remove('btn-info');
        }
        updateVatHelper();
    });

    vatOffEl?.addEventListener('change', () => {
        const onLab = document.querySelector('label[for="edit_vat_on"]');
        const offLab = document.querySelector('label[for="edit_vat_off"]');
        if (vatOffEl.checked) {
            offLab?.classList.add('btn-info');
            offLab?.classList.remove('btn-secondary');
            onLab?.classList.add('btn-secondary');
            onLab?.classList.remove('btn-info');
        }
        updateVatHelper();
    });

    // Commission manual edit -> override auto behaviour
    commEl?.addEventListener('input', () => {
        const comm = num(commEl.value);
        commissionOverride = comm > 0;
        updateCommissionRateDisplay();
    });

    // Reset commission back to the original rate
    commResetBtn?.addEventListener('click', () => {
        if (!amountEl || !commEl) return;
        const net = num(amountEl.value);
        if (net > 0 && initialCommissionRate > 0) {
            const comm = +(net * initialCommissionRate).toFixed(2);
            commEl.value = comm.toFixed(2);
            commissionOverride = false;
            updateCommissionRateDisplay();
        }
    });

    // Method styling + cheque toggle
    const methodRadios = form.querySelectorAll('input[name="payment_method"].btn-check');

    function updateMethodUI() {
        let m = 'BACS';
        methodRadios.forEach(r => {
            const lab = form.querySelector(`label[for="${r.id}"]`);
            if (r.checked) {
                m = r.value;
                lab?.classList.add('btn-info');
                lab?.classList.remove('btn-secondary');
            } else {
                lab?.classList.remove('btn-info');
                lab?.classList.add('btn-secondary');
            }
        });
        if (chequeRow) {
            chequeRow.style.display = (m === 'Cheque') ? 'block' : 'none';
        }
    }
    methodRadios.forEach(r => r.addEventListener('change', updateMethodUI));
    updateMethodUI();

    // Initial calc state
    updateVatHelper();
    initCommissionRate();

    // Save handler
    document.getElementById('btnSaveReceiptEdit')?.addEventListener('click', async () => {
        if (!form) return;

        // Calculate NET, VAT and GROSS from the current form state
        const net = num(amountEl?.value);
        const rate = getVatRate();
        const vatOn = isVatOn();
        let vat = 0;
        let gross = net;

        if (vatOn && net > 0) {
            vat = +(net * rate).toFixed(2);
            gross = +(net + vat).toFixed(2);
        }

        if (vatAmountEl) vatAmountEl.value = vat.toFixed(2);
        if (totalEl) totalEl.value = gross.toFixed(2);

        const body = new URLSearchParams(new FormData(form));

        // amount = gross, totals = "net|vat"
        body.set('FUNCTION', 'update_receipt');
        body.set('amount', gross.toFixed(2));
        body.set('totals', net.toFixed(2) + '|' + vat.toFixed(2));

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

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

            let status = (parts[0] || '').toLowerCase();
            let action = (parts[1] || '').toLowerCase();
            let invNo = parts[2] || '';
            let clientId = parts[3] || '';
            let rtype = parts[4] || '';
            let brokerCom = parts[5] || '';
            let agentCom = parts[6] || '';
            let brokerId = parts[7] || '';
            let agentId = parts[8] || '';

            if (status === 'success' || status === 'success outgoing' || status === 's') {
                // If the invoice was updated server-side, regenerate it
                if (action === 'invoice_regen' && invNo) {
                    triggerInvoiceRegen(invNo, clientId, rtype, brokerCom, agentCom, brokerId, agentId);
                }

                showResponse('success', 'Receipt updated');
                killModal('popupBox');
                if (typeof window.reloadList === 'function') {
                    reloadList();
                }
            } else {
                showResponse('danger', raw || 'Update failed');
            }
        } catch (e) {
            showResponse('danger', 'Network error');
        }
    });

    function triggerInvoiceRegen(invNo, clientId, rtype, brokerCom, agentCom, brokerId, agentId) {
        if (!invNo) return;

        const post = new URLSearchParams();

        // Core fields
        post.append('invNo', String(invNo).trim());
        if (clientId) post.append('clientnumber', String(clientId).trim());

        // rtype from invoices.target; fall back to "invoice" if empty
        post.append('rtype', (rtype && String(rtype).trim()) || 'invoice');

        const brokerComVal = (brokerCom === 1 || brokerCom === '1') ? '1' : '0';
        const agentComVal = (agentCom === 1 || agentCom === '1') ? '1' : '0';
        post.append('brokerCom', brokerComVal);
        post.append('agentCom', agentComVal);

        // Broker / agent IDs if present
        if (brokerId && String(brokerId).trim() !== '0') {
            post.append('broker_number', String(brokerId).trim());
        }
        if (agentId && String(agentId).trim() !== '0') {
            post.append('agent_number', String(agentId).trim());
        }

        post.append('tenant', TENANT_URL);

        fetch(`${ROOT_URL}/includes/engines/invoice.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: post
        }).catch(() => {});
    }


})();

// --- init MDB datepicker inside this modal ---
function initEditReceiptDatepicker() {
    const modal = document.getElementById('popupBox') || document;
    const wrap = modal.querySelector('#edit_date')?.closest('.date-picker, .datepicker');

    if (!wrap) return;
    if (typeof mdb === 'undefined' || !mdb.Datepicker) return;

    // prevent double init
    if (mdb.Datepicker.getInstance(wrap)) return;

    const format = wrap.dataset.format || 'dd-mm-yyyy';

    new mdb.Datepicker(wrap, {
        confirmDateOnSelect: true,
        format: format
    });
}

// Run now (modal scripts execute after content injection)
initEditReceiptDatepicker();

// Safety: run again after the modal is fully shown
const pb = document.getElementById('popupBox');
if (pb) {
    pb.addEventListener('shown.bs.modal', initEditReceiptDatepicker, {
        once: true
    });
}
</script>