//================ class dropdown foe pending list ================
const FinanceDash = {
    data: [],
    page: 1,
    limit: 10,
    yearsCache: [],

    /* =========================
        LOAD ACADEMIC YEARS
    ========================== */
    async loadYears() {
        const yearSelect = document.getElementById('pendingYear');
        if (!yearSelect) return;

        try {
            const res = await fetch('api/settings/get_all_years.php');
            const years = await res.json();
            this.yearsCache = Array.isArray(years) ? years : [];

            let html = '<option value="">Select Academic Year</option>';
            this.yearsCache.forEach(y => {
                const isSelected = y.is_active == 1 ? 'selected' : '';
                html += `<option value="${y.id}" ${isSelected}>${y.year_name}</option>`;
            });
            yearSelect.innerHTML = html;

            this.syncMonthToYear();

        } catch (err) {
            yearSelect.innerHTML = '<option value="">Error loading years</option>';
        }
    },

    /* =========================
        NEW: LOAD MEDIUMS
    ========================== */
    async loadMediums() {
        const mediumSelect = document.getElementById('pendingMedium');
        if (!mediumSelect) return;

        try {
            const res = await fetch('api/mediums/get_mediums.php');
            const result = await res.json();

            let html = '<option value="all">All Medium</option>';
            if (result.status && Array.isArray(result.data)) {
                result.data.forEach(m => {
                    html += `<option value="${m.id}">${m.medium_name}</option>`;
                });
            }
            mediumSelect.innerHTML = html;
        } catch (err) {
            mediumSelect.innerHTML = '<option value="all">Error loading</option>';
        }
    },

    /* ==========================================
        NEW: SYNC MONTH FILTER TO ACADEMIC YEAR
    ========================================== */
    syncMonthToYear() {
        const yearId = document.getElementById('pendingYear').value;
        const monthField = document.getElementById('pendingMonth');
        if (!yearId || !monthField) return;

        const selectedYear = this.yearsCache.find(y => y.id == yearId);

        if (selectedYear && selectedYear.start_date) {
            // This regex ensures we only get YYYY-MM even if there's a time attached
            const dateMatch = selectedYear.start_date.match(/^\d{4}-\d{2}/);
            if (dateMatch) {
                monthField.value = dateMatch[0];
            }
        }
    },

    /* =========================
        LOAD CLASSES
    ========================== */
    async loadClassesPending() {
        const classSelect = document.getElementById('pendingClass');
        if (!classSelect) return;

        try {
            const res = await fetch('api/classes/get_classes.php');
            const classes = await res.json();

            let html = '<option value="all">All Classes</option>';
            if (Array.isArray(classes)) {
                classes.forEach(cls => {
                    html += `<option value="${cls.id}">${cls.class_name}</option>`;
                });
            }
            classSelect.innerHTML = html;
        } catch (err) {
            classSelect.innerHTML = '<option value="all">Error loading classes</option>';
        }
    },

    /* =========================
        RESET FILTERS
    ========================== */
    async resetFilters() {
        document.getElementById('pendingClass').value = 'all';
        if (document.getElementById('pendingMedium')) document.getElementById('pendingMedium').value = 'all';
        document.getElementById('pendingStatus').value = 'all';
        document.getElementById('pendingSearch').value = '';

        await this.loadYears();

        this.page = 1;
        this.refreshDashboard();
    },

    /* =========================
        VIEW STUDENT STATEMENT (MODAL)
    ========================== */
    async viewStatement(studentId) {
        const hiddenInput = document.getElementById('m_student_id_hidden');
        if (hiddenInput) hiddenInput.value = studentId;

        const yearId = document.getElementById('pendingYear').value;
        if (!yearId) {
            alert("Please select an Academic Year first");
            return;
        }

        const modal = new bootstrap.Modal(document.getElementById('statementModal'));
        modal.show();

        const body = document.getElementById('statementBody');
        const footer = document.getElementById('statementFooter');
        body.innerHTML = '<tr><td colspan="6" class="text-center">Loading Ledger...</td></tr>';

        try {
            const res = await fetch(`api/financialReport/get_student_history.php?student_id=${studentId}&academic_year_id=${yearId}`);
            const result = await res.json();

            if (result.status !== 'success') throw new Error(result.message);

            const s = result.details;
            const fs = result.financial_summary;

            document.getElementById('m_student_name').innerText = s.student_name;
            document.getElementById('m_roll').innerText = s.roll_no;
            document.getElementById('m_parent').innerText = s.father_name;
            document.getElementById('m_address').innerText = s.address || 'N/A';

            let classLabel = s.class_name;
            if (s.section_name) classLabel += ` (${s.section_name})`;
            if (s.medium_name) classLabel += ` Medium :` + `- ${s.medium_name}`;

            document.getElementById('m_class').innerText = classLabel;

            body.innerHTML = result.history.map(r => {
                const bal = parseFloat(r.assigned_amount) - (parseFloat(r.period_paid) + parseFloat(r.period_discount));
                return `
                <tr>
                    <td>${r.due_month}</td>
                    <td>${r.fee_title}</td>
                    <td class="text-end">₹${parseFloat(r.assigned_amount).toLocaleString('en-IN')}</td>
                    <td class="text-end text-success">₹${parseFloat(r.period_paid).toLocaleString('en-IN')}</td>
                    <td class="text-end text-warning">₹${parseFloat(r.period_discount).toLocaleString('en-IN')}</td>
                    <td class="text-end fw-bold ${bal > 0 ? 'text-danger' : ''}">₹${bal.toLocaleString('en-IN')}</td>
                </tr>`;
            }).join('');

            footer.innerHTML = `
            <tr class="table-dark">
                <td colspan="2" class="text-center">SESSION TOTALS</td>
                <td class="text-end">₹${fs.total_expected.toLocaleString('en-IN')}</td>
                <td class="text-end">₹${fs.total_collected.toLocaleString('en-IN')}</td>
                <td class="text-end">₹${fs.total_discount.toLocaleString('en-IN')}</td>
                <td class="text-end text-warning">₹${fs.total_outstanding.toLocaleString('en-IN')}</td>
            </tr>`;

        } catch (err) {
            body.innerHTML = `<tr><td colspan="6" class="text-danger text-center">${err.message}</td></tr>`;
        }
    },

    downloadPHPReport() {
        const studentId = document.getElementById('m_student_id_hidden')?.value;
        const yearId = document.getElementById('pendingYear').value;
        if (!studentId || !yearId) {
            alert("Unable to generate report: Missing data.");
            return;
        }
        window.open(`api/financialReport/statement_student_pdf.php?student_id=${studentId}&academic_year_id=${yearId}`, '_blank');
    },

    /* =========================
        FETCH & REFRESH DASHBOARD
    ========================== */
    async refreshDashboard() {
        const monthInput = document.getElementById('pendingMonth').value; // format: "YYYY-MM"
        const classId = document.getElementById('pendingClass').value;
        const yearId = document.getElementById('pendingYear').value;
        const mediumId = document.getElementById('pendingMedium')?.value || 'all';

        if (!yearId || !monthInput) {
            this.data = [];
            this.updateKPIs();
            const msg = !yearId ? 'Please select an Academic Year' : 'Please select a Month';
            document.getElementById('pendingBody').innerHTML = `<tr><td colspan="8" class="text-center p-4">${msg}</td></tr>`;
            return;
        }

        // Convert "2026-02" to "February"
        const d = new Date(monthInput + '-01');
        const monthNameOnly = d.toLocaleString('en-US', { month: 'long' });

        try {
            const res = await fetch(`api/financialReport/fetch_fees.php?month=${monthNameOnly}&class=${classId}&academic_year_id=${yearId}&medium_id=${mediumId}`);
            const json = await res.json();
            this.data = (json.status && Array.isArray(json.data)) ? json.data : [];
            this.updateKPIs();
            this.renderTable();
        } catch (err) {
            console.error('Dashboard Fetch Error:', err);
        }
    },

    changePage(step) {
        const search = document.getElementById('pendingSearch').value.toLowerCase();
        const statusFilter = document.getElementById('pendingStatus').value;

        const filteredCount = this.data.filter(item => {
            const matchesSearch = item.student_name.toLowerCase().includes(search) ||
                item.roll_no.toString().includes(search);
            const matchesStatus = (statusFilter === 'all') || (item.payment_status === statusFilter);
            return matchesSearch && matchesStatus;
        }).length;

        const totalPages = Math.ceil(filteredCount / this.limit) || 1;

        const targetPage = this.page + step;
        if (targetPage >= 1 && targetPage <= totalPages) {
            this.page = targetPage;
            this.renderTable();
        }
    },

    renderTable() {
        const body = document.getElementById('pendingBody');
        const search = document.getElementById('pendingSearch').value.toLowerCase();
        const statusFilter = document.getElementById('pendingStatus').value;

        const filtered = this.data.filter(item => {
            const matchesSearch = item.student_name.toLowerCase().includes(search) || item.roll_no.toString().includes(search);
            const matchesStatus = (statusFilter === 'all') || (item.payment_status === statusFilter);
            return matchesSearch && matchesStatus;
        });

        const totalRecords = filtered.length;
        const totalPages = Math.ceil(totalRecords / this.limit) || 1;
        if (this.page > totalPages) this.page = 1;

        const start = (this.page - 1) * this.limit;
        const paginated = filtered.slice(start, start + this.limit);

        document.getElementById('paginationInfo').innerText = totalRecords > 0 ? `Showing Page ${this.page} of ${totalPages} (${totalRecords} entries)` : `Showing 0 entries`;

        if (paginated.length === 0) {
            body.innerHTML = '<tr><td colspan="7" class="text-center p-4 text-muted">No records found.</td></tr>';
            return;
        }

        body.innerHTML = paginated.map(item => {
            const assigned = parseFloat(item.assigned_total || 0);
            const paid = parseFloat(item.total_collected || 0);
            const discount = parseFloat(item.total_discount || 0);
            const balance = parseFloat(item.remaining_balance || 0);

            return `
            <tr>
                <td class="fw-bold text-primary">${item.roll_no}</td>
                <td>
                    <div class="fw-bold">${item.student_name}</div>
                    <div class="text-muted small">${item.parent_phone || '-'}</div>
                </td>
                <td>
                    ${item.class_name} 
                    ${item.section_name ? `<br><small class="text-muted">Sec: ${item.section_name}</small>` : ''}
                    ${item.medium_name ? `<br><small class="text-primary">Med: ${item.medium_name}</small>` : ''}
                </td>
                <td><span class="badge bg-info-subtle text-info border border-info">${item.fee_title || 'N/A'}</span></td>
                <td>
                    <div class="small">Assigned: ₹${assigned.toLocaleString('en-IN')}</div>
                    <div class="text-success small fw-bold">Paid: ₹${paid.toLocaleString('en-IN')}</div>
                </td>
                <td><span class="text-warning small fw-bold">₹${discount.toLocaleString('en-IN')}</span></td>
                <td>
                    <span class="badge rounded-pill ${item.payment_status === 'Paid' ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'}">${item.payment_status.toUpperCase()}</span>
                    ${balance > 0 ? `<div class="text-danger x-small fw-bold mt-1">Due: ₹${balance.toLocaleString('en-IN')}</div>` : ''}
                </td>
                <td class="text-center">
                    <button class="btn btn-sm btn-outline-primary" onclick="FinanceDash.viewStatement(${item.student_id})"><i class="fas fa-file-invoice"></i></button>
                    <button class="btn btn-sm btn-success" 
                        onclick='sendWhatsAppReminder(${item.student_id})'>
                        <i class="fab fa-whatsapp"></i>
                    </button>
                </td>
            </tr>`;
        }).join('');
    },

    updateKPIs() {
        let expected = 0, collected = 0, discounted = 0, outstanding = 0;
        this.data.forEach(item => {
            expected += parseFloat(item.assigned_total || 0);
            collected += parseFloat(item.total_collected || 0);
            discounted += parseFloat(item.total_discount || 0);
            outstanding += parseFloat(item.remaining_balance || 0);
        });
        const fmt = { minimumFractionDigits: 2, maximumFractionDigits: 2 };
        document.getElementById('totalExpected').innerText = expected.toLocaleString('en-IN', fmt);
        document.getElementById('totalCollected').innerText = collected.toLocaleString('en-IN', fmt);
        document.getElementById('totalDiscount').innerText = discounted.toLocaleString('en-IN', fmt);
        document.getElementById('totalOutstanding').innerText = outstanding.toLocaleString('en-IN', fmt);
    }
};

