// =========== load class list and filter for fee types ==================

async function fetchClassListFee(elementId, isFilter = false) {
    const classDropdown = document.getElementById(elementId);

    if (!classDropdown) return;

    try {
        const response = await fetch('api/classes/get_classes.php');
        if (!response.ok) throw new Error('Network response was not ok');

        const data = await response.json();

        // Customizing the first option based on whether it's a filter or a form
        let html = isFilter
            ? '<option value="">All Classes</option>'
            : '<option value="">-- Select Class --</option>';

        if (data.length > 0) {
            data.forEach(item => {
                html += `<option value="${item.id}">${item.class_name}</option>`;
            });
        } else {
            html = '<option value="">No classes found</option>';
        }

        classDropdown.innerHTML = html;

        // Trigger logic only for the Form dropdown (not the filter)
        if (!isFilter && classDropdown.value) {
            toggleStreamForFee(classDropdown);
        }

    } catch (error) {
        console.error(`Error loading classes for ${elementId}:`, error);
    }
}
/**
 * Populates Medium dropdowns from the database
 * @param {string} elementId - The ID of the select element to populate
 */
async function loadMediums(elementId) {
    const selectElement = document.getElementById(elementId);
    if (!selectElement) return;

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

        if (result.status) {
            // Keep the first "Select" option, clear the rest
            const firstOption = selectElement.options[0];
            selectElement.innerHTML = '';
            selectElement.appendChild(firstOption);

            result.data.forEach(medium => {
                const option = document.createElement('option');
                option.value = medium.id;
                option.textContent = medium.medium_name;
                selectElement.appendChild(option);
            });
        } else {
            console.error("Failed to load mediums:", result.msg);
        }
    } catch (error) {
        console.error("Error fetching mediums:", error);
    }
}
document.addEventListener('DOMContentLoaded', () => {
    loadMediums('filter_medium');
    loadMediums('filter_medium_id');

    // Populate the dropdown in the Fee Type form
    loadMediums('medium_id');
});
// ================= stream toggle dropdown ============

