<div class="ledger-container">
    <div class="card no-print">
        <div class="card-header">
            <h3 class="card-title">کھاتہ فلٹرز (Filters)</h3>
        </div>
        <div class="card-body">
            <div class="form-grid-4">
                <div class="form-group">
                    <label class="form-label">پارٹی منتخب کریں</label>
                    <select id="ledgerPartySelect" class="form-control select2"></select>
                </div>
                <div class="form-group">
                    <label class="form-label">تاریخ سے</label>
                    <input type="date" id="ledgerDateFrom" class="form-control" value="2026-03-01">
                </div>
                <div class="form-group">
                    <label class="form-label">تاریخ تک</label>
                    <input type="date" id="ledgerDateTo" class="form-control" value="2026-03-31">
                </div>
                <div class="form-group" style="align-self: end;">
                    <button type="button" class="btn btn-primary w-100" id="btnShowLedger">
                        <i class="fas fa-search"></i> کھاتہ دکھائیں
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Ledger Report Area -->
    <div class="card print-ledger">
        <div class="card-header d-flex justify-between">
            <h3 class="card-title" id="ledgerPartyName">مکمل کھاتہ تفصیل</h3>
            <div class="d-flex gap-2 no-print">
                <button type="button" class="btn btn-outline btn-sm" id="btnDownloadPDF">
                    <i class="fas fa-file-pdf"></i> پی ڈی ایف ڈاؤن لوڈ (PDF)
                </button>
                <button type="button" class="btn btn-outline btn-sm" onclick="window.print()">
                    <i class="fas fa-print"></i> رپورٹ پرنٹ کریں (A4)
                </button>
            </div>
        </div>
        <div class="card-body p-0">
            <!-- Branding for print -->
            <div class="print-branding print-only">
                <h1>بابا نوید ٹریڈرز اینڈ کمیشن ایجنٹ</h1>
                <p>غلہ منڈی، اوکاڑہ | فون: 0300-1234567</p>
                <h2 style="margin-top: 10px; border-top: 1px solid #000; padding-top: 5px;">پارٹی لیجر رپورٹ</h2>
            </div>

            <div class="table-responsive">
                <table class="table m-0">
                    <thead>
                        <tr>
                            <th>تاریخ</th>
                            <th>تفصیل / اندراج</th>
                            <th>نام (Dr)</th>
                            <th>جمع (Cr)</th>
                            <th>باقیہ (Balance)</th>
                        </tr>
                    </thead>
                    <tbody id="ledgerTableBody">
                        <!-- Populated via initLedger -->
                    </tbody>
                    <tfoot>
                        <tr style="background: var(--card-bg-alt); font-weight: 800;">
                            <td colspan="2" class="text-right">ٹوٹل:</td>
                            <td><span id="totalDebit">0.00</span></td>
                            <td><span id="totalCredit">0.00</span></td>
                            <td><span id="finalBalance">0.00</span></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Signature for print -->
            <div class="print-footer print-only">
                <div class="signature-line">پارٹی کے دستخط</div>
                <div class="signature-line">منشی / کیشیئر</div>
            </div>
        </div>
    </div>
</div>

<style>
/* PDF Generation Styles */
.generating-pdf,
.generating-pdf * {
    font-family: 'Segoe UI', Tahoma, Arial, sans-serif !important;
}
.generating-pdf {
    background-color: #fff !important;
    color: #000 !important;
    padding: 20px !important;
    direction: rtl !important;
}
.generating-pdf .print-only {
    display: block !important;
}
.generating-pdf .no-print {
    display: none !important;
}
.generating-pdf .card {
    border: none !important;
    box-shadow: none !important;
    margin: 0 !important;
}
.generating-pdf .table {
    border: 1px solid #000 !important;
    width: 100% !important;
}
.generating-pdf .table th, .generating-pdf .table td {
    border: 1px solid #000 !important;
    padding: 8px 10px !important;
    color: #000 !important;
    font-size: 10pt !important;
    word-wrap: normal !important;
    letter-spacing: normal !important;
    word-spacing: normal !important;
}
.generating-pdf .table th {
    background-color: #f1f1f1 !important;
}
.generating-pdf .table td:nth-child(1),
.generating-pdf .table td:nth-child(3),
.generating-pdf .table td:nth-child(4),
.generating-pdf .table td:nth-child(5) {
    white-space: nowrap !important;
}
</style>

