<div class="content-wrapper" style="min-height: 946px;">
    <section class="content-header">
        <h1>
            <i class="fa fa-map-o"></i> End of Term Report
            <small>Student Performance Overview</small>
        </h1>
        <a href="<?php echo base_url(); ?>admin/grade" class="col-md pull-right">Marks Grade</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php echo base_url(); ?>admin/mark" class="col-md pull-right">Marks Report</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php echo base_url(); ?>admin/examschedule" class="col-md pull-right">Exam Schedule</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php echo base_url(); ?>admin/exam" class="col-md pull-right">Exam List</a>
    </section>
     <style>
        .report-table {
    width: 98%; /* slightly less than full width */
    margin-left: auto;  /* centers the table horizontally */
    margin-right: auto; /* centers the table horizontally */
    border-collapse: collapse;
    font-size: 14px;
}

        .report-table th,
        .report-table td {
            border: 1px solid #000;
            padding: 8px;
            text-align: center;
        }
        .report-table thead th {
            background-color: #f1f1f1;
            font-weight: bold;
        }
        .total-row th,
        .total-row td {
            background-color: #eaeaea;
            font-weight: bold;
        }
        .comment-card {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            margin-top: 15px;
        }
        .comment-title {
            font-weight: bold;
            color: rgb(2, 22, 44);
            margin-bottom: 8px;
        }
        .comment-content {
            font-size: 14px;
            line-height: 1.5;
            color: #495057;
        }

    </style>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <!-- Filter Form -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-search"></i> Select Criteria</h3>
                    </div>
                   <form id="reportForm">
                        <div class="box-body">
                            <div class="row">
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Term</label>
                                        <select id="term" name="term" class="form-control" required>
                                            <option value="">Term</option>
                                            <?php foreach($terms as $term): ?>
                                                <option value="<?php echo $term; ?>"><?php echo $term; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Exam</label>
                                        <select name="exam_id" id="exam_id" class="form-control" required>
                                            <option value="">Select Exam</option>

                                            <?php if(!empty($exams)) : ?>
                                                <?php foreach($exams as $exam): ?>
                                                    <option value="<?php echo $exam['id']; ?>">
                                                        <?php echo $exam['name']; ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            <?php endif; ?>

                                        </select>
                                    </div>
                                </div>


                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Level</label><small class="req"> *</small>
                                        <select autofocus="" id="class_id" name="class_id" class="form-control" >
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                            <?php
                                            foreach ($levels as $class) {
                                                ?>
                                                <option value="<?php echo $class['id'] ?>" <?php if (set_value('class_id') == $class['id']) echo "selected=selected" ?>><?php echo $class['class'] ?></option>
                                                <?php
                                                $count++;
                                            }
                                            ?>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('class_id'); ?></span>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Class</label><small class="req"> *</small>
                                        <select  id="section_id" name="section_id" class="form-control" >
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('section_id'); ?></span>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                <div class="form-group">
                                    <label>Student From</label>
                                    <select id="student_from" name="student_from" class="form-control">
                                        <option value="">Select</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>Student To</label>
                                    <select id="student_to" name="student_to" class="form-control">
                                        <option value="">Select</option>
                                    </select>
                                </div>
                            </div>
                                <div class="text-center mt-5">
                                    <button type="button" id="generateBtn" class="btn btn-primary px-4">
                                        <i class="fa fa-file-text"></i> Generate Report
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Report Section -->
                <div id="reportSection" class="box box-info" style="display:none;">
                    <!-- School Header Section -->
                    <div class="text-center" style="padding: 20px; border-bottom: 2px solid #000;">
                        <?php if (!empty($settinglist[0]['image'])) { ?>
                            <img src="<?php echo base_url('uploads/school_content/logo/' . $settinglist[0]['image']); ?>" 
                                alt="School Logo" style="height: 90px; margin-bottom: 10px;">
                        <?php } ?>

                        <h2 style="margin: 0; font-weight: bold;"><?php echo $settinglist[0]['name']; ?></h2>
                        <p style="margin: 0;"><?php echo $settinglist[0]['address']; ?></p>
                        <p><?php echo $this->lang->line('phone'); ?>: <?php echo $settinglist[0]['phone']; ?></p>
                        <h4 id="examTitle" style="margin-top: 10px; font-weight: bold; text-decoration: underline;"></h4>

                    </div>

                    <!-- Report Info Section -->
                    <div style="padding: 15px;">
                        <p><strong>Student Name:</strong> <span id="student_name">-</span> &nbsp;&nbsp; | &nbsp;&nbsp; 
                           <strong>Admission No:</strong> <span id="admission_no">-</span></p>
                        <p><strong>Class:</strong> <span id="class_info">-</span> &nbsp;&nbsp; | &nbsp;&nbsp; 
                           <strong>Term:</strong> <span id="term_info">-</span> &nbsp;&nbsp; | &nbsp;&nbsp; 
                           <strong>Year:</strong> <span id="year_info">-</span></p>
                    </div>

                    <!-- Results Table -->
                    <div class="box-body">
                        <div class="table-responsive">
                            <table class="report-table">
                                <thead>
                                    <tr>
                                        <th>Subject</th>
                                        <th>Actual Mark</th>
                                        <th>Possible Mark</th>
                                        <th>Grade</th>
                                        <th>Subject Comment</th>
                                    </tr>
                                </thead>
                                <tbody id="marks_body">
                                    <!-- Marks will be populated by JavaScript -->
                                </tbody>
                            </table>
                        </div>

                        <!-- Comments Section -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <div class="comment-card">
                                    <div class="comment-title">Class Teacher's Comment</div>
                                    <div class="comment-content" id="teacher_comment">
                                        Comments will appear here after generating report.
                                    </div>
                                </div>

                                <div class="comment-card">
                                    <div class="comment-title">Head/Deputy Comment</div>
                                    <div class="comment-content" id="head_comment">
                                        Comments will appear here after generating report.
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Signature Section -->
                        <div style="margin-top:30px;">
                            <div style="float:left; width:50%;">
                                <strong>__________________________</strong><br>
                                Class Teacher
                            </div>
                            <div style="float:right; width:50%; text-align:right;">
                                <strong>__________________________</strong><br>
                                Headmaster/Deputy
                            </div>
                        </div>

                        <div style="clear:both;"></div>

                        <!-- Print Button -->
                       
                    </div>
                </div>
                <div id="printBtnContainer" class="text-center" style="margin-top:20px; display:none;"></div>
            </div>
        </div>
    </section>