/* ==========================================
    Initialization and Listeners
========================================== */
document.addEventListener('DOMContentLoaded', async () => {
    // 1. Load All Selectors First
    // We use Promise.all to load them in parallel for speed
    await Promise.all([
        FinanceDash.loadYears(),
        FinanceDash.loadClassesPending(),
        FinanceDash.loadMediums() // Ensure this fills #pendingMedium
    ]);

    // 2. Refresh Dashboard (Now that all filters have values)
    FinanceDash.refreshDashboard();

    // 3. Year change listener
    document.getElementById('pendingYear')?.addEventListener('change', () => {
        FinanceDash.syncMonthToYear();
        FinanceDash.page = 1;
        FinanceDash.refreshDashboard();
    });

    // 4. API-based Filters (Added 'pendingMedium')
    // Changing these requires a new Database Fetch
    ['pendingMonth', 'pendingClass', 'pendingMedium'].forEach(id => {
        document.getElementById(id)?.addEventListener('change', () => {
            FinanceDash.page = 1;
            FinanceDash.refreshDashboard();
        });
    });

    // 5. Client-side Filters
    // Changing these only re-renders the existing this.data
    ['pendingSearch', 'pendingStatus'].forEach(id => {
        document.getElementById(id)?.addEventListener(id === 'pendingSearch' ? 'input' : 'change', () => {
            FinanceDash.page = 1;
            FinanceDash.renderTable();
        });
    });

    // 6. Pagination Listeners
    document.getElementById('prevPage')?.addEventListener('click', () => {
        if (FinanceDash.page > 1) {
            FinanceDash.page--;
            FinanceDash.renderTable();
        }
    });

    document.getElementById('nextPage')?.addEventListener('click', () => {
        // IMPROVED: Calculate if another page exists based on filtered results
        const search = document.getElementById('pendingSearch').value.toLowerCase();
        const statusFilter = document.getElementById('pendingStatus').value;

        const filteredCount = FinanceDash.data.filter(item => {
            const matchesSearch = item.student_name.toLowerCase().includes(search) ||
                item.roll_no.toString().includes(search);
            const matchesStatus = (statusFilter === 'all') || (item.payment_status === statusFilter);
            return matchesSearch && matchesStatus;
        }).length;

        if (FinanceDash.page * FinanceDash.limit < filteredCount) {
            FinanceDash.page++;
            FinanceDash.renderTable();
        }
    });

    document.getElementById('clearFilters')?.addEventListener('click', () => FinanceDash.resetFilters());
});
// ==============for whatsapp reminder message =================

