function fetchStudents() {
    fetch('api/fees/get_students.php')  // Fetch students from the PHP backend
        .then(response => response.json())
        .then(res => {
            if (res.status === 'success') {
                const studentSelectElement = document.getElementById('get_student_id');
                res.data.forEach(student => {
                    studentSelectElement.innerHTML += `<option value="${student.id}">${student.student_name}</option>`;
                });
            } else {
                Swal.fire('Error!', 'Failed to load students.', 'error');
            }
        })
        .catch(error => {
            Swal.fire('Error!', 'Error fetching student data.', 'error');
        });
}

// Function to load fee types from the database
function fetchFeeTypes() {
    fetch('api/fees/get_fee_types.php')  // Fetch fee types from the PHP backend
        .then(response => response.json())
        .then(result => {
            if (result.status === 'success') {
                const feeSelectElement = document.getElementById('fee_type_id');
                result.data.forEach(get_fee => {
                    feeSelectElement.innerHTML += `<option value="${get_fee.id}">${get_fee.fee_title}</option>`;
                });
            } else {
                Swal.fire('Error!', 'Failed to load fee types.', 'error');
            }
        })
        .catch(error => {
            console.error(error);

            Swal.fire('Error!', 'Error fetching fee types.', 'error');
        });
}

// Function to update the amount when a fee type is selected
document.getElementById('fee_type_id').addEventListener('change', function() {
    const selectedFeeTypeId = this.value;

    if (!selectedFeeTypeId) {
        Swal.fire('Error!', 'Please select a fee type.', 'error');
        return;
    }

    // Fetch fee type amount from the backend (API call)
    fetch(`api/fees/get_fee_amount.php?id=${selectedFeeTypeId}`)
        .then(response => response.json())
        .then(data_get => {
            if (data_get.status === 'success') {
                document.getElementById('fee_amount').value = data_get.data.amount;
            } else {
                Swal.fire('Error!', 'Failed to fetch fee amount. Please try again later.', 'error');
            }
        })
        .catch(error => {
            console.error(error);
            Swal.fire('Error!', 'There was an issue fetching the fee amount. Please try again.', 'error');
        });
});

// Function to assign fee to student
function submitFeeAssignment() {
    const formData = new FormData(document.getElementById('feeAssignmentForm'));

    fetch('api/fees/assign_fee.php', {  // Make sure your backend PHP script path is correct
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(asign_data => {
        if (asign_data.status === 'success') {
            Swal.fire('Success!', asign_data.message, 'success');
            document.getElementById('feeAssignmentForm').reset();  // Reset the form
        } else {
            Swal.fire('Error!', asign_data.message, 'error');
        }
    })
    .catch(error => {
        Swal.fire('Error!', 'There was an error assigning the fee.', 'error');
    });
}

// Load students and fee types when the page loads
window.onload = function() {
    fetchStudents();
    fetchFeeTypes();
};





// Unique global variable to hold the chart instance
let finRep_ChartObject = null;

async function finRep_FetchAndDraw() {
    // console.log("1. Starting Unique Fetch Process...");
    
    const finRep_MonthEl = document.getElementById('monthInputFianancial');
    if (!finRep_MonthEl) {
        console.error("ERROR: Could not find HTML element with ID 'monthInputFianancial'");
        return;
    }

    const finRep_SelectedMonth = finRep_MonthEl.value;
    // console.log("2. Selected Month Value:", finRep_SelectedMonth);

    // Unique URL Construction with cache buster
    const finRep_TargetUrl = `http://localhost/LMS/Admin/api/financialReport/api_financial_summary.php?month=${finRep_SelectedMonth}&t=${new Date().getTime()}`;

    try {
        const finRep_ResponseObj = await fetch(finRep_TargetUrl);
        
        if (!finRep_ResponseObj.ok) {
            throw new Error(`HTTP Error Status: ${finRep_ResponseObj.status}`);
        }

        // Renamed 'result' to 'finRep_JsonResult'
        const finRep_JsonResult = await finRep_ResponseObj.json();
        // console.log("3. Unique API Data Received:", finRep_JsonResult);

        if (finRep_JsonResult.success && finRep_JsonResult.totals) {
            // Renamed 'data' to 'finRep_FinalData'
            const finRep_FinalData = finRep_JsonResult.totals;

            // Target HTML Elements
            const finRep_ExpEl = document.getElementById('finRep_StatExpected');
            const finRep_ColEl = document.getElementById('finRep_StatCollected');
            const finRep_PenEl = document.getElementById('finRep_StatPending');

            // Updating Text - Using unique variable references
            if (finRep_ExpEl) {
                finRep_ExpEl.innerText = "₹" + Number(finRep_FinalData.expected).toLocaleString('en-IN', { minimumFractionDigits: 2 });
                // console.log("4a. Updated Expected Card");
            }
            if (finRep_ColEl) {
                finRep_ColEl.innerText = "₹" + Number(finRep_FinalData.collected).toLocaleString('en-IN', { minimumFractionDigits: 2 });
                // console.log("4b. Updated Collected Card");
            }
            if (finRep_PenEl) {
                finRep_PenEl.innerText = "₹" + Number(finRep_FinalData.pending).toLocaleString('en-IN', { minimumFractionDigits: 2 });
                // console.log("4c. Updated Pending Card");
            }

            // Draw Chart using renamed parameters
            finRep_DrawChart(finRep_FinalData.collected, finRep_FinalData.pending);
        } else {
            console.error("5. API Success false or data missing:", finRep_JsonResult);
        }
    } catch (finRep_CatchError) {
        console.error("6. Unique Script Critical Failure:", finRep_CatchError.message);
    }
}

function finRep_DrawChart(finRep_PaidVal, finRep_UnpaidVal) {
    const finRep_CanvasObj = document.getElementById('finRep_ChartCanvas');
    if (!finRep_CanvasObj) {
        // console.error("ERROR: Canvas 'finRep_ChartCanvas' not found.");
        return;
    }
    
    const finRep_Ctx = finRep_CanvasObj.getContext('2d');
    
    // Clean up old chart instance
    if (finRep_ChartObject) { 
        finRep_ChartObject.destroy(); 
    }

    console.log("7. Rendering Chart - Paid:", finRep_PaidVal, "Pending:", finRep_UnpaidVal);

    finRep_ChartObject = new Chart(finRep_Ctx, {
        type: 'doughnut',
        data: {
            labels: ['Collected', 'Pending'],
            datasets: [{
                data: [finRep_PaidVal, finRep_UnpaidVal],
                backgroundColor: ['#198754', '#dc3545'],
                borderWidth: 0
            }]
        },
        options: {
            maintainAspectRatio: false,
            cutout: '80%',
            plugins: { 
                legend: { position: 'bottom' } 
            }
        }
    });
}

// Logic to initialize only when window and IDs are ready
window.addEventListener('load', () => {
    // console.log("0. Dashboard Page Fully Loaded");
    
    // Initial Load trigger
    finRep_FetchAndDraw();

    // Listen for Change on the specific ID
    const finRep_MonthInputObj = document.getElementById('monthInputFianancial');
    if (finRep_MonthInputObj) {
        finRep_MonthInputObj.addEventListener('change', finRep_FetchAndDraw);
    }
});