<style>
.cash-bank-list-card .card-body {
    display: flex;
    flex-direction: column;
    gap: var(--sp-4);
}

.cash-bank-summary-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: var(--sp-3);
}

.cb-summary-card {
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    background: linear-gradient(135deg, rgba(212, 168, 67, 0.12), rgba(255, 255, 255, 0.98));
    padding: var(--sp-4);
}

.cb-summary-label {
    display: block;
    font-size: 0.85em;
    color: var(--text-muted);
    margin-bottom: 6px;
}

.cb-summary-value {
    display: block;
    font-size: 1.45em;
    font-weight: 800;
    color: var(--primary);
}

.cb-summary-note {
    display: block;
    margin-top: 8px;
    font-size: 0.85em;
    color: var(--text-muted);
}

.cash-bank-filter-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.cash-bank-filter-bar .form-group {
    margin-bottom: 0;
    min-width: 160px;
    flex: 1 1 180px;
}

.cash-bank-filter-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.cash-bank-scroll {
    max-height: 540px;
    overflow-y: auto;
    border: 1px solid var(--border-light);
    border-radius: var(--radius-sm);
    background-color: #fff;
}

.cash-bank-scroll .table-responsive {
    margin-bottom: 0;
    border: none;
    border-radius: 0;
}

.cash-bank-status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    min-height: 26px;
    font-size: 0.9em;
    color: var(--text-muted);
}

.cash-bank-amount {
    white-space: nowrap;
}

.cb-empty-row td {
    text-align: center;
    color: var(--text-muted);
}

@media (max-width: 768px) {
    .cash-bank-summary-grid {
        grid-template-columns: 1fr;
    }

    .cash-bank-scroll {
        max-height: 420px;
    }

    .cash-bank-filter-actions {
        width: 100%;
    }

    .cash-bank-filter-actions .btn {
        flex: 1 1 0;
    }
}

.cash-bank-dashboard-row {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: var(--sp-4);
    margin-bottom: var(--sp-4);
}

@media (max-width: 992px) {
    .cash-bank-dashboard-row {
        grid-template-columns: repeat(2, 1fr);
    }
}

.cb-bank-list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0;
    border-bottom: 1px dashed var(--border-light);
}

.cb-bank-list-item:last-child {
    border-bottom: none;
}