const sendWhatsAppReminder = async (studentId) => {
    if (!studentId) return alert("Invalid Student ID");

    try {
        const response = await fetch(`api/fees/get_unpaid_by_student.php?student_id=${studentId}`);
        const result = await response.json();
          
        if (result.status && result.data && result.data.length > 0) {
            const cleanPhone = (result.parent_phone || '').replace(/\D/g, '');
            const finalPhone = cleanPhone.length === 10 ? '91' + cleanPhone : cleanPhone;

            let totalDue = 0;
            const feeItems = [];

            result.data.forEach(fee => {
                const amt = parseFloat(fee.balance || 0);
                if (amt > 0) {
                    totalDue += amt;
                    const monthText = fee.due_month ? `(${fee.due_month})` : '';
                    const dateText = fee.due_date ? ` [Due: ${fee.due_date}]` : '';
                    feeItems.push(`• ${fee.fee_title} ${monthText}: *₹${amt}*${dateText}`);
                }
            });

            if (feeItems.length === 0) {
                return alert("No current or past dues found.");
            }

            // Construct Message with School Name
            const msg = `*FEE REMINDER - ${result.school_name.toUpperCase()}*\n\n` +
                `Dear Parent, this is a reminder regarding the pending dues for *${result.student_name}*:\n\n` +
                `${feeItems.join('\n')}\n\n` +
                `*Total Outstanding: ₹${totalDue}*\n\n` +
                `Please settle the payment at the school office. Thank you.`;

            window.open(`https://wa.me/${finalPhone}?text=${encodeURIComponent(msg)}`, '_blank');
        } else {
            alert("No past or current unpaid fees found for this student.");
        }
    } catch (error) {
        console.error("Error:", error);
    }
};
//-----------------financial Report start----------------------------------------

