//========================= load academic year session =================================
async function loadSessionSwitcher() {
    const sessionSelect = document.getElementById('session_switcher');
    
    try {
        // Update the path to match your API location
        const response = await fetch('api/academic/get_academic_years.php');
        const years = await response.json();

        if (Array.isArray(years) && years.length > 0) {
            let options = '';
            
            years.forEach(year => {
                // If is_current is 1, we mark it as selected
                const isSelected = year.is_current == 1 ? 'selected' : '';
                options += `<option value="${year.id}" ${isSelected}>${year.year_name}</option>`;
            });

            sessionSelect.innerHTML = options;
            
            // After loading the years, fetch the list for the currently selected year
            if (typeof fetchStudentList === "function") {
                fetchStudentList();
            }
        }
    } catch (err) {
        console.error("Error loading academic years:", err);
    }
}

// Call this function when the page loads
document.addEventListener('DOMContentLoaded', loadSessionSwitcher);
/**
 * Safe function to populate Class Dropdown
 * Prevents: TypeError: Cannot set properties of null
 */
async function loadMediumFilters() {
    try {
        const res = await fetch('api/mediums/get_mediums.php');
        const result = await res.json();

        if (result.status) {
            const filterSelect = document.getElementById('filter_medium');
            result.data.forEach(m => {
                const opt = document.createElement('option');
                opt.value = m.id;
                opt.textContent = m.medium_name;
                filterSelect.appendChild(opt);
            });
        }
    } catch (err) {
        console.error("Error loading medium filters:", err);
    }
}
async function fetchClassList() {
    const classDropdown = document.getElementById('class_id');

    // CRITICAL FIX: If the element doesn't exist on this page, STOP HERE.
    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();

        let html = '<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>';
        }

        // Safe assignment
        classDropdown.innerHTML = html;

    } catch (error) {
        console.error('Error loading classes:', error);
        if (classDropdown) {
            classDropdown.innerHTML = '<option value="">Error loading data</option>';
        }
    }
}

// Run the check when the page is ready
document.addEventListener('DOMContentLoaded', () => {
    fetchClassList();
    loadMediumFilters();
});
function initClassDropdown() {
    const classFilter = document.getElementById('classFilter');

    fetch('api/classes/get_classes.php')
        .then(res => res.json())
        .then(data => {
            let options = '<option value="">All Classes</option>';
            data.forEach(item => {
                options += `<option value="${item.id}">${item.class_name}</option>`;
            });
            classFilter.innerHTML = options;
        })
        .catch(err => console.error("Error loading classes:", err));
}

// Call this once when the page loads
initClassDropdown();
// ===========section list call==============
async function loadSectionFilters(classId = '') {
    const filterDropdown = document.getElementById('filter_section');
    if (!filterDropdown) return;

    // Build URL: if classId is provided, filter the dropdown options
    const url = classId ? `api/sections/get_sections_by_class.php?class_id=${classId}` : 'api/sections/get_all_sections.php';

    try {
        const res = await fetch(url);
        const result = await res.json();

        filterDropdown.innerHTML = '<option value="">All Sections</option>';

        if (result.status === 'success' && result.data) {
            result.data.forEach(sec => {
                filterDropdown.innerHTML += `<option value="${sec.id}">${sec.section_name}</option>`;
            });
        }
    } catch (err) {
        console.error("Filter sync error", err);
    }
}

// Bind this to your class filter change
document.getElementById('classFilter')?.addEventListener('change', (e) => {
    loadSectionFilters(e.target.value);
    fetchStudentList(); // Refresh table too
});
// Call this when the page loads
loadSectionFilters();