// Run the check when the page is ready
// Run the check when the page is ready
document.addEventListener('DOMContentLoaded', () => {

    // 1. Populate the Filter Dropdown (Table view)
    fetchClassListFee('filter_class', true);

    // 2. Populate the Form Dropdown (Add Modal)
    fetchClassListFee('class_id', false);


    // 2. NEW: Add listener for manual user changes
    
});
function toggleTransportFields(value) {
    const transportDiv = document.getElementById('transport_details');
    const kmInput = document.getElementById('km_range');

    if (value === 'Transport Fee') {
        transportDiv.style.display = 'block';
        kmInput.setAttribute('required', 'required');
    } else {
        transportDiv.style.display = 'none';
        kmInput.removeAttribute('required');
        kmInput.value = ''; // Clear value if switching back
    }
}
function addFeeTypes() {
    // 1. Collect form data
    const feeTitle = document.getElementById('fee_title').value.trim();
    const description = document.getElementById('description').value.trim();
    const amount = document.getElementById('amount').value.trim();
    const class_id = document.getElementById('class_id').value;
    const academic_year_id = document.getElementById('academic_year_id').value;

    // Collect Medium Data
    const medium_id = document.getElementById('medium_id').value;

    // Get KM Range
    const kmRange = document.getElementById('km_range').value.trim();

    // 2. Validate form data
    // UPDATED: Added medium_id to required validation, removed stream logic
    if (feeTitle === "" || amount === "" || class_id === "" || academic_year_id === "" || medium_id === "") {
        Swal.fire('Error!', 'Fee Title, Class, Medium, Academic Year, and Amount are required.', 'error');
        return;
    }

    // Additional validation for Transport
    if (feeTitle === "Transport Fee" && kmRange === "") {
        Swal.fire('Error!', 'Please enter the KM range for Transport Fee.', 'error');
        return;
    }

    const formData = new FormData();
    formData.append("fee_title", feeTitle);
    formData.append("description", description);
    formData.append("amount", amount);
    formData.append("class_id", class_id);
    formData.append("academic_year_id", academic_year_id);
    formData.append("km_range", kmRange);

    // Add Medium ID to payload
    formData.append("medium_id", medium_id);

    // 3. Submit to API
    fetch("api/fees/add_fee_type.php", {
        method: "POST",
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                Swal.fire('Success!', data.message, 'success');

                // Close Modal
                const modalEl = document.getElementById('feeTypesModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) modal.hide();

                // Reset Form and hide conditional fields
                document.getElementById('fee_types_form').reset();
                document.getElementById('transport_details').style.display = 'none';

                loadFeeTypesList();
            } else {
                Swal.fire('Error!', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Fetch Error:', error);
            Swal.fire('Error!', 'An unexpected error occurred.', 'error');
        });
}

// =============load academic years for feetypes========== 
async function loadFeeAcademicYears() {
    try {
        const response = await fetch('api/academic/get_academic_year_fee.php');
        const years = await response.json();

        const yearSelect = document.getElementById('academic_year_id');
        if (!yearSelect) return;

        yearSelect.innerHTML = ''; // Clear existing

        years.forEach(yr => {
            const option = document.createElement('option');
            option.value = yr.id;

            // If it's the active year, add a label and select it
            if (yr.is_current == 1) {
                option.textContent = yr.year_name + " (Current)";
                option.selected = true; // This makes it the default choice
            } else {
                option.textContent = yr.year_name;
            }

            yearSelect.appendChild(option);
        });
    } catch (error) {
        console.error("Error loading years for fee form:", error);
    }
}

// Call this when the page loads
document.addEventListener('DOMContentLoaded', loadFeeAcademicYears);
// =======================filter academic year =================
async function loadFillterAcademicYr() {
    try {
        const response = await fetch('api/academic/get_academic_year_fee.php');
        const years = await response.json();

        const yearSelect = document.getElementById('filter_academic_year');
        if (!yearSelect) return;

        yearSelect.innerHTML = ''; // Clear existing

        years.forEach(yr => {
            const option = document.createElement('option');
            option.value = yr.id;

            // If it's the active year, add a label and select it
            if (yr.is_current == 1) {
                option.textContent = yr.year_name + " (Current)";
                option.selected = true; // This makes it the default choice
            } else {
                option.textContent = yr.year_name;
            }

            yearSelect.appendChild(option);
        });
    } catch (error) {
        console.error("Error loading years for fee form:", error);
    }
}
// Call this when the page loads
document.addEventListener('DOMContentLoaded', loadFillterAcademicYr);
// ====================load fee list search and pagination====================
let currentFeePage = 1;
let searchQuery = "";

function loadFeeTypesList(page = 1) {
    currentFeePage = page;
    const feeTypesList = document.getElementById('feeTypesList');

    // 1. Get all filter values (REMOVED: stream filter)
    const yearFilter = document.getElementById('filter_academic_year')?.value || '';
    const classFilter = document.getElementById('filter_class')?.value || '';
    const mediumFilter = document.getElementById('filter_medium')?.value || '';

    if (!feeTypesList) return;

    // 2. Prepare API Request (REMOVED: stream_id)
    const queryParams = new URLSearchParams({
        page: page,
        search: searchQuery,
        year_id: yearFilter,
        class_id: classFilter,
        medium_id: mediumFilter
    });

    fetch(`api/fees/get_fee_types.php?${queryParams.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                let rows = '';
                if (data.data.length === 0) {
                    rows = '<tr><td colspan="8" class="text-center text-muted">No fee structures found for this selection.</td></tr>';
                } else {
                    data.data.forEach((fee, index) => {
                        let displayTitle = '';

                        // Define Display Title with Icons
                        if (fee.fee_title === 'Transport Fee') {
                            displayTitle = `
                                <div class="d-flex align-items-center">
                                    <i class="fas fa-bus text-warning me-2"></i>
                                    <div>
                                        <span class="fw-bold">${fee.fee_title}</span><br>
                                        <span class="badge bg-light text-dark border border-warning" style="font-size: 0.7rem;">
                                            ${fee.km_range} KM
                                        </span>
                                    </div>
                                </div>`;
                        } else if (fee.fee_title === 'Hostel Fee') {
                            displayTitle = `<div class="d-flex align-items-center"><i class="fas fa-bed text-danger me-2"></i><span class="fw-bold">${fee.fee_title}</span></div>`;
                        } else if (fee.fee_title === 'Tuition Fee') {
                            displayTitle = `<div class="d-flex align-items-center"><i class="fas fa-book-open text-primary me-2"></i><span class="fw-bold">${fee.fee_title}</span></div>`;
                        } else {
                            displayTitle = `<div class="d-flex align-items-center"><i class="fas fa-file-alt text-success me-2"></i><span class="fw-bold">${fee.fee_title}</span></div>`;
                        }

                        // REMOVED: Stream Badge Logic

                        // Medium Badge Logic
                        let mediumBadge = fee.medium_name
                            ? `<br><span class="badge bg-secondary mt-1" style="font-size: 0.65rem; background-color: #6c757d;">${fee.medium_name}</span>`
                            : '';

                        const rowNumber = ((page - 1) * 10) + (index + 1);
                        rows += `
                    <tr>
                        <td>${rowNumber}</td>
                        <td>${displayTitle}</td>
                        <td><span class="badge bg-info text-dark">${fee.year_name}</span></td>
                        <td>
                            <span class="badge bg-light text-dark border">${fee.class_name}</span>
                            ${mediumBadge}
                        </td>
                        <td><small>${fee.description || '-'}</small></td>
                        <td class="fw-bold text-end">${parseFloat(fee.amount).toFixed(2)}</td>
                        <td>
                            <button class="btn btn-sm ${fee.status == 1 ? 'btn-success' : 'btn-danger'}" 
                                    onclick="toggleStatusFee(${fee.id}, ${fee.status})">
                                ${fee.status == 1 ? 'Active' : 'Inactive'}
                            </button>
                        </td>
                        <td>
                            <button class="btn btn-outline-primary btn-sm" onclick="editFeeType(${fee.id})">
                                <i class="fas fa-edit"></i>
                            </button>
                        </td>
                    </tr>`;
                    });
                }
                feeTypesList.innerHTML = rows;
                renderSeachPagination(data.total_pages, data.current_page);
            }
        })
        .catch(err => console.error("Error loading fees:", err));
}
// Function moved OUTSIDE loadFeeTypesList
function renderSeachPagination(totalPages, current) {
    const pagination = document.getElementById('seachpagination');
    if (!pagination) return;

    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }

    let buttons = '<nav aria-label="Page navigation"><ul class="pagination pagination-sm mb-0">';

    // Previous Button
    buttons += `
        <li class="page-item ${current === 1 ? 'disabled' : ''}">
            <button class="page-link" onclick="loadFeeTypesList(${current - 1})" ${current === 1 ? 'disabled' : ''}>Previous</button>
        </li>`;

    // Page Numbers
    for (let i = 1; i <= totalPages; i++) {
        buttons += `
            <li class="page-item ${i === current ? 'active' : ''}">
                <button class="page-link" onclick="loadFeeTypesList(${i})">${i}</button>
            </li>`;
    }

    // Next Button
    buttons += `
        <li class="page-item ${current === totalPages ? 'disabled' : ''}">
             <button class="page-link" onclick="loadFeeTypesList(${current + 1})" ${current === totalPages ? 'disabled' : ''}>Next</button>
        </li>`;

    buttons += '</ul></nav>';
    pagination.innerHTML = buttons;
}

// Function moved OUTSIDE loadFeeTypesList
function searchFees(value) {
    searchQuery = value.trim();
    loadFeeTypesList(1);
}

// Function to toggle the status between active and inactive
// =============================Function to toggle the status (active/inactive)===================
function toggleStatusFee(id, currentStatus) {
    const newStatus = currentStatus == 1 ? 0 : 1;

    fetch('api/fees/update_fee_status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, status: newStatus })
    })
        .then(response => {
            // If the server crashes with a 500 error, we capture the text
            if (!response.ok) {
                return response.text().then(text => { throw new Error(text) });
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                Swal.fire({
                    icon: 'success',
                    title: 'Status Updated',
                    showConfirmButton: false,
                    timer: 1500
                });
                loadFeeTypesList(); // Refresh the table
            } else {
                Swal.fire('Error!', data.message, 'error');
            }
        })
        .catch(error => {
            // This will now show you the ACTUAL PHP error if it's not JSON
            console.error('Server Response Error:', error);
            Swal.fire('Critical Error', 'Check the browser console for details.', 'error');
        });
}
// Function to load fee types and generate buttons for each fee





//============= Function to handle editing fee types============
// ===================get dropdown list class and year===========================
function populateAllDropdowns() {
    fetch('api/fees/get_dropdown_classAndYear.php')
        .then(res => res.json())
        .then(data => {

            // 1. Get references to all select elements
            const editClass = document.getElementById('edit_class_id');
            const editYear = document.getElementById('edit_academic_year_id');

            // Fill Class Dropdown
            if (editClass) {
                editClass.innerHTML = '<option value="">Select Class</option>';
                data.classes.forEach(cls => {
                    editClass.innerHTML += `<option value="${cls.id}">${cls.class_name}</option>`;
                });
            }

            // Fill Academic Year Dropdown
            if (editYear) {
                editYear.innerHTML = '<option value="">Select Year</option>';
                data.years.forEach(yr => {
                    // Using year_name from your DB
                    editYear.innerHTML += `<option value="${yr.id}">${yr.year_name}</option>`;
                });
            }

            // After dropdowns are ready, you can load your table
            loadFeeTypesList(1);
        });
}

// Call this on page load
document.addEventListener('DOMContentLoaded', populateAllDropdowns);
//=========================load edit data for fee types======================
// ============================edit fee title transport toggle=================
function toggleEditTransportFields(value) {
    const transportDiv = document.getElementById('edit_transport_details');
    const kmInput = document.getElementById('edit_km_range');

    if (value === 'Transport Fee') {
        transportDiv.style.display = 'block';
        kmInput.setAttribute('required', 'required');
    } else {
        transportDiv.style.display = 'none';
        kmInput.removeAttribute('required');
    }
}

async function editFeeType(id) {
    // 1. Load mediums first so the options exist before we try to select one
    await loadMediums('edit_medium_id');

    fetch(`api/fees/get_edit_fee_type.php?id=${id}`)
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                const fee = data.data;

                // 2. Fill Hidden ID and Text inputs
                document.getElementById('edit_fee_id').value = fee.id;
                document.getElementById('edit_fee_title').value = fee.fee_title;
                document.getElementById('edit_amount').value = fee.amount;
                document.getElementById('edit_description').value = fee.description;
                document.getElementById('edit_km_range').value = fee.km_range || '';

                // 3. Handle Transport UI (Toggle fields based on title)
                toggleEditTransportFields(fee.fee_title);

                // 4. Set Class and Year
                document.getElementById('edit_class_id').value = fee.class_id;
                document.getElementById('edit_academic_year_id').value = fee.academic_year_id;

                // 5. Set Medium
                document.getElementById('edit_medium_id').value = fee.medium_id || '';

                // REMOVED: Stream logic and toggleStreamVisibility call

                // 6. Open the Modal
                $('#editFeeModal').modal('show');
            } else {
                Swal.fire("Error", data.message || "Failed to fetch fee data", "error");
            }
        })
        .catch(err => {
            console.error("Fetch Error:", err);
            Swal.fire("Error", "Could not connect to server", "error");
        });
}
// Function to handle the update of a fee type
function updateFeeType() {
    const feeId = document.getElementById("edit_fee_id").value;
    const title = document.getElementById("edit_fee_title").value.trim();
    const desc = document.getElementById("edit_description").value.trim();
    const amount = document.getElementById("edit_amount").value;
    const classId = document.getElementById("edit_class_id").value;
    const yearId = document.getElementById("edit_academic_year_id").value;
    const mediumId = document.getElementById("edit_medium_id").value;
    const kmValue = document.getElementById("edit_km_range").value;

    // Validation for required fields (REMOVED: stream validation)
    if (!feeId || !title || !amount || !classId || !yearId || !mediumId) {
        Swal.fire({
            icon: "warning",
            title: "Missing Fields",
            text: "All required fields must be filled."
        });
        return;
    }

    const formData = new FormData();
    formData.append("edit_fee_id", feeId);
    formData.append("edit_fee_title", title);
    formData.append("edit_description", desc);
    formData.append("edit_amount", amount);
    formData.append("edit_class_id", classId);
    formData.append("edit_academic_year_id", yearId);
    formData.append("edit_medium_id", mediumId);
    formData.append("edit_km_range", kmValue);

    // Show loading
    Swal.fire({
        title: "Updating Fee...",
        text: "Please wait",
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch("api/fees/update_fee_type.php", {
        method: "POST",
        body: formData
    })
    .then(res => res.json())
    .then(data => {
        Swal.close();
        if (data.status === "success") {
            Swal.fire({
                icon: "success",
                title: "Updated!",
                text: data.message,
                timer: 1500,
                showConfirmButton: false
            });

            // Close modal
            const modalEl = document.getElementById("editFeeModal");
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            if (modalInstance) modalInstance.hide();

            // Reload list
            loadFeeTypesList();
        } else {
            Swal.fire({
                icon: "error",
                title: "Update Failed",
                text: data.message
            });
        }
    })
    .catch(err => {
        console.error("Update Error:", err);
        Swal.fire({
            icon: "error",
            title: "Server Error",
            text: "Something went wrong. Please try again."
        });
    });
}

// Load fee types on page load
window.onload = function () {
    loadFeeTypesList();
};
// =============Fee assign load table and check and submission form ==================
function openAssignFeeModal() {
    // 1. Identify dropdowns
    const classDrop = document.getElementById('assign_class_id');
    const sessionDrop = document.getElementById('assign_session_id');
    const mediumDrop = document.getElementById('assign_medium_id');
    const studentList = document.getElementById('student_list_area');

    // 2. Clear previous selections and show loading state
    if (classDrop) classDrop.innerHTML = '<option value="">Loading...</option>';
    if (sessionDrop) sessionDrop.innerHTML = '<option value="">Loading...</option>';
    if (mediumDrop) mediumDrop.innerHTML = '<option value="">Loading...</option>';
    
    // Reset student list to initial state
    if (studentList) {
        studentList.innerHTML = '<tr><td colspan="5" class="text-center">Select Class and Medium to load students</td></tr>';
    }

    // 3. Populate dropdowns
    populateDropdown('api/classes/get_classes.php', 'assign_class_id');
    populateDropdown('api/academic/get_academic_year_fee.php', 'assign_session_id');
    
    // Load Mediums using your existing helper
    if (typeof loadMediums === "function") {
        loadMediums('assign_medium_id');
    }

    // 4. Open the Modal
    $('#assignFeeModal').modal('show');
}

/**
 * Helper Function (Updated to handle stream_name display)
 */
function populateDropdown(url, elementId) {
    fetch(url)
        .then(res => res.json())
        .then(data => {
            const select = document.getElementById(elementId);
            if (!select) return;

            // Normalize data: handle both {data: [...]} and direct array responses
            const items = data.data ? data.data : data;

            // Determine the default label based on the element ID
            let typeLabel = 'Option';
            if (elementId.includes('class')) {
                typeLabel = 'Classes';
            } else if (elementId.includes('year') || elementId.includes('session')) {
                typeLabel = 'Academic Year';
            } else if (elementId.includes('medium')) {
                typeLabel = 'Mediums';
            }

            let html = `<option value="">-- Select ${typeLabel} --</option>`;

            if (Array.isArray(items)) {
                items.forEach(item => {
                    // REMOVED: item.stream_name check
                    // Logic picks the right property for the label
                    const name = item.class_name || item.year_name || item.medium_name || item.name;
                    const id = item.id;
                    
                    if (id && name) {
                        html += `<option value="${id}">${name}</option>`;
                    }
                });
            }

            select.innerHTML = html;
        })
        .catch(err => {
            console.error(`Failed to load dropdown ${elementId}:`, err);
            const select = document.getElementById(elementId);
            if (select) select.innerHTML = `<option value="">Error loading data</option>`;
        });
}

/**
 * Load Students and Fees based on Class, Session & Stream
 */
function loadStudentsAndFees() {
    const classId = document.getElementById('assign_class_id').value;
    const sessionId = document.getElementById('assign_session_id').value;
    const mediumId = document.getElementById('assign_medium_id').value;

    // REMOVED: Stream container validation logic

    // Validation: Requires Class, Session, and Medium to proceed
    if (!classId || !sessionId || !mediumId) {
        document.getElementById('student_list_area').innerHTML = '<tr><td colspan="5" class="text-center text-muted">Please select Class, Medium, and Session.</td></tr>';
        return;
    }

    const studentTable = document.getElementById('student_list_area');
    const feeSelect = document.getElementById('assign_fee_id');

    studentTable.innerHTML = '<tr><td colspan="5" class="text-center">Loading Data...</td></tr>';

    // Simplified URL (Removed stream_id)
    const url = `api/fees/get_students_and_fees.php?class_id=${classId}&session_id=${sessionId}&medium_id=${mediumId}`;

    fetch(url)
        .then(res => res.json())
        .then(data => {
            // 1. Fill Fee Dropdown
            feeSelect.innerHTML = '<option value="">Select Fee</option>';
            if (data.fees && data.fees.length > 0) {
                data.fees.forEach(f => {
                    feeSelect.innerHTML += `<option value="${f.id}">${f.fee_title} (${f.amount})</option>`;
                });
            }

            // 2. Fill Student Table
            studentTable.innerHTML = '';
            if (data.students && data.students.length > 0) {
                data.students.forEach(s => {
                    const isDropped = (s.promotion_status === 'dropped');

                    let actionButton = isDropped 
                        ? `<span class="badge bg-secondary">Dropped - No Fees</span>` 
                        : `<span class="text-muted">Eligible</span>`;

                    studentTable.innerHTML += `
                        <tr>
                            <td><input type="checkbox" name="student_ids[]" value="${s.id}" class="stu-checkbox" ${isDropped ? 'disabled' : ''}></td>
                            <td>${s.roll_no}</td>
                            <td>
                                <div class="fw-bold">${s.student_name}</div>
                                <small class="text-muted">ID: #STU-${s.id}</small>
                            </td> 
                            <td>
                                <span class="badge bg-light text-dark border">${s.medium_name}</span>
                            </td>
                            <td>${actionButton}</td>
                        </tr>`;
                });

                // Update student count badge
                if (document.getElementById('student_count')) {
                    document.getElementById('student_count').textContent = `${data.students.length} Students Found`;
                }

            } else {
                studentTable.innerHTML = '<tr><td colspan="5" class="text-center text-danger">No active students found for this Medium and Class.</td></tr>';
            }
        })
        .catch(err => {
            console.error("Error:", err);
            studentTable.innerHTML = '<tr><td colspan="5" class="text-center text-danger">Error loading data.</td></tr>';
        });
}

/**
 * 2. Select All Logic 
 * FIX: Use Event Delegation so it works even after the table reloads
 */
document.addEventListener('change', function (e) {
    if (e.target && e.target.id === 'checkAll') {
        const checkboxes = document.querySelectorAll('.stu-checkbox');
        checkboxes.forEach(cb => cb.checked = e.target.checked);
    }
});


// ==============submit assignment fee ======================
function submitFeeAssignment() {
    const form = document.getElementById('assignFeeForm');
    const formData = new FormData(form);

    // 1. Validate Multiple Months (NEW)
    const selectedMonths = formData.getAll('due_months[]');
    if (selectedMonths.length === 0) {
        alert("Please select at least one Month.");
        return;
    }

    // 2. Validate Medium (NEW)
    const mediumId = formData.get('medium_id');
    if (!mediumId) {
        alert("Please select a Medium.");
        return;
    }

    // 3. Validate Stream for Senior Classes

    // If the stream dropdown is visible (Class 11/12), it must have a value
    

    // 4. Check if a fee and date are selected
    if (!formData.get('fee_id') || !formData.get('due_date')) {
        alert("Please select a Fee Type and a Due Date.");
        return;
    }

    // 5. Check if at least one student is selected
    const selectedStudents = formData.getAll('student_ids[]');
    if (selectedStudents.length === 0) {
        alert("Please select at least one student from the list.");
        return;
    }

    // 6. Send to PHP
    // Note: PHP will receive $_POST['due_months'] as an array and $_POST['student_ids'] as an array
    fetch('api/fees/submit_fee_assignment.php', {
        method: 'POST',
        body: formData
    })
        .then(res => res.json())
        .then(data => {
            if (data.status === 'success') {
                alert(data.message);
                $('#assignFeeModal').modal('hide');
                // Reload the lists
                if (typeof loadAssignedFees === "function") loadAssignedFees();
            } else {
                alert("Error: " + data.message);
            }
        })
        .catch(err => {
            console.error("Submission failed:", err);
            alert("A system error occurred.");
        });
}
// ==============Function to load students from the database================

// fee asignment form submision 
function assignFee() {
    const form = document.getElementById('feeAssignmentForm');
    const formData = new FormData(form);

    // Convert FormData to JSON
    const data = Object.fromEntries(formData.entries());

    fetch('api/fees/assign_fee.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
        .then(res => res.json())
        .then(result => {
            if (result.status === 'success') {
                Swal.fire('Success!', 'Fee assigned to student.', 'success');
                form.reset();
            } else {
                Swal.fire('Error!', result.message, 'error');
            }
        })
        .catch(err => console.error('Error:', err));
}
// search , pagination and load assignFee 
// This triggers the initial load
document.addEventListener('DOMContentLoaded', function () {
    loadAssignedFees(1, ''); // Load page 1 with no search filter
});

// ===========load academic year id name =================
// 1. THIS RUNS AUTOMATICALLY ON PAGE LOAD
async function loadAcademicYears() {
    const yearDropdown = document.getElementById('feeFilterYear');
    if (!yearDropdown) return;

    try {
        const response = await fetch('api/settings/get_academic_years.php');
        const result = await response.json();

        if (result.status === 'success') {
            let options = '';

            result.data.forEach(year => {
                // Check 'is_current' from your PHP SQL to select the active year
                const isSelected = year.is_current == 1 ? 'selected' : '';
                options += `<option value="${year.id}" ${isSelected}>${year.year_name}</option>`;
            });

            yearDropdown.innerHTML = options;

            // IMPORTANT: After the dropdown is ready, load the fee table
            const currentSearch = document.getElementById('feeSearchInput').value;
            loadAssignedFees(1, currentSearch);
        }
    } catch (error) {
        console.error("Dropdown Error:", error);
        yearDropdown.innerHTML = '<option value="">Error loading years</option>';
    }
}

// Trigger this once when the page loads
document.addEventListener('DOMContentLoaded', loadAcademicYears);

// ... rest of your existing loadAssignedFees function follows here ...
let currentPage_fee = 1;

function loadAssignedFees(page = 1) {
    currentPage_fee = page;
    const tableBody = document.getElementById('assignedFeesList');

    // --- 1. COLLECT ALL FILTERS (REMOVED streamId) ---
    const searchVal = document.getElementById('feeSearchInput').value;
    const yearId = document.getElementById('feeFilterYear')?.value || '';
    const classId = document.getElementById('filter_class_id')?.value || '';
    const mediumId = document.getElementById('filter_medium_id')?.value || '';
    const rollNo = document.getElementById('filter_roll_no')?.value || '';

    // --- 2. CONSTRUCT URL (REMOVED stream_id) ---
    const params = new URLSearchParams({
        page: page,
        search: searchVal,
        year_id: yearId,
        class_id: classId,
        medium_id: mediumId,
        roll_no: rollNo
    });

    // --- 3. FETCH DATA ---
    fetch(`api/fees/get_assigned_fees.php?${params.toString()}`)
        .then(res => res.json())
        .then(result => {
            if (result.status === 'success') {
                let rows = '';
                result.data.forEach((item, index) => {
                    const totalAmount = parseFloat(item.total_amount || 0);
                    const balance = parseFloat(item.remaining_amount || 0);
                    const paidAmount = totalAmount - balance;
                    const status = (item.payment_status || 'unpaid').toLowerCase();

                    // --- Updated Badge Logic (REMOVED Stream Badge) ---
                    let classStreamDisplay = `
                        <div class="d-flex flex-column gap-1">
                            <span class="badge bg-info text-dark" style="font-size: 0.82rem; width: fit-content;">
                                <i class="fas fa-chalkboard"></i> ${item.class_name}
                                ${item.roll_no ? ` | Roll: ${item.roll_no}` : ''}
                            </span>
                            <div class="d-flex gap-1">
                                <span class="badge bg-light text-dark border" style="font-size: 0.72rem;">
                                    <i class="fas fa-language"></i> ${item.medium_name}
                                </span>
                            </div>
                        </div>`;

                    // Status UI Classes
                    let badgeClass = 'bg-danger';
                    let amountClass = 'text-danger fw-bold';

                    if (status === 'paid') {
                        badgeClass = 'bg-success';
                        amountClass = 'text-success';
                    } else if (['partially_paid', 'partial'].includes(status)) {
                        badgeClass = 'bg-warning text-dark';
                        amountClass = 'text-primary fw-bold';
                    }

                    // --- Action Buttons ---
                    let actionButtons = '';
                    if (status !== 'paid') {
                        actionButtons += `<button class="btn btn-sm btn-success" onclick="openBulkModal(${item.student_id})" title="Collect Fee">
                                            <i class="fas fa-money-bill-wave"></i> Pay
                                          </button>`;
                    }

                    if (paidAmount > 0) {
                        actionButtons += `<a href="print_receipt_duplicate.php?id=${item.id}" target="_blank" class="btn btn-sm btn-outline-primary" title="Print Receipt">
                                            <i class="fas fa-file-invoice"></i>
                                          </a>`;
                    }

                    const isDeletable = (status === 'unpaid');
                    const deleteOrLockBtn = isDeletable
                        ? `<button class="btn btn-sm btn-outline-danger" onclick="deleteAssignment(${item.id})" title="Delete">
                            <i class="fas fa-trash"></i>
                           </button>`
                        : `<button class="btn btn-sm btn-light text-muted" data-bs-toggle="tooltip" title="Financial records with payments are locked.">
                            <i class="fas fa-lock"></i>
                           </button>`;

                    rows += `
                    <tr>
                        <td class="text-muted small">${((page - 1) * 10) + (index + 1)}</td>
                        <td><div class="fw-bold text-uppercase" style="font-size:0.9rem;">${item.student_name}</div></td>
                        <td>${classStreamDisplay}</td>
                        <td><span class="small">${item.fee_title}</span></td>
                        <td class="${amountClass}">
                            <div style="font-size:0.9rem;">₹${totalAmount.toLocaleString('en-IN')}</div>
                            ${(paidAmount > 0 && status !== 'paid') ?
                            `<div style="font-size: 0.7rem; line-height:1.2;">
                                <span class="text-success">Paid: ₹${paidAmount.toLocaleString('en-IN')}</span><br>
                                <span class="text-danger">Due: ₹${balance.toLocaleString('en-IN')}</span>
                             </div>` : ''}
                        </td>
                        <td class="small">${item.due_date ? new Date(item.due_date).toLocaleDateString('en-IN') : '-'}</td>
                        <td class="small text-muted">${item.due_month}</td>
                        <td><span class="badge ${badgeClass}" style="font-size:0.7rem;">${status.toUpperCase()}</span></td>
                        <td>
                            <div class="d-flex gap-1">${actionButtons}${deleteOrLockBtn}</div>
                        </td>
                    </tr>`;
                });

                tableBody.innerHTML = rows || '<tr><td colspan="9" class="text-center p-4 text-muted">No assignments found matching these filters.</td></tr>';

                const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
                tooltipTriggerList.map(el => new bootstrap.Tooltip(el));

                renderPagination(result.pagination);
            }
        })
        .catch(err => console.error("Error loading fees:", err));
}

// 2. Update Pagination to use the correct ID
function renderPagination(pg) {
    const container = document.getElementById('paginationControls');
    if (!container) return;
    
    let html = '';

    if (pg.total_pages > 1) {
        html += '<div class="btn-group shadow-sm">';

        // Previous Button
        html += `<button class="btn btn-sm btn-outline-primary" 
                 ${pg.current_page === 1 ? 'disabled' : ''} 
                 onclick="loadAssignedFees(${pg.current_page - 1})">
                 <i class="fas fa-chevron-left"></i>
                 </button>`;

        // Page Numbers
        for (let i = 1; i <= pg.total_pages; i++) {
            // Optional: Logic to hide pages if total_pages is very large (e.g., > 10)
            html += `<button class="btn btn-sm ${i === pg.current_page ? 'btn-primary' : 'btn-outline-primary'}" 
                     onclick="loadAssignedFees(${i})">${i}</button>`;
        }

        // Next Button
        html += `<button class="btn btn-sm btn-outline-primary" 
                 ${pg.current_page === pg.total_pages ? 'disabled' : ''} 
                 onclick="loadAssignedFees(${pg.current_page + 1})">
                 <i class="fas fa-chevron-right"></i>
                 </button>`;

        html += '</div>';
    }
    
    container.innerHTML = html;
}

/**
 * Smart Debounce Listener
 * Handles Search and Roll Number inputs to prevent flickering
 */
let searchTimeout;
function triggerSmartReload() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => loadAssignedFees(1), 500);
}

// 1. Search Input Listener
document.getElementById('feeSearchInput').addEventListener('input', triggerSmartReload);

// 2. Roll Number Input Listener
const rollInput = document.getElementById('filter_roll_no');
if (rollInput) {
    rollInput.addEventListener('input', triggerSmartReload);
}

// 3. Year Dropdown Listener (Immediate)
const yearFilter = document.getElementById('feeFilterYear');
if (yearFilter) {
    yearFilter.addEventListener('change', () => loadAssignedFees(1));
}

/**
 * Handles the logic when the Class filter is changed.
 * Shows/Hides Stream dropdown smartly.
 */
function handleSmartFilterChange() {
    // Since we removed stream logic, we just trigger the data reload
    loadAssignedFees(1);
}

/**
 * Resets all filters to default state and reloads the table.
 */
function resetSmartFilters() {
    // 1. Identify existing filter elements
    const searchInput = document.getElementById('feeSearchInput');
    const classId = document.getElementById('filter_class_id');
    const mediumId = document.getElementById('filter_medium_id');
    const rollNo = document.getElementById('filter_roll_no');
    const yearId = document.getElementById('feeFilterYear');

    // 2. Clear values
    if (searchInput) searchInput.value = "";
    if (classId) classId.value = "";
    if (mediumId) mediumId.value = "";
    if (rollNo) rollNo.value = "";
    
    // Optional: Reset year to default if you use APP_YEAR_ID
    // if (yearId) yearId.value = ""; 

    // REMOVED: Stream ID and Stream Container logic

    // 3. Reload the list from page 1
    loadAssignedFees(1);
}
// --- INITIALIZE FILTERS ON PAGE LOAD ---
document.addEventListener('DOMContentLoaded', function () {
    // Fill Class Dropdown
    populateDropdown('api/classes/get_classes.php', 'filter_class_id');
    // Load the Table
    loadAssignedFees(1);
});

// delete assign fee if mistake 
function deleteAssignment(id) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This will remove the fee assignment for this student!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('api/fees/delete_assigned_fee.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: id })
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        Swal.fire('Deleted!', 'Assignment has been removed.', 'success');

                        // SMART REFRESH: 
                        // Just call the function with the current global page variable.
                        // It will automatically pick up the Search, Class, and Stream values.
                        loadAssignedFees(currentPage_fee);
                    } else {
                        Swal.fire('Error!', data.message, 'error');
                    }
                })
                .catch(err => {
                    console.error("Delete Error:", err);
                    Swal.fire('Error!', 'Could not connect to the server.', 'error');
                });
        }
    });
}
 

// ================collect payment ===================
// 1. Function to open the modal and fill data
function openBulkModal(studentId) {
    const yearDropdown = document.getElementById('feeFilterYear');
    if (!yearDropdown) {
        console.error("Year dropdown not found!");
        return;
    }

    const selectedYearId = yearDropdown.value;
    const selectedYearText = yearDropdown.options[yearDropdown.selectedIndex].text;

    const modalLabel = document.getElementById('paymentModalLabel');
    if (modalLabel) {
        modalLabel.innerHTML = `Collect Fees - <span class="text-white">${selectedYearText}</span>`;
    }

    fetch(`api/fees/get_student_summary.php?student_id=${studentId}&year_id=${selectedYearId}`)
        .then(res => res.json())
        .then(result => {
            if (result.status === 'error') {
                alert(result.message);
                return;
            }

            const s = result.student;

            // --- STUDENT INFO DISPLAY ---
            document.getElementById('info_name').innerText = s.student_name;
            document.getElementById('info_father').innerText = s.father_name;
            document.getElementById('info_roll').innerText = s.roll_no;

            // SMART CLASS, SECTION, & MEDIUM DISPLAY (Stream Removed)
            let classDetails = s.class_name;
            
            if (s.section_name) {
                classDetails += ` (${s.section_name})`;
            }
            
            // Show Medium (e.g., [English])
            if (s.medium_name) {
                classDetails += ` [${s.medium_name}]`;
            }

            // REMOVED: stream_name display logic

            const classInfoEl = document.getElementById('info_class');
            if (classInfoEl) {
                classInfoEl.innerText = classDetails;
            }

            // --- TABLE ROWS LOGIC ---
            let rows = '';
            if (!result.pending_fees || result.pending_fees.length === 0) {
                rows = `<tr><td colspan="3" class="text-center text-muted p-4">No pending fees for this year.</td></tr>`;
            } else {
                result.pending_fees.forEach(fee => {
                    const balance = parseFloat(fee.remaining_amount || 0);
                    rows += `
                    <tr>
                        <td class="text-center align-middle">
                            <input type="checkbox" class="fee-checkbox" data-id="${fee.id}" onchange="updateTotal()" checked>
                        </td>
                        <td class="align-middle">
                            <strong>${fee.fee_title}</strong><br>
                            <small class="text-muted">${fee.due_month || ''}</small>
                        </td>
                        <td>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">₹</span>
                                <input type="number" 
                                       class="form-control pay-amount-input" 
                                       data-id="${fee.id}" 
                                       value="${balance}" 
                                       max="${balance}" 
                                       oninput="validateAndTotal(this)">
                            </div>
                            <small class="text-danger" style="font-size: 0.7rem;">Balance: ₹${balance}</small>
                        </td>
                    </tr>`;
                });
            }
            document.getElementById('pending_fees_table').innerHTML = rows;

            // --- RESET FIELDS ---
            if (document.getElementById('payment_remarks')) document.getElementById('payment_remarks').value = '';
            if (document.getElementById('discount_percent')) document.getElementById('discount_percent').value = '';

            updateTotal();

            const modalEl = document.getElementById('paymentModal');
            const modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
            modalInstance.show();
        })
        .catch(err => {
            console.error("Error:", err);
            alert("Failed to load details.");
        });
}


function validateAndTotal(input) {
    const max = parseFloat(input.getAttribute('max'));
    let val = parseFloat(input.value);

    if (val > max) {
        input.value = max;
        alert("Amount cannot exceed the balance of ₹" + max);
    }
    updateTotal();
}

function updateTotal() {
    let subTotal = 0;

    // 1. Sum up selected fee rows
    document.querySelectorAll('.fee-checkbox:checked').forEach(cb => {
        const feeId = cb.dataset.id;
        const amountInput = document.querySelector(`.pay-amount-input[data-id="${feeId}"]`);
        if (amountInput) {
            subTotal += parseFloat(amountInput.value || 0);
        }
    });

    // 2. Get Discount Percentage
    const discountInput = document.getElementById('discount_percent');
    const discountPercent = parseFloat(discountInput.value) || 0;

    // 3. Calculate Math
    const discountAmount = (subTotal * discountPercent) / 100;
    const finalAmount = subTotal - discountAmount;

    // 4. Update UI Elements
    if (document.getElementById('original_total')) {
        document.getElementById('original_total').innerText = "₹" + subTotal.toLocaleString('en-IN', { minimumFractionDigits: 2 });
    }

    if (document.getElementById('discount_amount_display')) {
        document.getElementById('discount_amount_display').innerText = "₹" + discountAmount.toLocaleString('en-IN', { minimumFractionDigits: 2 });
    }

    document.getElementById('grand_total').innerText = "₹" + finalAmount.toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

//Ensure typing in the discount field triggers the update
document.addEventListener('DOMContentLoaded', function () {
    const discField = document.getElementById('discount_percent');
    if (discField) {
        discField.addEventListener('input', updateTotal);
    }
});


//=======================fee payment submision================= 
document.getElementById('bulkPaymentForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const checkedCheckboxes = document.querySelectorAll('.fee-checkbox:checked');

    if (checkedCheckboxes.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'No Selection',
            text: 'Please select at least one fee to pay.',
            confirmButtonColor: '#3085d6'
        });
        return;
    }

    // Show a "Processing" loader
    Swal.fire({
        title: 'Processing Payment...',
        text: 'Please wait while we update the records.',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    const paymentData = [];
    let subTotal = 0; // To track original amount

    checkedCheckboxes.forEach(cb => {
        const feeId = cb.dataset.id;
        const amountInput = document.querySelector(`.pay-amount-input[data-id="${feeId}"]`);

        if (amountInput) {
            const val = parseFloat(amountInput.value || 0);
            subTotal += val;
            paymentData.push({
                fee_id: feeId,
                amount: val
            });
        }
    });

    // --- NEW: Calculate the discount and final amount for the payload ---
    const discountPercent = parseFloat(document.getElementById('discount_percent').value) || 0;
    const discountAmount = (subTotal * discountPercent) / 100;
    const finalTotal = subTotal - discountAmount;

    const payload = {
        payments: paymentData,
        payment_mode: document.getElementById('bulk_payment_mode').value,
        remarks: document.getElementById('payment_remarks').value,
        // --- ADDED THESE NEW FIELDS ---
        discount_percent: discountPercent,
        discount_value: discountAmount,
        final_total_amount: finalTotal
    };

    fetch('api/fees/collect_bulk_payment.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
        .then(res => res.json())
        .then(result => {
            if (result.status === 'success') {
                const selectedYearId = document.getElementById('feeFilterYear').value;
                Swal.fire({
                    icon: 'success',
                    title: 'Payment Successful!',
                    text: 'The transaction has been recorded.',
                    showConfirmButton: true,
                    confirmButtonText: '<i class="fas fa-print"></i> Print Receipt',
                    showCancelButton: true,
                    cancelButtonText: 'Close',
                    confirmButtonColor: '#28a745'
                }).then((choice) => {
                    if (choice.isConfirmed) {
                        const receiptUrl = `print_receipt.php?receipt_no=${result.receipt_no}&year_id=${selectedYearId}`;
                        window.open(receiptUrl, '_blank');
                    }
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Transaction Failed',
                    text: result.message
                });
            }
        })
        .catch(err => {
            console.error("Submission Error:", err);
            Swal.fire({
                icon: 'error',
                title: 'System Error',
                text: 'Could not connect to the server.'
            });
        });
});

//---------------- fee defaulter loaded started ---------------------------

// Unique global state to prevent interference with other scripts
// let defBoard_CurrentPage = 1;

//---------------- fee defaulter loaded started --------------------------- 