function generateReport(period) {
    if (!period) return;

    const yearEl = document.getElementById('pendingYear');
    let academic_year_id = "";

    if (yearEl && yearEl.value && yearEl.value !== "") {
        academic_year_id = yearEl.value;
    } else if (typeof APP_YEAR_ID !== 'undefined' && APP_YEAR_ID !== "") {
        academic_year_id = APP_YEAR_ID;
    }

    if (!academic_year_id) {
        alert("Error: Academic Year ID not found. Please select a year.");
        return;
    }

    const periodEl = document.getElementById('reportPeriod');
    const periodLabel = periodEl ? periodEl.options[periodEl.selectedIndex].text : "Full Academic Year";

    const breakdownBody = document.getElementById('m_breakdown_body');
    if (breakdownBody) {
        breakdownBody.innerHTML = `
            <tr>
                <td colspan="30" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status"></div>
                    <p class="mt-2 text-muted">Analyzing full session records...</p>
                </td>
            </tr>`;
    }

    // Note: period=yearly is forced here as we removed quarterly logic in PHP
    fetch(`api/reports/get_finance_summary.php?period=yearly&academic_year_id=${academic_year_id}`)
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(res => {
            if (res.status === 'success') {
                renderReportUI(res, periodLabel);
            } else {
                alert("Server Error: " + res.message);
                if (breakdownBody) {
                    breakdownBody.innerHTML = `<tr><td colspan="30" class="text-center text-danger">${res.message}</td></tr>`;
                }
            }
        })
        .catch(err => {
            console.error("Critical Fetch Error:", err);
            alert("Failed to load report. Check console for details.");
        });
}