let stu_current_page = 1;
let current_student_data = null; // Stores data for PDF
function fetchStudentList() {
    const classId = document.getElementById('classFilter').value;
    const mediumId = document.getElementById('filter_medium').value;
    // UPDATE: Getting the section_id from the dropdown instead of a string name
    const sectionId = document.getElementById('filter_section').value;

    const searchTerm = document.getElementById('studentSearch').value;
    const yearId = document.getElementById('session_switcher')?.value || '';
    const tableBody = document.getElementById('studentTableBody');

    tableBody.innerHTML = '<tr><td colspan="6" class="text-center">Loading Students...</td></tr>';

    // UPDATE: Changed the URL parameter from 'section' to 'section_id'
    fetch(`api/students/get_students.php?stu_page=${stu_current_page}&class_id=${classId}&medium_id=${mediumId}&section_id=${sectionId}&search=${searchTerm}&year_id=${yearId}`)
        .then(res => res.json())
        .then(res => {
            if (res.status) {
                let rows = '';
                if (res.data.length === 0) {
                    rows = '<tr><td colspan="6" class="text-center text-muted">No students found.</td></tr>';
                } else {
                    res.data.forEach(s => {
                     
                        const img = s.student_photo ? `uploads/students/${s.student_photo}` : 'assets/img/default.png';

                        let status = (s.promotion_status || 'active');
                        let badgeClass = 'bg-success';
                        if (status === 'dropped') {
                            badgeClass = 'bg-danger';
                        } else if (status === 'promoted') {
                            badgeClass = 'bg-info text-dark';
                        } else if (status === 'failed') {
                            badgeClass = 'bg-warning text-dark';
                        } else if (status === 'active') {
                            badgeClass = 'bg-success';
                        } else {
                            badgeClass = 'bg-secondary';
                        }

                        rows += `
                    <tr>
                        <td><strong>${s.roll_no}</strong></td>
                        <td><img src="${img}" width="35" class="rounded-circle"></td>
                        <td>${s.student_name}</td>
                        
                        <td><span class="fw-bold">${s.class_name}</span> 
                            ${s.section_name ? `<span class="badge bg-secondary ms-1">${s.section_name}</span>` : ''}
                            <span class="badge border text-dark bg-light">
                                <i class="fas fa-language text-muted me-1"></i>${s.medium_name || 'N/A'}
                            </span></td>
                                      <td>${s.parent_phone}</td>
                        <td>
                        
                        <div class="dropdown">
                            <button class="btn btn-sm border-0 p-0 dropdown-toggle shadow-none" type="button" data-bs-toggle="dropdown">
                                <span class="badge ${badgeClass}">${status.toUpperCase()}</span>
                            </button>
                            <ul class="dropdown-menu shadow border-0 animated--fade-in">
                                <li><h6 class="dropdown-header">Update Status</h6></li>
                                <li><a class="dropdown-item text-success" href="#" onclick="updateStatus(${s.enrollment_id}, 'active')"><i class="fas fa-check-circle me-2"></i> Active</a></li>
                                <li><a class="dropdown-item text-info" href="#" onclick="updateStatus(${s.enrollment_id}, 'promoted')"><i class="fas fa-arrow-up me-2"></i> Promoted</a></li>
                                <li><a class="dropdown-item text-warning" href="#" onclick="updateStatus(${s.enrollment_id}, 'failed')"><i class="fas fa-exclamation-triangle me-2"></i> Failed</a></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="updateStatus(${s.enrollment_id}, 'dropped')"><i class="fas fa-times-circle me-2"></i> Dropped</a></li>
                            </ul>
                        </div>
                    </td>
                        <td class="text-center">
                           <div class="btn-group ">
                            <button onclick="viewStudent(${s.id})" class="btn btn-sm btn-info text-white"><i class="fas fa-eye"></i></button>
                            
                            <button onclick="loadStudentEdit(${s.id})" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></i></button>
                           </div>
                        </td>
                    </tr>`;
                    });
                }
                tableBody.innerHTML = rows;

                document.getElementById('stu_current_page_text').innerText = res.curr_page;
                document.getElementById('stu_total_pages_text').innerText = res.total_pages;

                document.getElementById('stu_prev_btn').disabled = (res.curr_page <= 1);
                document.getElementById('stu_next_btn').disabled = (res.curr_page >= res.total_pages);
            }
        });
}

// Navigation Function
function changeStuPage(direction) {
    stu_current_page += direction;
    fetchStudentList();
}

/* --- Event Listeners --- */
// 3. If Medium changes, reset to page 1 and reload
document.getElementById('filter_medium').addEventListener('change', () => {
    stu_current_page = 1;
    fetchStudentList();
});
// 1. If Class changes, reset to page 1 and reload
document.getElementById('classFilter').addEventListener('change', () => {
    stu_current_page = 1;
    fetchStudentList();
});

// 2. If Search changes, reset to page 1 and reload
document.getElementById('studentSearch').addEventListener('input', () => {
    stu_current_page = 1;
    fetchStudentList();
});

// Initialize on Load
initClassDropdown();
fetchStudentList();


// ============student active,promoted, failed, dropout toggler=============
/**
 * Updates the promotion status of a student using AJAX and SweetAlert2
//  *  The ENUM value ('active', 'promoted', 'failed', 'dropped')
 */
