/* All Balances Report Controller */

async function initAllBalances() {
    const $tableBody = $('#balancesTableBody');
    const $search = $('#balanceSearch');
    const $btnReset = $('#btnResetFilters');

    let accountsList = [];

    // Type mapping to Urdu display names
    const typeUrduMap = {
        'zamidar': 'زمیندار',
        'khareedar': 'خریدار',
        'driver': 'ڈرائیور',
        'broker': 'بروکر',
        'employee': 'ملازم'
    };

    // Load Data from Backend
    async function loadData() {
        try {
            $tableBody.html('<tr><td colspan="6" class="text-center"><i class="fas fa-spinner fa-spin"></i> ڈیٹا لوڈ ہو رہا ہے...</td></tr>');
            const res = await API.get('/accounts', { include_balance: 1 });
            
            // Filter only parties and banks
            accountsList = res.data.filter(acc => acc.type === 'party' || acc.type === 'bank_cash');
            
            // Calculate running balance for each account
            accountsList.forEach(acc => {
                let opening = parseFloat(acc.opening_balance) || 0;
                if (acc.balance_type === 'Cr') {
                    opening = -opening;
                }
                acc.calculated_balance = opening + (parseFloat(acc.total_dr) || 0) - (parseFloat(acc.total_cr) || 0);
            });

            renderTable();
        } catch (err) {
            console.error(err);
            $tableBody.html('<tr><td colspan="6" class="text-center text-danger">ڈیٹا لوڈ کرنے میں غلطی آئی۔</td></tr>');
        }
    }

    // Render Table based on current filters
    function renderTable() {
        const query = ($search.val() || '').trim().toLowerCase();

        // Apply filters
        const filtered = accountsList.filter(acc => {
            // 1. Text Search (name, phone, city)
            const nameMatch = acc.name.toLowerCase().includes(query);
            const phoneMatch = (acc.phone || '').toLowerCase().includes(query);
            const cityMatch = (acc.city || '').toLowerCase().includes(query);
            if (query && !nameMatch && !phoneMatch && !cityMatch) return false;

            return true;
        });

        // Populate Table
        if (filtered.length === 0) {
            $tableBody.html('<tr><td colspan="5" class="text-center">کوئی ریکارڈ نہیں ملا۔</td></tr>');
            $('#totalBalance').text('0.00');
            return;
        }

        let html = '';
        let totalBalanceSum = 0;

        filtered.forEach(acc => {
            const bal = acc.calculated_balance;
            let displayType = '';

            if (acc.type === 'bank_cash') {
                displayType = '<span class="badge badge-success">بینک / کیش</span>';
            } else {
                const urduType = typeUrduMap[acc.sub_type] || acc.sub_type;
                displayType = `<span class="badge ${acc.sub_type === 'zamidar' ? 'badge-info' : 'badge-accent'}">${urduType}</span>`;
            }

            const phoneStr = acc.phone ? acc.phone : '';
            const cityStr = acc.city ? acc.city : '';
            let contactInfo = '-';
            if (phoneStr && cityStr) {
                contactInfo = `${phoneStr} | ${cityStr}`;
            } else if (phoneStr || cityStr) {
                contactInfo = phoneStr || cityStr;
            }

            const absBal = Math.abs(bal);
            totalBalanceSum += absBal;

            // Optional styling: Red text for debit (receivable/customer), Green for credit (payable/bank/cash)
            const colorClass = bal > 0.005 ? 'text-danger' : (bal < -0.005 ? 'text-success' : '');
            const balanceCell = `<span class="${colorClass} fw-bold"><bdi>${Utils.formatNumber(absBal)}</bdi></span>`;

            html += `
                <tr>
                    <td>
                        <a href="#ledger?id=${acc.id}" class="text-primary fw-bold fs-5">${acc.name}</a>
                    </td>
                    <td>${displayType}</td>
                    <td><bdi>${contactInfo}</bdi></td>
                    <td>${balanceCell}</td>
                    <td class="no-print">
                        <a href="#ledger?id=${acc.id}" class="btn btn-outline btn-sm">
                            <i class="fas fa-book"></i> لیجر دیکھیں
                        </a>
                    </td>
                </tr>
            `;
        });

        $tableBody.html(html);

        // Update Footers
        $('#totalBalance').text(Utils.formatNumber(totalBalanceSum));
    }

    // Event Bindings
    $search.on('input', renderTable);

    $btnReset.on('click', function() {
        $search.val('');
        renderTable();
        Toast.success("فلٹرز صاف کر دیے گئے ہیں۔");
    });

    // Load PDF Functionality
    async function loadHtml2Pdf() {
        if (typeof html2pdf !== 'undefined') return true;
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';
            script.onload = () => resolve(true);
            script.onerror = () => reject(new Error('html2pdf failed to load'));
            document.head.appendChild(script);
        });
    }

    $('#btnDownloadPDF').on('click', async function() {
        const filename = `All_Balances_Report_${Utils.getISODate()}.pdf`;
        const $btn = $(this);
        $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> لوڈنگ...');

        try {
            await loadHtml2Pdf();
            
            const $printArea = $('.print-ledger');
            $printArea.addClass('generating-pdf');

            const opt = {
                margin:       10,
                filename:     filename,
                image:        { type: 'jpeg', quality: 0.98 },
                html2canvas:  { scale: 2, useCORS: true, letterRendering: true },
                jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
            };

            await html2pdf().set(opt).from($printArea[0]).save();
            Toast.success("پی ڈی ایف رپورٹ ڈاؤن لوڈ ہو گئی ہے۔");
        } catch (err) {
            console.error(err);
            Toast.danger("پی ڈی ایف ڈاؤن لوڈ کرنے میں غلطی آئی۔");
        } finally {
            $('.print-ledger').removeClass('generating-pdf');
            $btn.prop('disabled', false).html('<i class="fas fa-file-pdf"></i> پی ڈی ایف (PDF)');
        }
    });

    // Start load
    await loadData();
}