/**
 * UI Rendering Logic: Populates cards and dynamic table
 */
function renderReportUI(res, periodLabel) {
    try {
        const s = res.summary;
        const feeCols = res.fee_columns; // Array of titles like ["Tuition Fee", "Bus Fee"]
        const breakdown = res.breakdown;

        const fmt = (val) => '₹' + parseFloat(val || 0).toLocaleString('en-IN', { minimumFractionDigits: 0 });

        const updateText = (id, val) => {
            const el = document.getElementById(id);
            if (el) el.innerText = val;
        };

        updateText('m_total_students', breakdown.reduce((acc, row) => acc + parseInt(row.student_count || 0), 0));
        updateText('m_report_title', periodLabel);
        updateText('m_total_assign', fmt(s.total_assigned));
        updateText('m_total_collect', fmt(s.period_collected));
        updateText('m_total_out', fmt(s.total_unpaid));
        updateText('m_total_discount', fmt(s.total_discount));

        // 2. Build Dynamic Header (Removed Stream from Column Header)
        let headerHtml = `
        <tr>
            <th rowspan="2" class="align-middle bg-dark text-white">Class</th>
            <th rowspan="2" class="align-middle text-center bg-dark text-white">Students</th>`;

        feeCols.forEach(col => {
            headerHtml += `<th colspan="2" class="text-center border-bottom bg-secondary text-white">${col}</th>`;
        });

        headerHtml += `
            <th rowspan="2" class="align-middle text-end bg-success text-white">Net Paid</th>
            <th rowspan="2" class="align-middle text-end bg-danger text-white">Net Unpaid</th>
        </tr><tr>`;

        feeCols.forEach(() => {
            headerHtml += `
                <th class="text-end small text-success" style="font-size:10px">Paid</th>
                <th class="text-end small text-danger" style="font-size:10px">Unpaid</th>`;
        });
        headerHtml += `</tr>`;

        const headerRow = document.getElementById('m_header_row');
        if (headerRow) headerRow.innerHTML = headerHtml;

        // 3. Build Table Body
        let bodyHtml = '';
        breakdown.forEach(row => {
            // Stream display logic removed
            bodyHtml += `<tr>
                <td class="fw-bold text-primary">${row.class_name}</td>
                <td class="text-center">${row.student_count}</td>`;

            feeCols.forEach(col => {
                const safeKey = col.replace(/ /g, '_');
                const p = parseFloat(row[safeKey + '_paid'] || 0);
                const u = parseFloat(row[safeKey + '_unpaid'] || 0);

                bodyHtml += `
                    <td class="text-end text-success font-monospace" style="font-size:11px">${p > 0 ? p.toFixed(0) : '-'}</td>
                    <td class="text-end text-danger font-monospace" style="font-size:11px">${u > 0 ? u.toFixed(0) : '-'}</td>`;
            });

            bodyHtml += `
                <td class="text-end fw-bold text-success">${fmt(row.total_class_paid)}</td>
                <td class="text-end fw-bold bg-light text-danger">${fmt(row.total_class_unpaid)}</td>
            </tr>`;
        });

        const breakdownBody = document.getElementById('m_breakdown_body');
        if (breakdownBody) breakdownBody.innerHTML = bodyHtml;

        // 4. Show the Modal
        const modalEl = document.getElementById('reportModal');
        if (modalEl) {
            let reportModal = bootstrap.Modal.getInstance(modalEl);
            if (!reportModal) reportModal = new bootstrap.Modal(modalEl);
            reportModal.show();
        }

    } catch (err) {
        console.error("UI Rendering Error:", err);
        alert("Error displaying data. Check console.");
    }
}
/**
 * Filter table rows based on Class Name search
 */