function updateStatus(enrollmentId, newStatus) {

    if (!enrollmentId) {
        Swal.fire('Error', 'ID is missing!', 'error');
        return;
    }
    Swal.fire({
        title: 'Change Status?',
        text: `Are you sure you want to set this student to ${newStatus.toUpperCase()}?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, update it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {

            // Show a "Processing" loader
            Swal.fire({
                title: 'Updating...',
                allowOutsideClick: false,
                didOpen: () => { Swal.showLoading(); }
            });

            // AJAX Request to your PHP handler
            fetch('api/students/update_enrollment_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `id=${enrollmentId}&status=${newStatus}`
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: 'Student status updated successfully.',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {

                            // IMPORTANT: Change 'fetchStudentList' to match YOUR function name exactly
                            if (typeof fetchStudentList === "function") {

                                fetchStudentList();
                            } else {
                                console.log("Function fetchStudentList not found! Reloading page instead.");
                                location.reload();
                            }
                        });
                    } else {
                        Swal.fire('Error!', data.message || 'Could not update status.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'System error occurred.', 'error');
                });
        }
    });
}


// ==============================load student edit ===============================
async function loadStudentEdit(id) {
    try {
        // 1. Fetch data in parallel (Removed streamsRes)
        const [studentRes, classesRes, mediumsRes] = await Promise.all([
            fetch(`api/students/student_single_api.php?id=${id}`),
            fetch(`api/students/classes_list_api.php`),
            fetch(`api/mediums/get_mediums.php`)
        ]);

        const data = await studentRes.json();
        const classes = await classesRes.json();
        const mediumsData = await mediumsRes.json();
        const mediums = mediumsData.status ? mediumsData.data : [];

        if (!data || data.status === false) {
            throw new Error(data.message || "Failed to load student data");
        }

        const today = new Date().toISOString().split('T')[0];

        Swal.fire({
            title: 'Edit Student Information',
            width: '800px',
            html: `
                <form id="studentEditForm" class="text-start container-fluid">
                    <input type="hidden" id="student_edit_id" value="${data.id}">
                    <input type="hidden" id="student_edit_academic_year" value="${data.academic_year_id || data.academic_year}">
                    
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase">Student Name</label>
                            <input type="text" id="student_edit_name" class="form-control" value="${data.student_name || ''}">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase">Class</label>
                            <select id="student_edit_class" class="form-select" onchange="handleEditClassChange(this)">
                                ${classes.map(cls => `
                                    <option value="${cls.id}" ${String(cls.id) === String(data.class_id) ? 'selected' : ''}>
                                        ${cls.class_name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-md-12">
                            <label class="form-label fw-bold small text-uppercase">Medium <span class="text-danger">*</span></label>
                            <select id="student_edit_medium_id" class="form-select">
                                <option value="">-- Choose Medium --</option>
                                ${mediums.map(m => `
                                    <option value="${m.id}" ${String(m.id) === String(data.medium_id) ? 'selected' : ''}>
                                        ${m.medium_name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Roll No</label>
                            <input type="text" id="student_edit_roll" class="form-control" value="${data.roll_no || ''}">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Section</label>
                            <select id="student_edit_section_id" class="form-select">
                                <option value="">Loading...</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Gender</label>
                            <select id="student_edit_gender" class="form-select">
                                <option value="Male" ${data.gender === 'Male' ? 'selected' : ''}>Male</option>
                                <option value="Female" ${data.gender === 'Female' ? 'selected' : ''}>Female</option>
                                <option value="Other" ${data.gender === 'Other' ? 'selected' : ''}>Other</option>
                            </select>
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase">Father's Name</label>
                            <input type="text" id="student_edit_father" class="form-control" value="${data.father_name || ''}">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small text-uppercase">Mother's Name</label>
                            <input type="text" id="student_edit_mother" class="form-control" value="${data.mother_name || ''}">
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Parent Phone</label>
                            <input type="text" id="student_edit_phone" class="form-control" value="${data.parent_phone || ''}" oninput="this.value = this.value.replace(/\\D/g,'').slice(0,10)">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Date of Birth</label>
                            <input type="date" id="student_edit_dob" class="form-control" value="${data.dob}" max="${today}">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold small text-uppercase">Admission Date</label>
                            <input type="date" id="student_edit_admission_date" class="form-control" value="${data.admission_date}">
                        </div>
                    </div>

                    <div class="row g-3 mt-1">
                        <div class="col-md-12">
                            <label class="form-label fw-bold small text-uppercase">Address</label>
                            <textarea id="student_edit_address" class="form-control" rows="2">${data.address || ''}</textarea>
                        </div>
                    </div>

                    <hr>

                    <div class="row align-items-center bg-light p-2 rounded">
                        <div class="col-md-8">
                            <label class="form-label fw-bold small text-uppercase">Update Photo (Optional)</label>
                            <input type="file" id="student_edit_photo" class="form-control" accept="image/*">
                        </div>
                        <div class="col-md-4 text-center border-start">
                             <img src="uploads/students/${data.student_photo || 'default.png'}" class="img-thumbnail" style="height: 60px;">
                        </div>
                    </div>
                </form>
            `,
            didOpen: () => {
                setTimeout(() => {
                    // 1. Load Sections
                    loadSectionsForEdit(data.class_id, data.section_id);
                }, 100);
            },
            confirmButtonText: '<i class="fa fa-save"></i> Update Student',
            showCancelButton: true,
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                const formData = new FormData();

                // Validation
                const name = document.getElementById("student_edit_name").value;
                const mediumVal = document.getElementById('student_edit_medium_id').value;

                if (!name) return Swal.showValidationMessage("Name is required");
                if (!mediumVal) return Swal.showValidationMessage("Please select a medium");

                // Append Data (Stream removed)
                formData.append("id", document.getElementById("student_edit_id").value);
                formData.append("student_name", name);
                formData.append("class_id", document.getElementById("student_edit_class").value);
                formData.append("medium_id", mediumVal);
                formData.append("section_id", document.getElementById("student_edit_section_id").value);
                formData.append("father_name", document.getElementById("student_edit_father").value);
                formData.append("mother_name", document.getElementById("student_edit_mother").value);
                formData.append("academic_year", document.getElementById("student_edit_academic_year").value);
                formData.append("roll", document.getElementById("student_edit_roll").value);
                formData.append("phone", document.getElementById("student_edit_phone").value);
                formData.append("dob", document.getElementById("student_edit_dob").value);
                formData.append("admission_date", document.getElementById("student_edit_admission_date").value);
                formData.append("gender", document.getElementById("student_edit_gender").value);
                formData.append("address", document.getElementById("student_edit_address").value);

                const photo = document.getElementById("student_edit_photo").files[0];
                if (photo) formData.append("student_photo", photo);

                return fetch("api/students/update_student.php", { method: "POST", body: formData })
                    .then(res => res.json())
                    .then(res => { if (!res.success) throw new Error(res.message); return res; })
                    .catch(err => Swal.showValidationMessage(err.message));
            }
        }).then(result => {
            if (result.isConfirmed) {
                Swal.fire('Updated!', '', 'success');
                if (window.fetchStudentList) fetchStudentList();
            }
        });

    } catch (err) {
        Swal.fire("Error", err.message, "error");
    }
}
/** * Keep this in the global scope so the HTML 'onchange' can find it
 */
function handleEditClassChange(selectElement) {
    const classId = selectElement.value;
    
    // Update sections based on the new class
    // We pass null for the second argument so the section dropdown resets
    loadSectionsForEdit(classId, null);

    // Stream logic has been removed to prevent "Cannot read properties of null" errors
    // as the stream_container no longer exists in the DOM.
}
async function loadSectionsForEdit(classId, selectedSectionId = null) {
    const sectionSelect = document.getElementById('student_edit_section_id');
    if (!sectionSelect) return;

    try {
        const res = await fetch(`api/sections/get_sections_by_class.php?class_id=${classId}`);
        const result = await res.json();

        if (result.status === 'success' && result.data.length > 0) {
            let options = '<option value="">-- Choose Section --</option>';
            result.data.forEach(sec => {
                // Use non-strict equality to handle string vs number
                const isSelected = String(sec.id) == String(selectedSectionId) ? 'selected' : '';
                options += `<option value="${sec.id}" ${isSelected}>${sec.section_name}</option>`;
            });
            sectionSelect.innerHTML = options;

            // Critical: Forced re-selection
            if (selectedSectionId) {
                sectionSelect.value = selectedSectionId;
            }
        } else {
            sectionSelect.innerHTML = '<option value="">NA</option>';
        }
    } catch (err) {
        sectionSelect.innerHTML = '<option value="">Error</option>';
    }
}


// view single student profile details 
function viewStudent(id) {
    const content = document.getElementById('viewStudentContent');
    content.innerHTML = '<div class="text-center p-5"><div class="spinner-border text-primary"></div></div>';

    // Show the modal
    const viewModal = new bootstrap.Modal(document.getElementById('viewStudentModal'));
    viewModal.show();

    fetch(`api/students/get_student_details.php?id=${id}`)
        .then(res => res.json())
        .then(res => {
            if (res.status) {
                current_student_data = res.data; // Store globally
                const s = res.data;
                const photo = s.student_photo ? `uploads/students/${s.student_photo}` : 'assets/img/default-avatar.png';

                content.innerHTML = `
                <div class="row">
                    <div class="col-md-4 text-center border-end">
            <img src="${photo}" class="img-fluid rounded mb-3 border" style="max-height: 200px;">
            <h4>${s.student_name}</h4>
            <div class="mb-2">
                <span class="badge bg-primary">
                    ${s.class_name} ${s.section_name ? '| Section: ' + s.section_name : ''}
                </span>
                ${s.stream_name && s.stream_name !== 'N/A' ? `<span class="badge bg-info text-dark">Stream: ${s.stream_name}</span>` : ''}
            </div>
            <div class="mt-1">
                                <span class="badge outline-badge-secondary text-secondary border border-secondary">
                                    <i class="fas fa-language"></i> Medium: ${s.medium_name || 'N/A'}
                                </span>
                            </div>
            <span class="badge bg-secondary mb-2">Roll No: ${s.roll_no}</span>
        </div>
                    <div class="col-md-8">
                        <table class="table table-sm table-borderless">
                            <tr><th width="40%">Father's Name:</th><td>${s.father_name}</td></tr>
                            <tr><th>Mother's Name:</th><td>${s.mother_name || 'N/A'}</td></tr>
                            <tr><th>Gender:</th><td>${s.gender}</td></tr>
                            <tr><th>Date of Birth:</th><td>${s.dob}</td></tr>
                            <tr><th>Phone:</th><td>${s.parent_phone}</td></tr>
                            <tr><th>Address:</th><td>${s.address}</td></tr>
                            <tr><th>Admission Date:</th><td>${s.admission_date}</td></tr>
                            <tr><th>Current Session:</th><td><span class="text-success">${s.year_name}</span></td></tr>
                        </table>
                    </div>
                </div>
            `;
            } else {
                content.innerHTML = `<div class="alert alert-danger">${res.msg}</div>`;
            }
        })
        .catch(err => {
            content.innerHTML = `<div class="alert alert-danger">Error loading data.</div>`;
        });
}
// ==========for pdf download student details =============

// ================expot to excel ============
function exportToExcel() {
    const classId = document.getElementById('classFilter').value;
    const sections = document.getElementById('filter_section').value;
    const searchs = document.getElementById('studentSearch').value;

    // Create a download URL with current filters
    const url = `api/students/export_students.php?search=${searchs}&section=${sections}&class_id=${classId}`;

    // Trigger download
    window.location.href = url;
}

// ================student profile download =============
function downloadStudentPDF() {
    if (!current_student_data) return;

    const s = current_student_data;
    const buffer = document.getElementById('pdf-buffer');
    const photo = s.student_photo ? s.student_photo : 'assets/img/default.png';

    // Generate a clean HTML structure inside the buffer
    buffer.innerHTML = `
        <div style="padding: 30px; border: 5px solid #1a73e8;">
            <div style="text-align: center; border-bottom: 2px solid #eee; padding-bottom: 10px;">
                <h1 style="color: #1a73e8; margin: 0;">OFFICIAL STUDENT PROFILE</h1>
                <p>Academic Session: ${s.year_name}</p>
            </div>
            <table width="100%" style="margin-top: 20px;">
                <tr>
                    <td width="70%" style="vertical-align: top;">
                        <p><strong>Full Name:</strong> ${s.student_name}</p>
                        <p><strong>Class:</strong> ${s.class_name}</p>
                        <p><strong>Roll No:</strong> ${s.roll_no}</p>
                        <p><strong>Father's Name:</strong> ${s.father_name}</p>
                        <p><strong>DOB:</strong> ${s.dob}</p>
                        <p><strong>Phone:</strong> ${s.parent_phone}</p>
                        <p><strong>Address:</strong> ${s.address}</p>
                    </td>
                    <td width="30%" align="right" style="vertical-align: top;">
                        <img src="${photo}" style="width: 150px; border: 1px solid #ddd; padding: 5px;">
                    </td>
                </tr>
            </table>
        </div>`;

    const opt = {
        margin: 10,
        filename: `${s.student_name}_Profile.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };

    html2pdf().set(opt).from(buffer).save().then(() => {
        buffer.innerHTML = ''; // Clear after finish
    });
}

//================populate promotion field promotion start  =================
async function populatePromotionModal() {
    try {
        const fromClass = document.getElementById('promote_from_class');
        const toClass = document.getElementById('promote_to_class');
        const yearDropdown = document.getElementById('next_academic_year');

        // 1. Initial Data Fetch
        const [classRes, yearRes] = await Promise.all([
            fetch('api/classes/get_classes.php'),
            fetch('api/academic/get_academic_years.php')
        ]);

        const classes = await classRes.json();
        const years = await yearRes.json();

        // 2. Populate Class Dropdowns
        let classOptions = '<option value="">Select Class</option>';
        classes.forEach(cls => {
            classOptions += `<option value="${cls.id}">${cls.class_name}</option>`;
        });
        fromClass.innerHTML = classOptions;
        toClass.innerHTML = classOptions;

        // 3. Populate Academic Year Dropdown
        yearDropdown.innerHTML = '<option value="">Select Session</option>';
        years.forEach(year => {
            yearDropdown.innerHTML += `<option value="${year.id}">${year.year_name}</option>`;
        });

        // NOTE: We no longer need the toClass.addEventListener here 
        // because the HTML uses onchange="handleToClassChange(this.value)"

    } catch (err) {
        console.error("Error populating promotion modal:", err);
    }
}

/**
 * Helper: Load Sections for the Destination (TO) Class
 * This replaces loadPromotionSections to match your HTML's handleToClassChange
 */
async function handleToClassChange(classId) {
    const container = document.getElementById('to_section_container');
    const sectionSelect = document.getElementById('promote_to_section');
    
    if (!classId) {
        if (container) container.style.display = 'none';
        return;
    }

    try {
        const res = await fetch(`api/sections/get_sections_by_class.php?class_id=${classId}`);
        const secData = await res.json();

        if (secData.status === 'success' && secData.data && secData.data.length > 0) {
            let options = '<option value="">Select Next Section</option>';
            secData.data.forEach(sec => {
                options += `<option value="${sec.id}">${sec.section_name}</option>`;
            });
            sectionSelect.innerHTML = options;
            
            // SHOW container (div) instead of just the select for better UI
            if (container) {
                container.style.display = 'block';
            } else {
                sectionSelect.style.display = 'block';
            }
        } else {
            // HIDE if no sections exist
            if (container) container.style.display = 'none';
            sectionSelect.style.display = 'none';
            sectionSelect.innerHTML = '<option value="">No Sections</option>';
        }
    } catch (err) {
        console.error("Error Loading Sections:", err);
        if (container) container.style.display = 'none';
    }
}



//============prometded student preview and check uncheck ===========
/**
 * Preview students from the selected "From Class"
 * Simplified to promote all students from the class regardless of current section.
 */
async function previewPromotion() {
    const fromClass = document.getElementById('promote_from_class').value;

    if (!fromClass) {
        Swal.fire("Error", "Select a 'From Class' first", "warning");
        return;
    }

    try {
        // Updated API call: section parameter removed as we want the whole class
        const res = await fetch(`api/students/fetch_students_preview.php?class_id=${fromClass}`);
        const students = await res.json();

        const tbody = document.getElementById('promo_student_list');
        tbody.innerHTML = '';

        let html = '';

        if (students.length === 0) {
            html = '<tr><td colspan="3" class="text-center">No students found in this class.</td></tr>';
        } else {
            students.forEach(s => {
                const status = (s.promotion_status || 'active').toLowerCase();
                const canPromote = (status !== 'failed' && status !== 'dropped');
                const rowClass = canPromote ? '' : 'table-light text-muted';

                const checkboxAttr = canPromote
                    ? `value="${s.id}" class="promo-check form-check-input"`
                    : 'disabled';

                let statusBadge = '';
                if (status === 'failed') statusBadge = '<span class="badge bg-warning text-dark ms-2">Failed - Must Repeat</span>';
                if (status === 'dropped') statusBadge = '<span class="badge bg-danger ms-2">Dropped - Inactive</span>';

                html += `
                <tr class="${rowClass}">
                    <td>
                        <input type="checkbox" ${checkboxAttr} ${canPromote ? 'checked' : ''}>
                    </td>
                    <td>${s.roll_no || 'N/A'}</td>
                    <td>
                        <strong>${s.student_name}</strong> ${statusBadge}
                    </td>
                </tr>`;
            });
        }

        tbody.innerHTML = html;

        document.getElementById('promotion_preview_area').style.display = 'block';
        document.getElementById('btn_finish_promo').style.display = 'inline-block';

    } catch (err) {
        console.error("Fetch Error:", err);
        Swal.fire("Error", "Failed to load student list", "error");
    }
}

/**
 * Toggles all checkboxes in the promotion list
 */
function toggleAllPromo(master) {
    document.querySelectorAll('.promo-check:not(:disabled)').forEach(cb => {
        cb.checked = master.checked;
    });
}

/**
 * Executes the bulk promotion process
 */
async function promoteStudents() {
    const fromClass = document.getElementById('promote_from_class').value;
    const toClass = document.getElementById('promote_to_class').value;
    const toSection = document.getElementById('promote_to_section').value;
    const nextYearId = document.getElementById('next_academic_year').value;

    const selectedIds = Array.from(document.querySelectorAll('.promo-check:checked')).map(cb => cb.value);

    // Validation
    if (!fromClass || !toClass || !nextYearId) {
        Swal.fire("Error", "Please select source class, destination class, and the next academic year.", "error");
        return;
    }

    if (selectedIds.length === 0) {
        Swal.fire("Error", "No students selected for promotion.", "warning");
        return;
    }

    const confirm = await Swal.fire({
        title: 'Are you sure?',
        text: `You are about to promote ${selectedIds.length} students to the next session.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, promote them!'
    });

    if (confirm.isConfirmed) {
        const formData = new FormData();
        formData.append('student_ids', JSON.stringify(selectedIds));
        formData.append('to_class', toClass);
        formData.append('to_section', toSection);
        formData.append('next_year_id', nextYearId);
        formData.append('from_class', fromClass);

        try {
            const res = await fetch("api/students/bulk_promote.php", {
                method: "POST",
                body: formData
            });

            const data = await res.json();

            if (data.status) {
                Swal.fire("Success!", data.msg, "success");
                const modalEl = document.getElementById('promotionModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) modal.hide();
                
                if (typeof fetchStudentList === "function") fetchStudentList();
            } else {
                Swal.fire("Failed", data.msg, "error");
            }
        } catch (err) {
            console.error(err);
            Swal.fire("Error", "Server connection failed.", "error");
        }
    }
}
//================populate promotion field promotion end  =================

// =================== add section dropdown by class =============
/**
 * Unified Event Listener
 * This handles both Sections and Streams when the Class is changed
 */
document.addEventListener('change', function (e) {
    if (e.target && e.target.id === 'class_id') {
        const selectedClassId = e.target.value;

        // 1. Trigger Section Fetching
        fetchSections(selectedClassId);

      
    }
});

// ================ Section Logic =================
async function fetchSections(classId) {
    const sectionSelect = document.getElementById('student_section');
    if (!sectionSelect) return;

    if (!classId) {
        sectionSelect.innerHTML = '<option value="">Select Class First</option>';
        sectionSelect.disabled = true;
        return;
    }

    try {
        sectionSelect.disabled = true;
        sectionSelect.innerHTML = '<option value="">Loading...</option>';

        const response = await fetch(`api/sections/get_sections_by_class.php?class_id=${classId}`);
        if (!response.ok) throw new Error("Network response was not ok");

        const result = await response.json();

        if (result.status === 'success' && Array.isArray(result.data)) {
            if (result.data.length > 0) {
                let html = '<option value="">-- Choose Section --</option>';
                result.data.forEach(sec => {
                    html += `<option value="${sec.id}">${sec.section_name}</option>`;
                });
                sectionSelect.innerHTML = html;
                sectionSelect.disabled = false;
                sectionSelect.required = true;
            } else {
                sectionSelect.innerHTML = '<option value="">No Sections found</option>';
                sectionSelect.disabled = true;
                sectionSelect.required = false;
            }
        }
    } catch (err) {
        console.error("Fetch Error:", err);
        sectionSelect.innerHTML = '<option value="">Error loading sections</option>';
    }
}




// Load Mediums from Database
// Function to load mediums into the dropdown
async function loadMediums() {
    try {
        const response = await fetch('api/mediums/get_mediums.php');
        const result = await response.json();
        const mediumSelect = document.getElementById('medium_id');

        if (result.status) {
            // Clear existing options except the first one
            mediumSelect.innerHTML = '<option value="">Select Medium</option>';

            result.data.forEach(medium => {
                const option = document.createElement('option');
                option.value = medium.id;
                option.textContent = medium.medium_name;
                mediumSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error("Error loading mediums:", error);
    }
}

// Call this in your initialization block
document.addEventListener('DOMContentLoaded', () => {
    loadMediums();
    // your loadStreams() call is likely already here
});

// Call on page load
document.addEventListener('DOMContentLoaded', loadMediums);
// =================== add student area code   ==========================
async function addStudent() {
    const form = document.getElementById("studentForm");
    const formData = new FormData(form);

    /* =========================
        REQUIRED FIELD VALIDATION
    ========================== */
    const requiredFields = [
        'student_name',
        'father_name',
        'class_id',
        'medium_id',
        'roll_no',
        'gender',
        'parent_phone',
        'address',
        'dob',
        'admission_date'
    ];

    for (let field of requiredFields) {
        const value = formData.get(field);
        if (!value || value.toString().trim() === "") {
            Swal.fire({
                title: "Missing Field!",
                text: `Please fill ${field.replace("_", " ").toUpperCase()}`,
                icon: "warning"
            });
            return;
        }
    }

    /* =========================================
            MEDIUM VALIDATION (Strict ID Check)
        ========================================= */
    const medium_id = formData.get('medium_id');
    if (!medium_id || parseInt(medium_id) <= 0) {
        Swal.fire({
            title: "Medium Required!",
            text: "Please select Instruction Medium (English or Assamese).",
            icon: "warning"
        });
        return;
    }

    /* =========================
        VALIDATE DATE OF BIRTH (DOB)
    ========================== */
    const dob = formData.get('dob');
    const dobDate = new Date(dob);
    const today = new Date();
    if (dobDate > today) {
        Swal.fire({
            title: "Invalid Date of Birth!",
            text: "Date of birth cannot be in the future.",
            icon: "warning"
        });
        return;
    }

    /* =========================
        VALIDATE ADMISSION DATE
    ========================== */
    const admissionDate = formData.get('admission_date');
    if (!admissionDate) {
        Swal.fire({
            title: "Missing Admission Date!",
            text: "Admission date is required.",
            icon: "warning"
        });
        return;
    }

    /* =========================
        CLASS VALIDATION
    ========================== */
    const class_val = formData.get('class_id');
    const class_id = parseInt(class_val);
    if (isNaN(class_id) && !class_val) {
        Swal.fire({
            title: "Invalid Class!",
            text: "Please select a class",
            icon: "warning"
        });
        return;
    }

    /* =========================
        ROLL NUMBER VALIDATION
    ========================== */
    const roll_no = parseInt(formData.get('roll_no'));
    if (isNaN(roll_no) || roll_no <= 0) {
        Swal.fire({
            title: "Invalid Roll Number!",
            text: "Roll number must be a positive number",
            icon: "warning"
        });
        return;
    }

    /* =========================
        PARENT PHONE VALIDATION
    ========================== */
    let phone = formData.get('parent_phone').trim();
    phone = phone.replace(/[\s\-()]/g, '');
    const phoneRegex = /^(\+91\d{10}|\d{10})$/;

    if (!phoneRegex.test(phone)) {
        Swal.fire({
            title: "Invalid Phone Number!",
            text: "Please enter exactly 10 digits or +91 followed by 10 digits.",
            icon: "warning"
        });
        return;
    }

    if (phone.length === 10) {
        phone = "+91" + phone;
    }
    formData.set('parent_phone', phone);

    /* =========================
        STUDENT PHOTO VALIDATION
    ========================== */
    const photoInput = document.getElementById("student_photo");
    if (photoInput && photoInput.files.length > 0) {
        const file = photoInput.files[0];
        const allowedTypes = ["image/jpeg", "image/png"];
        const maxSize = 300 * 1024;

        if (!allowedTypes.includes(file.type)) {
            Swal.fire({
                title: "Invalid Photo!",
                text: "Photo must be JPG or PNG",
                icon: "warning"
            });
            return;
        }

        if (file.size > maxSize) {
            Swal.fire({
                title: "Photo Too Large!",
                text: "Photo must be under 300KB",
                icon: "warning"
            });
            return;
        }
    }

    /* =========================
        SEND REQUEST
    ========================== */
    try {
        const res = await fetch("api/students/student_add.php", {
            method: "POST",
            body: formData
        });

        const data = await res.json();

        if (data.status) {
            Swal.fire({
                title: "Success!",
                text: data.msg,
                icon: "success",
                timer: 1500,
                showConfirmButton: false
            });
            form.reset();

            const modal = bootstrap.Modal.getInstance(document.getElementById('studentModal'));
            if (modal) modal.hide();

            if (typeof fetchStudentList === "function") {
                fetchStudentList();
            }
        } else {
            Swal.fire({
                title: "Error!",
                text: data.msg,
                icon: "error"
            });
        }

    } catch (err) {
        Swal.fire({
            title: "Server Error!",
            text: err.message || "Something went wrong",
            icon: "error"
        });
    }
}
// Call this on page load
document.addEventListener('DOMContentLoaded', () => {
    initClassDropdown(); // For your Add Student Modal
    populatePromotionModal(); // For this Promotion Modal
});