</div>

<script>
document.getElementById('generateBtn').addEventListener('click', function () {
    var term = document.getElementById('term').value;
    var level = document.getElementById('class_id').value;
    var exam_id = document.getElementById('exam_id').value;
    var cls = document.getElementById('section_id').value;
    var studentfrom = document.getElementById('student_from').value;
    var studentto = document.getElementById('student_to').value;

    if(term === "" || level === "" || cls === "" || studentfrom === "" || exam_id === "") {
        alert("Please select Term, Level, Class, Student From and Student To to generate the report.");
        return;
    }

    var generateBtn = document.getElementById('generateBtn');
    generateBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating Report...';
    generateBtn.disabled = true;

    // CSRF token for CodeIgniter
    var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>';
    var csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';

    $.ajax({
        url: '<?php echo base_url(); ?>admin/endofterm/generate_report',
        type: 'POST',
        data: {
            term: term,
            class_id: level,
            section_id: cls,
            exam_id: exam_id,
            student_from: studentfrom,
            student_to: studentto,
            [csrfName]: csrfHash
        },
        success: function(response) {
    generateBtn.innerHTML = '<i class="fa fa-file-text"></i> Generate Report';
    generateBtn.disabled = false;

    try {
        var data = typeof response === 'string' ? JSON.parse(response) : response;

        if(data.success && data.students && Array.isArray(data.students)) {

            // Clear old reports
            const reportSection = document.getElementById('reportSection');
            reportSection.innerHTML = ''; 

            // Append each student's report
            data.students.forEach(student => {
                reportSection.appendChild(createStudentReport(student));
            });

            // Show report section
            reportSection.style.display = 'block';
            reportSection.scrollIntoView({ behavior: 'smooth' });

            // Show print button
            const printBtnContainer = document.getElementById('printBtnContainer');
            printBtnContainer.innerHTML = `
                <button class="btn btn-success" onclick="printReport()">
                    <i class="fa fa-print"></i> Print Report
                </button>
            `;
            printBtnContainer.style.display = 'block';

        } else {
            alert('No students found for the selected range.');
        }
    } catch(e) {
        alert("Invalid server response! Check console.");
        console.error(response);
    }
},
        error: function(xhr, status, error) {
            generateBtn.innerHTML = '<i class="fa fa-file-text"></i> Generate Report';
            generateBtn.disabled = false;
            alert('AJAX request failed. Check console for details.');
            console.error("AJAX error:", status, error, xhr.responseText);
        }
    });
});