function filterClassTable() {
    const input = document.getElementById("classSearchInput");
    const filter = input.value.toUpperCase();
    const rows = document.getElementById("m_breakdown_body").getElementsByTagName("tr");

    for (let i = 0; i < rows.length; i++) {
        const td = rows[i].getElementsByTagName("td")[0];
        if (td) {
            const txtValue = td.textContent || td.innerText;
            rows[i].style.display = txtValue.toUpperCase().includes(filter) ? "" : "none";
        }
    }
}

/**
 * Print only the modal content
 */
function printReport() {
    const modalBody = document.querySelector('#reportModal .modal-body').innerHTML;
    const originalBody = document.body.innerHTML;

    document.body.innerHTML = `
        <div class="p-4">
            <h2 class="text-center">${document.getElementById('m_report_title').innerText}</h2>
            <hr>
            ${modalBody}
        </div>`;

    window.print();
    location.reload(); // Reload to restore original UI after printing
}

// ----------------financial Report start--------------------------------------------
//=================== Daily Report ==================================
async function openRevenueModal(type = 'daily') {
    const modalEl = document.getElementById('revenueModal');
    const modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
    modalInstance.show();

    const dateInput = document.getElementById('reportDate');

    if (type === 'uptodate') {
        try {
            // Fetch the dynamic start date from your settings/session table
            const response = await fetch('api/reports/get_session_info.php');
            const data = await response.json();

            if (data.start_date) {
                dateInput.value = data.start_date; // Sets it to e.g., 2025-04-01 from DB
            }
        } catch (error) {
            console.error("Error fetching session start:", error);
            dateInput.value = new Date().getFullYear() + "-04-01"; // Generic Fallback
        }
    } else {
        dateInput.value = new Date().toISOString().split('T')[0];
    }

    loadRevenueReport(type);
}