<script>
async function initLedger(params) {
    const $partySelect = $('#ledgerPartySelect');
    const $tableBody = $('#ledgerTableBody');
    const $btnShow = $('#btnShowLedger');

    // 1. Set default dates (Current Month)
    const todayStr = Utils.getISODate();
    const parts = todayStr.split('-');
    const firstDayStr = `${parts[0]}-${parts[1]}-01`;
    $('#ledgerDateFrom').val(firstDayStr);
    $('#ledgerDateTo').val(todayStr);

    // 2. Load Parties/Accounts
    try {
        const res = await API.get('/accounts', { exclude_equity: 1 }); // Get accounts excluding Original Capital
        MandiData.accounts = res.data;
        Utils.populateSelect('ledgerPartySelect', MandiData.accounts, 'کھاتہ منتخب کریں...');
        
        // Auto-select party if ID is passed in params
        if (params && params.id) {
            $partySelect.val(params.id).trigger('change');
            setTimeout(() => {
                $btnShow.click();
            }, 100);
        }
    } catch (err) {
        Toast.danger("اکاؤنٹس لوڈ کرنے میں غلطی آئی۔");
    }

    // 3. Show Ledger Action
    $btnShow.on('click', async function() {
        const accId = $partySelect.val();
        const from = $('#ledgerDateFrom').val();
        const to = $('#ledgerDateTo').val();

        if (!accId) {
            Toast.warning("براہ کرم پہلے کوئی کھاتہ منتخب کریں۔");
            return;
        }

        const account = MandiData.accounts.find(a => a.id == accId);
        $('#ledgerPartyName').text(`کھاتہ: ${account.name} (${account.type === 'party' ? account.sub_type : 'سسٹم اکاؤنٹ'})`);
        
        $btnShow.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> رپورٹ بن رہی ہے...');

        try {
            const res = await API.get(`/ledger/${accId}`, { from_date: from, to_date: to });
            renderLedger(res.data);
            Toast.success("کھاتہ رپورٹ اپڈیٹ کر دی گئی ہے۔");
        } catch (err) {
        } finally {
            $btnShow.prop('disabled', false).html('<i class="fas fa-search"></i> کھاتہ دکھائیں');
        }
    });

    // 4. Download PDF Action
    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 accId = $partySelect.val();
        if (!accId) {
            Toast.warning("براہ کرم پہلے کوئی کھاتہ منتخب کریں۔");
            return;
        }

        const account = MandiData.accounts.find(a => a.id == accId);
        const filename = `Ledger_${account.name.replace(/\s+/g, '_')}_${$('#ledgerDateFrom').val()}_to_${$('#ledgerDateTo').val()}.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)');
        }
    });

    function renderLedger(data) {
        let html = '';
        const acc = data.account;
        const entries = data.ledger;
        const from = $('#ledgerDateFrom').val();

        // 1. Add Opening Balance Row (Essential for user to see starting state)
        const ob = parseFloat(data.opening_balance);
        const obType = ob >= 0 ? 'Dr' : 'Cr';
        const obUrdu = obType === 'Dr' ? '(نام)' : '(جمع)';
        
        html += `
            <tr class="table-info" style="background-color: var(--gray-50); border-bottom: 2px solid var(--border-color);">
                <td><bdi>${Utils.formatDate(from)}</bdi></td>
                <td class="fw-bold"><bdi>سابقہ بقیہ / اوپننگ بیلنس (Opening Balance)</bdi></td>
                <td class="text-danger fw-bold"><bdi>${obType === 'Dr' ? Utils.formatNumber(Math.abs(ob)) : '-'}</bdi></td>
                <td class="text-success fw-bold"><bdi>${obType === 'Cr' ? Utils.formatNumber(Math.abs(ob)) : '-'}</bdi></td>
                <td class="fw-bold ${ob >= 0 ? 'text-danger' : 'text-success'}">
                    <bdi>${Utils.formatNumber(Math.abs(ob))}</bdi>&nbsp;<bdi>${obUrdu}</bdi>
                </td>
            </tr>
        `;

        // 2. Add Transaction Rows
        if (entries.length === 0) {
            // No transactions
        } else {
            entries.forEach(e => {
                const dr = parseFloat(e.debit);
                const cr = parseFloat(e.credit);
                const bal = parseFloat(e.running_balance);
                const balType = bal >= 0 ? 'Dr' : 'Cr';
                const balUrdu = balType === 'Dr' ? '(نام)' : '(جمع)';
                
                const isRev = parseInt(e.is_reversed, 10) === 1;
                const wrapStart = isRev ? '<del>' : '';
                const wrapEnd = isRev ? '</del>' : '';
                const inlineStyle = isRev ? 'style="opacity: 0.65;"' : '';

                html += `
                    <tr class="${isRev ? 'text-muted text-decoration-line-through' : ''}" ${inlineStyle}>
                        <td><bdi>${wrapStart}${Utils.formatDate(e.journal_date)}${wrapEnd}</bdi></td>
                        <td>
                            <div class="fw-bold"><bdi>${wrapStart}${e.header_narration || e.narration || '-'}${wrapEnd}</bdi></div>
                            ${e.narration && e.narration !== e.header_narration ? `<div class="text-muted" style="font-size: 0.85em; margin-top: 2px;"><bdi>${wrapStart}${e.narration}${wrapEnd}</bdi></div>` : ''}
                            <small class="text-muted"><bdi>#${e.journal_id} | ${e.source_type} ${isRev ? '| (منسوخ شدہ)' : ''}</bdi></small>
                        </td>
                        <td class="text-danger"><bdi>${dr > 0 ? wrapStart + Utils.formatNumber(dr) + wrapEnd : '-'}</bdi></td>
                        <td class="text-success"><bdi>${cr > 0 ? wrapStart + Utils.formatNumber(cr) + wrapEnd : '-'}</bdi></td>
                        <td class="fw-bold ${bal >= 0 ? 'text-danger' : 'text-success'}">
                            <bdi>${wrapStart}${Utils.formatNumber(Math.abs(bal))}${wrapEnd}</bdi>&nbsp;<bdi>${balUrdu}</bdi>
                        </td>
                    </tr>
                `;
            });
        }

        $tableBody.html(html);

        // FIXED: Exclude reversed entries from totals
        let totalDr = entries.filter(e => parseInt(e.is_reversed) !== 1).reduce((s, e) => s + parseFloat(e.debit), 0);
        let totalCr = entries.filter(e => parseInt(e.is_reversed) !== 1).reduce((s, e) => s + parseFloat(e.credit), 0);
        
        $('#totalDebit').text(Utils.formatNumber(totalDr));
        $('#totalCredit').text(Utils.formatNumber(totalCr));
        
        // Final Balance
        const lastBal = entries.length > 0 
            ? parseFloat(entries[entries.length-1].running_balance)
            : ob;
            
        const lastType = lastBal >= 0 ? '(نام)' : '(جمع)';
        $('#finalBalance').text(`${Utils.formatNumber(Math.abs(lastBal))} ${lastType}`);
    }
}
</script>