@media (max-width: 992px) {
    .cash-bank-dashboard-row {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="cash-bank-container">
    <div class="cash-bank-dashboard-row">
        <!-- Box 1: Total Sale -->
        <div class="card cb-dashboard-card" style="background: linear-gradient(135deg, rgba(46, 204, 113, 0.08), rgba(255, 255, 255, 1)); border: 1px solid var(--border);">
            <div class="card-body" style="padding: 16px;">
                <div style="font-size: 0.9em; color: var(--text-muted); margin-bottom: 8px; font-weight: 500;">مجموعی فروخت (Total Sale)</div>
                <div id="cbDashboardTotalSale" style="font-size: 1.8em; font-weight: 800; color: #2ecc71;">0.00</div>
            </div>
        </div>

        <!-- Box 2: Total Purchase -->
        <div class="card cb-dashboard-card" style="background: linear-gradient(135deg, rgba(231, 76, 60, 0.08), rgba(255, 255, 255, 1)); border: 1px solid var(--border);">
            <div class="card-body" style="padding: 16px;">
                <div style="font-size: 0.9em; color: var(--text-muted); margin-bottom: 8px; font-weight: 500;">مجموعی خریداری (Total Purchase)</div>
                <div id="cbDashboardTotalPurchase" style="font-size: 1.8em; font-weight: 800; color: #e74c3c;">0.00</div>
            </div>
        </div>

        <!-- Box 3: Total Expense -->
        <div class="card cb-dashboard-card" style="background: linear-gradient(135deg, rgba(142, 68, 173, 0.08), rgba(255, 255, 255, 1)); border: 1px solid var(--border);">
            <div class="card-body" style="padding: 16px;">
                <div style="font-size: 0.9em; color: var(--text-muted); margin-bottom: 8px; font-weight: 500;">مجموعی اخراجات (Total Expense)</div>
                <div id="cbDashboardTotalExpense" style="font-size: 1.8em; font-weight: 800; color: #8e44ad;">0.00</div>
            </div>
        </div>

        <!-- Box 4: Bank Balances -->
        <div class="card cb-dashboard-card" style="background: linear-gradient(135deg, rgba(52, 152, 219, 0.08), rgba(255, 255, 255, 1)); border: 1px solid var(--border);">
            <div class="card-body" style="padding: 16px; display: flex; flex-direction: column; justify-content: space-between; min-height: 140px;">
                <div>
                    <div style="font-size: 0.9em; color: var(--text-muted); margin-bottom: 12px; border-bottom: 1px solid var(--border-light); padding-bottom: 6px; font-weight: bold;">کیش اور بینک بیلنس (Cash & Bank Balances)</div>
                    <div id="cbDashboardBanksList" style="max-height: 100px; overflow-y: auto; font-size: 0.9em; display: flex; flex-direction: column; gap: 4px; padding-left: 4px;">
                        <!-- Dynamically populated list of banks -->
                    </div>
                </div>
                <div style="border-top: 1px solid var(--border-light); padding-top: 8px; margin-top: 8px; display: flex; justify-content: space-between; align-items: center; font-weight: 800; font-size: 1.1em;">
                    <span>کل رقم (Grand Total):</span>
                    <span id="cbDashboardBanksTotal" style="color: #2980b9;">0.00</span>
                </div>
            </div>
        </div>
    </div>

    <div class="form-grid-2">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title cash-bank-form-title">نقد وصولی / ادائیگی (Naqad/Bank)</h3>
            </div>
            <div class="card-body">
                <form id="cashBankForm">
                    <div class="form-group">
                        <label class="form-label">تاریخ (Date)</label>
                        <input type="date" id="cbDate" class="form-control">
                    </div>

                    <div class="form-group">
                        <label class="form-label">قسم (Entry Type)</label>
                        <div class="toggle-group" id="cbTypeToggle">
                            <button type="button" class="toggle-btn active" data-value="payment">ادائیگی (Cr)</button>
                            <button type="button" class="toggle-btn" data-value="receipt">وصولی (Dr)</button>
                            <button type="button" class="toggle-btn" data-value="transfer">منتقلی (Transfer)</button>
                            <button type="button" class="toggle-btn" data-value="direct_deposit">براہ راست جمع</button>
                            <button type="button" class="toggle-btn" data-value="debit_adj">نام ڈالیں (Dr Adj)</button>
                            <button type="button" class="toggle-btn" data-value="credit_adj">جمع ڈالیں (Cr Adj)</button>
                            <button type="button" class="toggle-btn" data-value="commission_pay">کمیشن ادائیگی</button>
                            <button type="button" class="toggle-btn" data-value="expense">خرچہ (Expense)</button>
                        </div>
                        <input type="hidden" id="cbType" value="payment">
                    </div>

                    <div id="cbModeNormal">
                        <div class="form-group">
                            <label class="form-label">پارٹی منتخب کریں</label>
                            <select id="cbParty" class="form-control select2"></select>
                            <div class="mt-1"><small class="text-muted" id="bal_cbParty"></small></div>
                        </div>
                        <div class="form-group" id="cbItemGroup" style="display: none;">
                            <label class="form-label">جنس (Item) منتخب کریں</label>
                            <select id="cbItem" class="form-control select2"></select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">اکاؤنٹ (کیش / بینک)</label>
                            <select id="cbAccount" class="form-control"></select>
                            <div class="mt-1"><small class="text-muted" id="bal_cbAccount"></small></div>
                        </div>
                    </div>

                    <div id="cbModeTransfer" style="display: none;">
                        <div class="form-group">
                            <label class="form-label">منجانب اکاؤنٹ (Transfer From)</label>
                            <select id="cbFromAccount" class="form-control"></select>
                            <div class="mt-1"><small class="text-accent fw-bold" id="bal_cbFromAccount"></small></div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">بنام اکاؤنٹ (Transfer To)</label>
                            <select id="cbToAccount" class="form-control"></select>
                            <div class="mt-1"><small class="text-success fw-bold" id="bal_cbToAccount"></small></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">رقم (Amount RS)</label>
                        <input type="number" id="cbAmount" class="form-control fw-bold" placeholder="0.00" style="font-size: 1.25em;">
                    </div>

                    <div class="form-group">
                        <label class="form-label">تفصیل (Details / Remarks)</label>
                        <textarea id="cbDetail" class="form-control" rows="2" placeholder="چیک نمبر، بینک تفصیل، وغیرہ..."></textarea>
                    </div>

                    <div class="form-actions" style="margin-top: var(--sp-4);">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save"></i> واؤچر محفوظ کریں
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card cash-bank-list-card">
            <div class="card-header">
                <h3 class="card-title">حالیہ روزنامچہ اندراجات</h3>
            </div>
            <div class="card-body">
                <div class="cash-bank-summary-grid">
                    <div class="cb-summary-card">
                        <span class="cb-summary-label">کل فلٹر شدہ اندراجات</span>
                        <span class="cb-summary-value" id="cbOverallRecords">0</span>
                        <span class="cb-summary-note" id="cbSummaryRange">تمام تاریخیں</span>
                    </div>
                    <div class="cb-summary-card">
                        <span class="cb-summary-label">لوڈ شدہ اندراجات</span>
                        <span class="cb-summary-value" id="cbLoadedRecords">0 / 0</span>
                        <span class="cb-summary-note">اسکرول پر مزید ڈیٹا آتا جائے گا</span>
                    </div>
                    <div class="cb-summary-card">
                        <span class="cb-summary-label">مجموعی رقم</span>
                        <span class="cb-summary-value" id="cbOverallAmount">0.00</span>
                        <span class="cb-summary-note">منتخب فلٹر کے مطابق</span>
                    </div>
                </div>

                <div class="cash-bank-filter-bar">
                    <div class="form-group">
                        <label class="form-label">تاریخ سے</label>
                        <input type="date" id="cbFilterFromDate" class="form-control">
                    </div>
                    <div class="form-group">
                        <label class="form-label">تاریخ تک</label>
                        <input type="date" id="cbFilterToDate" class="form-control">
                    </div>
                    <div class="form-group" style="min-width: 160px; flex: 1 1 180px;">
                        <label class="form-label">جنس (Item)</label>
                        <select id="cbFilterItem" class="form-control select2">
                            <option value="">تمام اجناس...</option>
                        </select>
                    </div>
                    <div class="cash-bank-filter-actions">
                        <button type="button" class="btn btn-primary btn-sm" id="cbApplyFilter">
                            <i class="fas fa-filter"></i> فلٹر دکھائیں
                        </button>
                        <button type="button" class="btn btn-outline btn-sm" id="cbResetFilter">
                            <i class="fas fa-undo"></i> ری سیٹ
                        </button>
                    </div>
                </div>

                <div class="cash-bank-scroll" id="cbEntriesScroll">
                    <div class="table-responsive">
                        <table class="table m-0">
                            <thead>
                                <tr>
                                    <th>تاریخ</th>
                                    <th>تفصیل</th>
                                    <th>رقم</th>
                                    <th>ایکشن</th>
                                </tr>
                            </thead>
                            <tbody id="cbRecentEntries">
                                <tr class="cb-empty-row">
                                    <td colspan="4">لوڈنگ...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="cash-bank-status">
                    <span id="cbEntriesStatusText">ڈیٹا لوڈ ہو رہا ہے...</span>
                    <span id="cbEntriesMeta"></span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function initCashBank() {
    const $form = $('#cashBankForm');
    const $tableBody = $('#cbRecentEntries');
    const $scrollBox = $('#cbEntriesScroll');
    const $submitBtn = $form.find('button[type="submit"]');
    const $formTitle = $('.cash-bank-form-title');
    const accountBalances = {};
    const listState = {
        limit: 25,
        offset: 0,
        loading: false,
        hasMore: true,
        requestId: 0,
        filters: {
            from_date: '',
            to_date: '',
            item_id: ''
        }
    };

    $('#cbDate').val(new Date().toISOString().split('T')[0]);

    function setStatus(text, meta = '') {
        $('#cbEntriesStatusText').text(text || '');
        $('#cbEntriesMeta').text(meta || '');
    }

    function updateSummary(summary = {}, pagination = {}) {
        const totalRecords = parseInt(summary.total_records || 0, 10);
        const loadedTotal = parseInt(pagination.loaded_total || 0, 10);
        $('#cbOverallRecords').text(totalRecords.toLocaleString('en-PK'));
        $('#cbLoadedRecords').text(`${loadedTotal.toLocaleString('en-PK')} / ${totalRecords.toLocaleString('en-PK')}`);
        $('#cbOverallAmount').text(Utils.formatNumber(parseFloat(summary.total_amount || 0)));

        let rangeText = 'تمام تاریخیں';
        if (listState.filters.from_date && listState.filters.to_date) {
            rangeText = `${Utils.formatDate(listState.filters.from_date)} سے ${Utils.formatDate(listState.filters.to_date)}`;
        } else if (listState.filters.from_date) {
            rangeText = `${Utils.formatDate(listState.filters.from_date)} سے آگے`;
        } else if (listState.filters.to_date) {
            rangeText = `${Utils.formatDate(listState.filters.to_date)} تک`;
        } else if (summary.first_date && summary.last_date) {
            rangeText = `${Utils.formatDate(summary.first_date)} سے ${Utils.formatDate(summary.last_date)}`;
        }

        $('#cbSummaryRange').text(rangeText);
    }

    function getEntryVisual(entryType) {
        switch (entryType) {
            case 'receipt':
                return {
                    badge: '<span class="badge badge-success">وصولی</span>',
                    amountClass: 'text-success'
                };
            case 'transfer':
                return {
                    badge: '<span class="badge badge-info">منتقلی</span>',
                    amountClass: 'text-accent'
                };
            case 'direct_deposit':
                return {
                    badge: '<span class="badge badge-warning" style="background-color: #e67e22; color: white;">براہ راست جمع</span>',
                    amountClass: 'text-primary'
                };
            case 'debit_adj':
                return {
                    badge: '<span class="badge badge-warning" style="background-color: #e67e22; color: white;">نام ایڈجسٹمنٹ</span>',
                    amountClass: 'text-danger'
                };
            case 'credit_adj':
                return {
                    badge: '<span class="badge badge-info" style="background-color: #8e44ad; color: white;">جمع ایڈجسٹمنٹ</span>',
                    amountClass: 'text-success'
                };
            case 'commission_pay':
                return {
                    badge: '<span class="badge badge-info" style="background-color: #2980b9; color: white;">کمیشن ادائیگی</span>',
                    amountClass: 'text-danger'
                };
            case 'expense':
                return {
                    badge: '<span class="badge badge-warning" style="background-color: #e74c3c; color: white;">خرچہ</span>',
                    amountClass: 'text-danger'
                };
            default:
                return {
                    badge: '<span class="badge badge-danger">ادائیگی</span>',
                    amountClass: 'text-danger'
                };
        }
    }

    function renderCBEntries(entries, append = false) {
        if (!append) {
            $tableBody.empty();
        }

        if (!entries.length) {
            if (!append) {
                $tableBody.html('<tr class="cb-empty-row"><td colspan="4">کوئی اندراج نہیں ملی۔</td></tr>');
            }
            return;
        }

        const html = entries.map(v => {
            const visual = getEntryVisual(v.entry_type);
            const amount = parseFloat(v.total_amount || 0);
            const createdBy = v.created_by_name ? ` | ${v.created_by_name}` : '';

            return `
                <tr>
                    <td>${Utils.formatDate(v.journal_date)}</td>
                    <td>
                        <div class="fw-bold">${v.narration}</div>
                        <div class="mt-1">${visual.badge} <small class="text-muted">#${v.id}${createdBy}</small></div>
                    </td>
                    <td class="fw-bold cash-bank-amount ${visual.amountClass}">
                        ${Utils.formatNumber(amount)}
                    </td>
                    <td>
                        <button class="btn btn-outline btn-sm" onclick="reverseCB(${v.id})" title="ریورس کریں">
                            <i class="fas fa-trash-alt text-danger"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');

        if (append) {
            $tableBody.append(html);
        } else {
            $tableBody.html(html);
        }
    }

    async function ensureScrollableFill() {
        const el = $scrollBox[0];
        if (!el) return;

        if (!listState.loading && listState.hasMore && el.scrollHeight <= el.clientHeight + 20) {
            await loadRecentEntries();
        }
    }

    async function loadRecentEntries({ reset = false } = {}) {
        if (listState.loading) return;
        if (!reset && !listState.hasMore) return;

        if (reset) {
            listState.offset = 0;
            listState.hasMore = true;
            $scrollBox.scrollTop(0);
            $tableBody.html('<tr class="cb-empty-row"><td colspan="4">لوڈنگ...</td></tr>');
        }

        listState.loading = true;
        const currentRequestId = ++listState.requestId;
        setStatus(reset ? 'اندراجات لوڈ ہو رہی ہیں...' : 'مزید اندراجات لوڈ ہو رہی ہیں...');

        const params = {
            limit: listState.limit,
            offset: listState.offset
        };

        if (listState.filters.from_date) {
            params.from_date = listState.filters.from_date;
        }
        if (listState.filters.to_date) {
            params.to_date = listState.filters.to_date;
        }
        if (listState.filters.item_id) {
            params.item_id = listState.filters.item_id;
        }

        try {
            const res = await API.get('/cash-bank', params);
            if (currentRequestId !== listState.requestId) return;

            const payload = res.data || {};
            const items = payload.items || [];
            const summary = payload.summary || {};
            const pagination = payload.pagination || {};

            const totalRecords = parseInt(summary.total_records || 0, 10);
            renderCBEntries(items, !reset);
            listState.offset = parseInt(pagination.loaded_total || (listState.offset + items.length), 10);
            listState.hasMore = !!pagination.has_more;
            updateSummary(summary, pagination);
            updateDashboardStats(payload.stats || {});

            if (totalRecords === 0) {
                setStatus('اس فلٹر میں کوئی اندراج موجود نہیں ہے.');
            } else if (listState.hasMore) {
                setStatus('مزید اندراجات کے لیے نیچے اسکرول کریں۔', `لوڈ شدہ: ${listState.offset.toLocaleString('en-PK')} / ${totalRecords.toLocaleString('en-PK')}`);
            } else {
                setStatus('تمام اندراجات لوڈ ہو گئی ہیں۔', `کل اندراجات: ${totalRecords.toLocaleString('en-PK')}`);
            }
        } catch (err) {
            if (reset) {
                $tableBody.html('<tr class="cb-empty-row"><td colspan="4">ڈیٹا لوڈ کرنے میں خرابی ہوئی۔</td></tr>');
            }
            setStatus('ڈیٹا لوڈ کرنے میں خرابی ہوئی۔');
        } finally {
            if (currentRequestId === listState.requestId) {
                listState.loading = false;
                setTimeout(() => {
                    ensureScrollableFill();
                }, 0);
            }
        }
    }

    function updateDashboardStats(stats = {}) {
        // Update Total Sale
        const totalSale = parseFloat(stats.total_sale || 0);
        $('#cbDashboardTotalSale').text(Utils.formatNumber(totalSale));

        // Update Total Purchase
        const totalPurchase = parseFloat(stats.total_purchase || 0);
        $('#cbDashboardTotalPurchase').text(Utils.formatNumber(totalPurchase));

        // Update Total Expense
        const totalExpense = parseFloat(stats.total_expense || 0);
        $('#cbDashboardTotalExpense').text(Utils.formatNumber(totalExpense));

        // Update Bank balances
        const banks = stats.banks || [];
        const $banksList = $('#cbDashboardBanksList');
        $banksList.empty();

        banks.forEach(b => {
            const balance = parseFloat(b.balance || 0);
            const formattedBal = Utils.formatNumber(balance);
            const colorClass = balance >= 0 ? 'text-success' : 'text-danger';
            const itemHtml = `
                <div class="cb-bank-list-item">
                    <span style="font-weight: 500;">${b.name} (${b.sub_type === 'cash' ? 'کیش' : 'بینک'}):</span>
                    <span class="fw-bold ${colorClass}">${formattedBal} روپے</span>
                </div>
            `;
            $banksList.append(itemHtml);
        });

        // Update Grand Total
        const totalCashBank = parseFloat(stats.total_cash_bank || 0);
        const totalColorClass = totalCashBank >= 0 ? 'text-success' : 'text-danger';
        $('#cbDashboardBanksTotal').text(`${Utils.formatNumber(totalCashBank)} روپے`).removeClass('text-success text-danger').addClass(totalColorClass);
    }

    async function fetchBalance(accountId, targetId) {
        if (!accountId) {
            $(`#bal_${targetId}`).text('');
            delete accountBalances[targetId];
            return;
        }

        try {
            $(`#bal_${targetId}`).html('<i class="fas fa-spinner fa-spin"></i> لوڈنگ...');
            const res = await API.get(`/ledger/${accountId}/balance`);
            const balance = parseFloat(res.data.balance);
            accountBalances[targetId] = balance;

            const label = 'موجودہ بیلنس: ';
            const colorClass = balance >= 0 ? 'text-success' : 'text-danger';
            const amountStr = `${Utils.formatNumber(Math.abs(balance))} روپے`;
            const typeStr = balance >= 0 ? ' (Dr)' : ' (Cr)';

            $(`#bal_${targetId}`).html(`${label}<span class="${colorClass}">${amountStr}${typeStr}</span>`);
        } catch (err) {
            $(`#bal_${targetId}`).text('بیلنس لوڈ نہیں ہو سکا۔');
        }
    }

    try {
        const [allAccountsRes, itemsRes] = await Promise.all([
            API.get('/accounts', { exclude_equity: 1 }),
            API.get('/items')
        ]);

        Utils.populateSelect('cbParty', allAccountsRes.data, 'پارٹی منتخب کریں...');
        Utils.populateSelect('cbItem', itemsRes.data, 'جنس منتخب کریں...');
        Utils.populateSelect('cbFilterItem', itemsRes.data, 'تمام اجناس...');
        $('#cbFilterItem').select2({ placeholder: 'تمام اجناس...', allowClear: true, dir: 'rtl', width: '100%' });

        const populateAcc = (id, includeCapital = false, onlyDirectDeposit = false) => {
            const $acc = $(id);
            const currentVal = $acc.val();
            $acc.empty().append('<option value=""></option>');
            allAccountsRes.data.forEach(a => {
                const isCapital = a.name.includes('capital (سرمایہ)');
                if (!includeCapital && isCapital) return;
                if (onlyDirectDeposit && parseInt(a.allow_direct_deposit, 10) !== 1) return;
                $acc.append(new Option(`${a.name} (${a.sub_type})`, a.id));
            });
            $acc.val(currentVal).trigger('change.select2');
            $acc.select2({ placeholder: 'اکاؤنٹ منتخب کریں...', allowClear: true, dir: 'rtl', width: '100%' });
        };

        populateAcc('#cbAccount', false);
        populateAcc('#cbFromAccount', true);
        populateAcc('#cbToAccount', true);

        $('#cbParty').on('change', function() { fetchBalance($(this).val(), 'cbParty'); });
        $('#cbAccount').on('change', function() { fetchBalance($(this).val(), 'cbAccount'); });
        $('#cbFromAccount').on('change', function() { fetchBalance($(this).val(), 'cbFromAccount'); });
        $('#cbToAccount').on('change', function() { fetchBalance($(this).val(), 'cbToAccount'); });

        $('#cbTypeToggle .toggle-btn').on('click', function() {
            const value = $(this).data('value');
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
            $('#cbType').val(value);

            $('#bal_cbParty, #bal_cbAccount, #bal_cbFromAccount, #bal_cbToAccount').text('');
            $('#cbItemGroup').hide(); // Default hide item selection

            if (value === 'direct_deposit') {
                $('#cbModeNormal').show();
                $('#cbParty').closest('.form-group').hide();
                $('#cbAccount').closest('.form-group').show();
                $('#cbModeTransfer').hide();
                $formTitle.text('براہ راست بینک جمع (Direct Deposit)');
                populateAcc('#cbAccount', false, true);
            } else if (value === 'transfer') {
                $('#cbModeNormal').hide();
                $('#cbModeTransfer').show();
                $formTitle.text('کھاتہ سے کھاتہ منتقli (Contra Entry)');
                populateAcc('#cbFromAccount', true);
                populateAcc('#cbToAccount', true);
            } else if (value === 'expense') {
                $('#cbModeNormal').show();
                $('#cbParty').closest('.form-group').hide();
                $('#cbItemGroup').show(); // Show Item selection
                $('#cbAccount').closest('.form-group').show();
                $('#cbModeTransfer').hide();
                $formTitle.text('خرچہ اندراج (System Expense)');
                populateAcc('#cbAccount', false);
            } else if (value === 'debit_adj' || value === 'credit_adj') {
                $('#cbParty').closest('.form-group').show();
                $('#cbModeNormal').show();
                $('#cbAccount').closest('.form-group').hide();
                $('#cbModeTransfer').hide();
                $formTitle.text(value === 'debit_adj' ? 'نام کھاتہ ایڈجسٹمنٹ (Debit Adjustment)' : 'جمع کھاتہ ایڈجسٹمنٹ (Credit Adjustment)');
            } else if (value === 'commission_pay') {
                $('#cbParty').closest('.form-group').show();
                $('#cbItemGroup').show(); // Show item selection for commission
                $('#cbModeNormal').show();
                $('#cbAccount').closest('.form-group').show();
                $('#cbModeTransfer').hide();
                $formTitle.text('کمیشن ادائیگی واؤچر (Commission Payment)');
                populateAcc('#cbAccount', false);
            } else {
                $('#cbParty').closest('.form-group').show();
                $('#cbModeNormal').show();
                $('#cbAccount').closest('.form-group').show();
                $('#cbModeTransfer').hide();
                $formTitle.text('نقد وصولی / ادائیگی (Naqad/Bank)');
                populateAcc('#cbAccount', false);
            }
        });
    } catch (err) {
        Toast.danger('ڈیٹا لوڈ کرنے میں غلطی آئی۔');
    }

    function applyFilters(resetInputs = false) {
        if (resetInputs) {
            $('#cbFilterFromDate').val('');
            $('#cbFilterToDate').val('');
            $('#cbFilterItem').val('').trigger('change.select2');
        }

        const fromDate = $('#cbFilterFromDate').val();
        const toDate = $('#cbFilterToDate').val();
        const itemId = $('#cbFilterItem').val() || '';

        if (fromDate && toDate && fromDate > toDate) {
            Toast.warning('شروع کی تاریخ اختتامی تاریخ سے بڑی نہیں ہو سکتی۔');
            return;
        }

        listState.filters.from_date = fromDate;
        listState.filters.to_date = toDate;
        listState.filters.item_id = itemId;
        loadRecentEntries({ reset: true });
    }

    $('#cbApplyFilter').on('click', function() {
        applyFilters(false);
    });

    $('#cbResetFilter').on('click', function() {
        applyFilters(true);
    });

    $('#cbFilterFromDate, #cbFilterToDate, #cbFilterItem').on('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            applyFilters(false);
        }
    });

    $scrollBox.on('scroll', function() {
        const el = this;
        if (listState.loading || !listState.hasMore) return;
        if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120) {
            loadRecentEntries();
        }
    });

    window.reverseCB = async function(id) {
        if (!confirm('کیا آپ واقعی اس واؤچر کو ریورس کرنا چاہتے ہیں؟')) return;
        try {
            const res = await API.post(`/cash-bank/${id}/reverse`);
            if (res.success) {
                Toast.success('واؤچر ریورس ہو گیا۔');
                loadRecentEntries({ reset: true });
            }
        } catch (err) {}
    };

    $form.on('submit', async function(e) {
        e.preventDefault();

        const type = $('#cbType').val();
        const amount = parseFloat($('#cbAmount').val());
        const payload = {
            date: $('#cbDate').val(),
            amount: amount,
            type: type,
            narration: $('#cbDetail').val()
        };

        if (type === 'transfer') {
            payload.from_account_id = parseInt($('#cbFromAccount').val(), 10);
            payload.to_account_id = parseInt($('#cbToAccount').val(), 10);

            if (!payload.from_account_id || !payload.to_account_id) {
                Toast.warning('براہ کرم دونوں اکاؤنٹس منتخب کریں۔');
                return;
            }

            const fromBalance = accountBalances.cbFromAccount || 0;
            if (amount > fromBalance) {
                Toast.danger(`Insufficient Balance! آپ کے پاس صرف ${Utils.formatNumber(fromBalance)} روپے موجود ہیں۔`);
                return;
            }
        } else if (type === 'direct_deposit') {
            payload.account_id = parseInt($('#cbAccount').val(), 10);
            if (!payload.account_id) {
                Toast.warning('براہ کرم اکاؤنٹ منتخب کریں۔');
                return;
            }
        } else if (type === 'debit_adj' || type === 'credit_adj') {
            payload.party_id = parseInt($('#cbParty').val(), 10);
            if (!payload.party_id) {
                Toast.warning('براہ کرم پارٹی منتخب کریں۔');
                return;
            }
        } else if (type === 'commission_pay') {
            payload.party_id = parseInt($('#cbParty').val(), 10);
            payload.account_id = parseInt($('#cbAccount').val(), 10);
            payload.item_id = parseInt($('#cbItem').val(), 10);
            if (!payload.party_id || !payload.account_id || !payload.item_id) {
                Toast.warning('براہ کرم پارٹی، اکاؤنٹ اور جنس منتخب کریں۔');
                return;
            }
        } else if (type === 'expense') {
            payload.account_id = parseInt($('#cbAccount').val(), 10);
            payload.item_id = parseInt($('#cbItem').val(), 10) || null;
            if (!payload.account_id) {
                Toast.warning('براہ کرم اکاؤنٹ منتخب کریں۔');
                return;
            }
        } else {
            payload.party_id = parseInt($('#cbParty').val(), 10);
            payload.account_id = parseInt($('#cbAccount').val(), 10);
            if (!payload.party_id || !payload.account_id) {
                Toast.warning('براہ کرم پارٹی اور اکاؤنٹ منتخب کریں۔');
                return;
            }
        }

        if ((type === 'payment' || type === 'commission_pay' || type === 'expense') && payload.account_id && amount > (accountBalances.cbAccount || 0)) {
            const accountBalance = accountBalances.cbAccount || 0;
            Toast.danger(`Insufficient Balance! آپ کے پاس صرف ${Utils.formatNumber(accountBalance)} روپے موجود ہیں۔`);
            return;
        }

        if (!payload.amount) {
            Toast.warning('براہ کرم رقم درج کریں۔');
            return;
        }

        $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> محفوظ ہو رہا ہے...');

        try {
            const res = await API.post('/cash-bank', payload);
            if (res.success) {
                Toast.success('واؤچر کامیابی سے محفوظ ہو گیا ہے۔');
                $form[0].reset();
                $('#cbDate').val(Utils.getISODate());
                $('#cbParty, #cbAccount, #cbFromAccount, #cbToAccount, #cbItem').val(null).trigger('change');
                $('.toggle-btn[data-value="payment"]').click();
                loadRecentEntries({ reset: true });
            }
        } catch (err) {
        } finally {
            $submitBtn.prop('disabled', false).html('<i class="fas fa-save"></i> واؤچر محفوظ کریں');
        }
    });

    $('#cbDate').val(Utils.getISODate());
    loadRecentEntries({ reset: true });
    Utils.setupEnterNavigation('#cashBankForm');
}
</script>