document.addEventListener('DOMContentLoaded', () => {
    const studentSelect = document.getElementById('student_id');
    const classSelect = document.getElementById('class_section_id');

    const studentFrame = document.getElementById('studentReportFrame');
    const classFrame = document.getElementById('classReportFrame');

    const downloadStudentBtn = document.getElementById('downloadStudentBtn');
    const downloadClassBtn = document.getElementById('downloadClassBtn');

    const printStudentBtn = document.getElementById('printStudentBtn');
    const printClassBtn = document.getElementById('printClassBtn');

    document.getElementById('studentForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const studentId = studentSelect.value;
        const viewUrl = `/report-card/student/${studentId}`;
        studentFrame.src = viewUrl;
        studentFrame.hidden = false;
        downloadStudentBtn.href = viewUrl + "?download=1";
    });

    document.getElementById('classForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const classId = classSelect.value;
        const viewUrl = `/report-card/class/${classId}`;
        classFrame.src = viewUrl;
        classFrame.hidden = false;
        downloadClassBtn.href = viewUrl + "?download=1";
    });

    printStudentBtn.addEventListener('click', function (e) {
        e.preventDefault();
        printIframe('studentReportFrame');
    });

    printClassBtn.addEventListener('click', function (e) {
        e.preventDefault();
        printIframe('classReportFrame');
    });

    function printIframe(id) {
        const frame = document.getElementById(id);
        frame.contentWindow.focus();
        frame.contentWindow.print();
    }
});