function loadRevenueReport(type = 'daily') {
    const reportDateEl = document.getElementById('reportDate');
    if (!reportDateEl) return; // Safety exit

    const selectedDate = reportDateEl.value;
    const loader = document.getElementById('modal_report_loader');
    const content = document.getElementById('modal_report_content');

    // Show Loader
    if (loader) loader.classList.remove('d-none');
    if (content) content.style.opacity = '0.3';

    // Target the title specifically inside the revenueModal ID
    const modalTitle = document.querySelector('#revenueModal .modal-title');

    if (modalTitle) {
        if (type === 'uptodate') {
            modalTitle.innerHTML = '<i class="fas fa-calendar-check me-2 text-warning"></i> Session Up-To-Date Report';
        } else {
            modalTitle.innerHTML = '<i class="fas fa-chart-line me-2 text-primary"></i> Daily Financial Summary';
        }
    }

    // Update PDF button dynamically
    const pdfBtn = document.getElementById('downloadPdfBtn');
    if (pdfBtn) {
        const selectedDate = document.getElementById('reportDate').value;

        if (type === 'uptodate') {
            pdfBtn.setAttribute('onclick', `window.open('api/reports/range_report_pdf.php?start_date=${selectedDate}', '_blank')`);
            pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Print Full Session';
        } else {
            pdfBtn.setAttribute('onclick', `window.open('api/reports/oneday_report_generated__pdf.php?date=${selectedDate}', '_blank')`);
            pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Print Daily Report';
        }
    }

    fetch(`api/reports/get_daily_revenue.php?date=${selectedDate}&type=${type}`)
        .then(res => res.json())
        .then(data => {
            if (loader) loader.classList.add('d-none');
            if (content) content.style.opacity = '1';

            if (data.status === 'success') {
                let totalCash = 0;
                let totalDisc = 0;

                // --- HANDLE PAYMENT MODE BREAKDOWN ---
                let breakdownHtml = '';
                if (data.breakdown && data.breakdown.length > 0) {
                    data.breakdown.forEach(row => {
                        const mode = row.payment_mode || 'N/A';
                        const cash = parseFloat(row.net_cash || 0);
                        const disc = parseFloat(row.total_discount || 0);
                        totalCash += cash;
                        totalDisc += disc;

                        breakdownHtml += `
                            <tr>
                                <td class="ps-3"><strong>${mode}</strong></td>
                                <td class="text-center">${row.transactions}</td>
                                <td class="text-danger text-end">₹${disc.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</td>
                                <td class="fw-bold text-end pe-3">₹${cash.toLocaleString('en-IN', { minimumFractionDigits: 2 })}</td>
                            </tr>`;
                    });
                } else {
                    breakdownHtml = '<tr><td colspan="4" class="text-center p-3 text-muted">No records found.</td></tr>';
                }

                // --- SAFE UPDATE OF TOTALS ---
                const mCash = document.getElementById('modal_total_cash');
                const mDisc = document.getElementById('modal_total_disc');
                if (mCash) mCash.innerText = `₹${totalCash.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`;
                if (mDisc) mDisc.innerText = `₹${totalDisc.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`;

                const dCash = document.getElementById('total_cash_display');
                if (dCash) dCash.innerText = `₹${totalCash.toLocaleString('en-IN', { minimumFractionDigits: 2 })}`;

                const bBody = document.getElementById('breakdown_body');
                if (bBody) bBody.innerHTML = breakdownHtml;

                // --- 3. HANDLE CLASS-WISE SUMMARY ---
                let classHtml = '';
                if (data.class_summary && data.class_summary.length > 0) {
                    data.class_summary.forEach(row => {
                        classHtml += `<tr><td class="ps-3"><strong>Class ${row.class_name}</strong></td><td class="text-center">${row.transactions}</td><td class="text-end pe-3 fw-bold">₹${parseFloat(row.class_total).toLocaleString('en-IN')}</td></tr>`;
                    });
                } else {
                    classHtml = '<tr><td colspan="3" class="text-center p-2">No class data.</td></tr>';
                }
                const cBody = document.getElementById('class_breakdown_body');
                if (cBody) cBody.innerHTML = classHtml;

                // --- 4. HANDLE TRANSACTIONS (Stream Removed) ---
                let txHtml = '';
                if (data.transactions && data.transactions.length > 0) {
                    data.transactions.forEach(tx => {
                        const timeInfo = (type === 'uptodate') ? tx.pay_day : tx.pay_time;

                        // Build the Class + Section string (Stream logic removed)
                        let studentDetails = `Class ${tx.class_name || ''}`;
                        if (tx.section_name) studentDetails += ` - ${tx.section_name}`;

                        txHtml += `
                            <tr>
                                <td class="ps-3 text-muted small">${timeInfo}</td>
                                <td class="fw-bold">${tx.receipt_number}</td>
                                <td>
                                    <div class="fw-bold">${tx.student_name}</div>
                                    <div class="small text-muted">${studentDetails}</div>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark border">${tx.payment_mode}</span>
                                </td>
                                <td class="text-end pe-3 fw-bold">₹${parseFloat(tx.amount_paid).toLocaleString('en-IN')}</td>
                            </tr>`;
                    });
                }
                const tBody = document.getElementById('transaction_list_body');
                if (tBody) tBody.innerHTML = txHtml || '<tr><td colspan="5" class="text-center p-4 text-muted">No transactions.</td></tr>';
            }
        })
        .catch(err => {
            if (loader) loader.classList.add('d-none');
            console.error("Revenue Load Error:", err);
        });
}
