<div class="expense-container">
    <div class="form-grid-2">
        <!-- Input Form -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">روزمرہ اخراجات (Petty Cash/Expenses)</h3>
            </div>
            <div class="card-body">
                <form id="expenseForm">
                    <div class="form-group">
                        <label class="form-label">تاریخ (Date)</label>
                        <input type="date" id="exDate" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">خرچے کی تفصیل (Detail)</label>
                        <input type="text" id="exDetail" class="form-control" required placeholder="مثلاً: چائے Munshi، بجلی بل، مزدوری...">
                    </div>

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

                    <div class="form-group">
                        <label class="form-label">جنس / Item (اختیاری)</label>
                        <select id="exItem" class="form-control"></select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">اکاؤنٹ (کیش / بینک)</label>
                        <select id="exAccount" class="form-control" required></select>
                        <div class="mt-1"><small class="text-muted" id="bal_exAccount"></small></div>
                    </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>

        <!-- Recent Expenses -->
        <div class="card">
            <div class="card-header d-flex justify-between align-center" style="flex-wrap: wrap; gap: 10px;">
                <h3 class="card-title">اخراجات کی فہرست</h3>
                <div class="d-flex align-center gap-2" style="flex-wrap: wrap;">
                    <label class="form-label m-0">تاریخ:</label>
                    <label class="form-label m-0">ØªØ§Ø±ÛŒØ® Ø³Û’:</label>
                    <input type="date" id="exFilterFromDate" class="form-control form-control-sm w-auto">
                    <label class="form-label m-0">ØªØ§Ø±ÛŒØ® ØªÚ©:</label>
                    <input type="date" id="exFilterToDate" class="form-control form-control-sm w-auto">
                    <label class="form-label m-0">Ø¬Ù†Ø³:</label>
                    <select id="exFilterItem" class="form-control form-control-sm" style="min-width: 180px;"></select>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table m-0">
                        <thead>
                            <tr>
                                <th>تاریخ</th>
                                <th>تفصیل</th>
                                <th>رقم</th>
                                <th class="text-center" style="width:80px;">عمل</th>
                            </tr>
                        </thead>
                        <tbody id="exRecentSummary">
                            <!-- Populated via initExpense -->
                        </tbody>
                        <tfoot>
                            <tr style="background: var(--card-bg-alt); font-weight: 800;">
                                <td colspan="2" class="text-right">کل خرچہ:</td>
                                <td id="exTotalAmount" colspan="2">0.00</td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function initExpense() {
    const $form = $('#expenseForm');
    const $tableBody = $('#exRecentSummary');
    const $submitBtn = $form.find('button[type="submit"]');
    const accountBalances = {};
    let editId = null;
    let originalAccountId = null;
    let originalAmount = 0;

    // 1. Initial State
    const today = Utils.getISODate();
    $('#exDate').val(today);
    $('#exFilterFromDate').val(today);
    $('#exFilterToDate').val(today);

    const $filterHeader = $('#exFilterFromDate').closest('div.d-flex');
    const $filterLabels = $filterHeader.find('label.form-label.m-0');
    if ($filterLabels.length >= 4) {
        $filterLabels.eq(0).remove();
        $filterLabels.eq(1).html('&#1578;&#1575;&#1585;&#1740;&#1582; &#1587;&#1746;:');
        $filterLabels.eq(2).html('&#1578;&#1575;&#1585;&#1740;&#1582; &#1578;&#1705;:');
        $filterLabels.eq(3).html('&#1580;&#1606;&#1587;:');
    }

    async function fetchBalance(accountId) {
        if (!accountId) {
            $('#bal_exAccount').text('');
            delete accountBalances.exAccount;
            return;
        }

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

            const colorClass = balance >= 0 ? 'text-success' : 'text-danger';
            const typeStr = balance >= 0 ? ' (Dr)' : ' (Cr)';
            $('#bal_exAccount').html(`موجودہ بیلنس: <span class="${colorClass}">${Utils.formatNumber(Math.abs(balance))} روپے${typeStr}</span>`);
        } catch (err) {
            $('#bal_exAccount').text('بیلنس لوڈ نہیں ہو سکا۔');
        }
    }

    // 2. Load Data
    try {
        const accountsRes = await API.get('/accounts', { type: 'bank_cash', exclude_capital: 1 });
        
        const $acc = $('#exAccount');
        $acc.empty().append('<option value=""></option>');
        accountsRes.data.forEach(a => {
            $acc.append(new Option(`${a.name} (${a.sub_type})`, a.id));
        });
        $acc.select2({ placeholder: "کیش / بینک اکاؤنٹ...", allowClear: true, dir: "rtl", width: '100%' });

        $acc.on('change', function() {
            fetchBalance($(this).val());
        });

        const itemsRes = await API.get('/items');
        const $item = $('#exItem');
        const $filterItem = $('#exFilterItem');
        $item.empty().append('<option value=""></option>');
        $filterItem.empty().append('<option value=""></option>');
        itemsRes.data.forEach(i => {
            $item.append(new Option(i.name, i.id));
            $filterItem.append(new Option(i.name, i.id));
        });
        $item.select2({ placeholder: "کسی جنس کا خرچہ ہے تو منتخب کریں...", allowClear: true, dir: "rtl", width: '100%' });
        $filterItem.select2({ placeholder: "Filter by item...", allowClear: true, dir: "rtl", width: '100%' });

    } catch (err) {
        Toast.danger("اکاؤنٹس یا جنس لوڈ کرنے میں غلطی آئی۔");
    }

    // 3. Load Recent Expenses
    async function loadRecentExpenses() {
        try {
            $tableBody.html('<tr><td colspan="4" class="text-center">لوڈنگ...</td></tr>');
            const params = {
                from_date: $('#exFilterFromDate').val(),
                to_date: $('#exFilterToDate').val()
            };
            if ($('#exFilterItem').val()) {
                params.item_id = parseInt($('#exFilterItem').val());
            }
            const res = await API.get('/expenses', params);
            renderExEntries(res.data.expenses || []);
        } catch (err) {
            $tableBody.html('<tr><td colspan="4" class="text-center error">ڈیٹا لوڈ کرنے میں غلطی ہوئی۔</td></tr>');
        }
    }

    function renderExEntries(entries) {
        let html = '';
        let total = 0;
        if (entries.length === 0) {
            $tableBody.html('<tr><td colspan="4" class="text-center">اس تاریخ کا کوئی خرچہ ریکارڈ نہیں ہے۔</td></tr>');
            $('#exTotalAmount').text('0.00');
            return;
        }

        entries.forEach(e => {
            const amt = parseFloat(e.total_amount);
            const itemBadge = e.item_name ? ` <span class="badge bg-secondary" style="font-size: 0.8em; margin-right: 5px;">${e.item_name}</span>` : '';
            const rawData = encodeURIComponent(JSON.stringify(e));
            
            html += `
                <tr>
                    <td>${Utils.formatDate(e.journal_date)}</td>
                    <td><span class="fw-bold">${e.narration}</span>${itemBadge}</td>
                    <td class="text-danger fw-bold">${Utils.formatNumber(amt)}</td>
                    <td class="text-center">
                        <div style="display: flex; gap: 5px; justify-content: center;">
                            <button type="button" class="btn btn-icon btn-sm" style="color: var(--primary);" onclick="editExpense('${rawData}')" title="ترمیم کریں">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button type="button" class="btn btn-icon btn-sm" style="color: var(--danger);" onclick="deleteExpense(${e.id})" title="ڈیلیٹ کریں">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
            total += amt;
        });
        $tableBody.html(html);
        $('#exTotalAmount').text(Utils.formatNumber(total));
    }

    // Edit functionality globally available for onclick
    window.editExpense = function(encodedData) {
        const e = JSON.parse(decodeURIComponent(encodedData));
        editId = e.id;
        $('#exDate').val(e.journal_date);
        
        // Strip 'تصحیح خرچہ: ' or 'خرچہ: ' prefix if present to avoid double prefixes
        let detail = e.narration;
        if(detail.startsWith('خرچہ: ')) detail = detail.substring(6);
        if(detail.startsWith('تصحیح خرچہ: ')) detail = detail.substring(12);
        $('#exDetail').val(detail);
        
        $('#exAmount').val(e.total_amount);
        $('#exAccount').val(e.account_id).trigger('change');
        $('#exItem').val(e.item_id).trigger('change');
        originalAccountId = parseInt(e.account_id) || null;
        originalAmount = parseFloat(e.total_amount) || 0;
        
        $submitBtn.html('<i class="fas fa-edit"></i> خرچہ اپڈیٹ کریں');
        $submitBtn.removeClass('btn-primary').addClass('btn-warning');
        
        // Scroll to form
        document.querySelector('.expense-container').scrollIntoView({ behavior: 'smooth' });
    };

    window.deleteExpense = async function(id) {
        if (!confirm('کیا آپ واقعی یہ خرچہ حذف کرنا چاہتے ہیں؟')) return;
        try {
            await API.delete('/expenses/' + id);
            Toast.success('خرچہ حذف ہو گیا۔');
            loadRecentExpenses();
        } catch (err) {}
    };

    function resetForm() {
        editId = null;
        originalAccountId = null;
        originalAmount = 0;
        $form[0].reset();
        $('#exDate').val(today);
        $('#exAccount').val(null).trigger('change');
        $('#exItem').val(null).trigger('change');
        $submitBtn.html('<i class="fas fa-save"></i> خرچہ محفوظ کریں');
        $submitBtn.removeClass('btn-warning').addClass('btn-primary');
    }

    // 4. Form Submission
    $form.on('submit', async function(e) {
        e.preventDefault();
        
        const payload = {
            date: $('#exDate').val(),
            narration: $('#exDetail').val(),
            amount: parseFloat($('#exAmount').val()),
            account_id: parseInt($('#exAccount').val()),
            item_id: $('#exItem').val() ? parseInt($('#exItem').val()) : null
        };

        let availableBalance = accountBalances.exAccount;
        if (payload.amount && payload.account_id && typeof availableBalance !== 'number') {
            try {
                const balRes = await API.get(`/ledger/${payload.account_id}/balance`);
                availableBalance = parseFloat(balRes.data.balance);
                accountBalances.exAccount = availableBalance;
            } catch (err) {
                Toast.warning("اکاؤنٹ بیلنس چیک نہیں ہو سکا، دوبارہ کوشش کریں۔");
                return;
            }
        }

        if (editId && originalAccountId === payload.account_id) {
            availableBalance += originalAmount;
        }

        if (payload.amount && payload.account_id && payload.amount > availableBalance) {
            Toast.danger(`⚠️ Insufficient Balance! دستیاب رقم ${Utils.formatNumber(availableBalance)} روپے ہے۔`);
            return;
        }

        if (!payload.narration || !payload.amount || !payload.account_id) {
            Toast.warning("براہ کرم تمام معلومات مکمل طور پر درج کریں۔");
            return;
        }

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

        try {
            let res;
            if (editId) {
                res = await API.put('/expenses/' + editId, payload);
            } else {
                res = await API.post('/expenses', payload);
            }
            
            if (res.success) {
                Toast.success(editId ? "✅ خرچہ کامیابی سے اپڈیٹ ہو گیا ہے۔" : "✅ خرچہ کامیابی سے محفوظ ہو گیا ہے۔");
                resetForm();
                loadRecentExpenses();
            }
        } catch (err) {
        } finally {
            $submitBtn.prop('disabled', false).html(editId ? '<i class="fas fa-edit"></i> خرچہ اپڈیٹ کریں' : '<i class="fas fa-save"></i> خرچہ محفوظ کریں');
        }
    });

    // 5. Change List Filters
    $('#exFilterFromDate, #exFilterToDate').on('change', function() {
        loadRecentExpenses();
    });

    $('#exFilterItem').on('change', function() {
        loadRecentExpenses();
    });

    loadRecentExpenses();
    Utils.setupEnterNavigation('#expenseForm');
}
</script>