/**
 * Create full report for a single student
 * Returns a DOM element
 */
// Create a student report element
function createStudentReport(student) {
    const container = document.createElement('div');
    container.className = 'student-report';
    container.style.pageBreakAfter = 'always';

    container.innerHTML = `
        <div class="text-center" style="padding:20px; border-bottom:2px solid #000;">
            ${student.school_logo ? `<img src="${student.school_logo}" alt="School Logo" style="height:90px; margin-bottom:10px;">` : ''}
            <h2 style="margin:0; font-weight:bold;">${student.school_name}</h2>
            <p style="margin:0;">${student.school_address}</p>
            <p>Phone: ${student.school_phone}</p>
            <h4 style="margin-top:10px; font-weight:bold; text-decoration:underline;">${student.exam_name.toUpperCase()} REPORT</h4>
        </div>

        <div style="padding:15px;">
            <p><strong>Student Name:</strong> ${student.student_name} &nbsp; | &nbsp; 
               <strong>Admission No:</strong> ${student.admission_no}</p>
            <p><strong>Class:</strong> ${student.class_name} ${student.section_name} &nbsp; | &nbsp; 
               <strong>Term:</strong> ${student.term} &nbsp; | &nbsp; 
               <strong>Year:</strong> ${student.year}</p>
        </div>

        <div class="table-responsive">
            <table class="report-table">
                <thead>
                    <tr>
                        <th>Subject</th>
                        <th>Actual Mark</th>
                        <th>Possible Mark</th>
                        <th>Grade</th>
                        <th>Comment</th>
                    </tr>
                </thead>
                <tbody>
                    ${student.subjects_marks.map(s => `
                        <tr>
                            <td>${s.subject}</td>
                            <td>${s.actual_mark}</td>
                            <td>${s.possible_mark}</td>
                            <td>${s.grade}</td>
                            <td>${s.comment}</td>
                        </tr>
                    `).join('')}
                    <tr class="total-row">
                        <th>Total</th>
                        <th>${student.total_actual}</th>
                        <th>${student.total_possible}</th>
                        <th>-</th>
                        <th>Overall ${student.total_actual/student.total_possible >= 0.7 ? 'Excellent' : 'Good'} Performance</th>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="comment-card">
            <div class="comment-title">Class Teacher's Comment</div>
            <div class="comment-content">${student.teacher_comment}</div>
        </div>

        <div class="comment-card">
            <div class="comment-title">Head/Deputy Comment</div>
            <div class="comment-content">${student.head_comment}</div>
        </div>

        <div style="margin: 30px 1% 0 1%;"> <!-- top:30px, left/right:10% -->
    <div style="width:49%; float:left;">
        <strong>__________________________</strong><br>Class Teacher
    </div>
    <div style="width:49%; float:right; text-align:right;">
        <strong>__________________________</strong><br>Headmaster/Deputy
    </div>
    <div style="clear:both;"></div>
</div>
    `;

    return container;
}

// Update the report section with multiple students
// After updating reports
function updateReports(students) {
    const container = document.getElementById('reportSection');
    container.innerHTML = ''; // clear previous

    students.forEach(student => container.appendChild(createStudentReport(student)));
    container.style.display = 'block';

    // Show print button dynamically
    const printBtnContainer = document.getElementById('printBtnContainer');
    printBtnContainer.innerHTML = `
        <button class="btn btn-success" onclick="printReport()">
            <i class="fa fa-print"></i> Print Report
        </button>
    `;
    printBtnContainer.style.display = 'block';
}


// Print all reports
function printReport() {
    const reportContent = document.getElementById('reportSection').innerHTML;
    const printWindow = window.open('', '', 'height=800,width=1200');

    printWindow.document.write('<html><head><title>Print Report</title>');

    // Copy all styles (both <link> and <style>)
    Array.from(document.querySelectorAll('link[rel="stylesheet"], style')).forEach(n => {
        printWindow.document.write(n.outerHTML);
    });

    printWindow.document.write('</head><body>');
    printWindow.document.write(reportContent);
    printWindow.document.write('</body></html>');

    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close();
}
</script>


<script type="text/javascript">
    function getSectionByClass(class_id, section_id) {
        if (class_id !== "" && section_id !== "") {
            $('#section_id').html("");
            var base_url = '<?php echo base_url() ?>';
            var div_data = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
            $.ajax({
                type: "GET",
                url: base_url + "sections/getByClass",
                data: {'class_id': class_id},
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, obj)
                    {
                        var sel = "";
                        if (section_id === obj.section_id) {
                            sel = "selected";
                        }
                        div_data += "<option value=" + obj.section_id + " " + sel + ">" + obj.section + "</option>";
                    });
                    $('#section_id').append(div_data);
                }
            });
        }
    }

    $(document).ready(function () {
        $('.detail_popover').popover({
            placement: 'right',
            title: '',
            trigger: 'hover',
            container: 'body',
            html: true,
            content: function () {
                return $(this).closest('td').find('.fee_detail_popover').html();
            }
        });

        $(document).on('change', '#class_id', function (e) {
            $('#section_id').html("");
            var class_id = $(this).val();
            var base_url = '<?php echo base_url() ?>';
            var div_data = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
            $.ajax({
                type: "GET",
                url: base_url + "sections/getByClass",
                data: {'class_id': class_id},
                dataType: "json",
                success: function (data) {
                    $.each(data, function (i, obj)
                    {
                        div_data += "<option value=" + obj.section_id + ">" + obj.section + "</option>";
                    });
                    $('#section_id').append(div_data);
                }
            });
        });
        $(document).on('change', '#section_id', function (e) {

            getStudentsByClassAndSection();

        });
        var class_id = $('#class_id').val();
        var section_id = '<?php echo set_value('section_id') ?>';
        getSectionByClass(class_id, section_id);
        if (class_id != "" || section_id != "") {
            postbackStudentsByClassAndSection(class_id, section_id);
        }
    });
   function getStudentsByClassAndSection() {

    $('#student_id').html("");
    $('#student_from').html("");
    $('#student_to').html("");

    var class_id = $('#class_id').val();
    var section_id = $('#section_id').val();
    var base_url = '<?php echo base_url() ?>';

    var default_option = '<option value="">Select</option>';

    $.ajax({
        type: "GET",
        url: base_url + "student/getByClassAndSection",
        data: {'class_id': class_id, 'section_id': section_id},
        dataType: "json",
        success: function (data) {

            var options = default_option;

            $.each(data, function (i, obj) {
                options += "<option value='" + obj.id + "'>" 
                        + obj.firstname + " " + obj.lastname + 
                        "</option>";
            });

            $('#student_id').append(options);
            $('#student_from').append(options);
            $('#student_to').append(options);
        }
    }); 
   }

    function postbackStudentsByClassAndSection(class_id, section_id) {
        $('#student_id').html("");
        var student_id = '<?php echo set_value('student_id') ?>';
        var base_url = '<?php echo base_url() ?>';
        var div_data = '<option value=""><?php echo $this->lang->line('select'); ?></option>';
        $.ajax({
            type: "GET",
            url: base_url + "student/getByClassAndSection",
            data: {'class_id': class_id, 'section_id': section_id},
            dataType: "json",
            success: function (data) {
                $.each(data, function (i, obj)
                {
                    var sel = "";
                    if (student_id == obj.id) {
                        sel = "selected=selected";
                    }
                    div_data += "<option value=" + obj.id + " " + sel + ">" + obj.firstname + " " + obj.lastname + "</option>";
                });
                $('#student_id').append(div_data);
            }
        });
    }
</script>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>