<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: 100%;
            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="">Select 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-3">
                                    <div class="form-group">
                                        <label for="exampleInputEmail1">Learner</label><small class="req"> *</small>
                                        <select  id="student_id" name="student_id" class="form-control" >
                                            <option value=""><?php echo $this->lang->line('select'); ?></option>
                                        </select>
                                        <span class="text-danger"><?php echo form_error('student_id'); ?></span>
                                    </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 class="text-center no-print" style="margin-top:40px;">
                            <button class="btn btn-success" onclick="printReport()">
                                <i class="fa fa-print"></i> Print Report
                            </button>
                        </div>
                    </div>
                </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 student = document.getElementById('student_id').value;

    if(term === "" || level === "" || cls === "" || student === "" || exam_id === "") {
        alert("Please select Term, Level, Class, Student and Exam 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;

    // Get CSRF token if CodeIgniter CSRF is enabled
    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_id: student,
            [csrfName]: csrfHash // include CSRF token
        },
        // Remove dataType to debug properly
        success: function(response) {
            generateBtn.innerHTML = '<i class="fa fa-file-text"></i> Generate Report';
            generateBtn.disabled = false;

            // Try parsing JSON manually to catch PHP errors
            try {
                var data = typeof response === 'string' ? JSON.parse(response) : response;


                if(data.success) {
                    updateReportSection(data);
                    document.getElementById('reportSection').style.display = 'block';
                    document.getElementById('reportSection').scrollIntoView({ behavior: 'smooth' });
                } else {
                    alert(data.message || 'Error generating report.');
                    console.log("Controller response:", data);
                }
            } catch(e) {
                alert("Invalid server response! Check console.");
                console.error("Raw server response:", 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);
            console.error("Response text:", xhr.responseText);
        }
    });
});



function updateReportSection(data) {
    // Update student information
    document.getElementById('student_name').textContent = data.student_name;
    document.getElementById('admission_no').textContent = data.admission_no;
    document.getElementById('class_info').textContent = data.class_name + data.section_name;
    document.getElementById('term_info').textContent = data.term;
    document.getElementById('year_info').textContent = data.year;
    document.getElementById('examTitle').innerText = data.exam_name.toUpperCase() + " REPORT";


    // Update marks table
    var tbody = document.getElementById('marks_body');
    tbody.innerHTML = '';

    data.subjects_marks.forEach(function(subject) {
        var row = document.createElement('tr');
        row.innerHTML = `
            <td>${subject.subject}</td>
            <td>${subject.actual_mark}</td>
            <td>${subject.possible_mark}</td>
            <td>${subject.grade}</td>
            <td>${subject.comment}</td>
        `;
        tbody.appendChild(row);
    });

    // Add total row
    var totalRow = document.createElement('tr');
    totalRow.className = 'total-row';
    totalRow.innerHTML = `
        <th>Total</th>
        <th>${data.total_actual}</th>
        <th>${data.total_possible}</th>
        <th>-</th>
        <th>Overall ${data.total_actual/data.total_possible >= 0.7 ? 'Excellent' : 'Good'} Performance</th>
    `;
    tbody.appendChild(totalRow);

    // Update comments
    document.getElementById('teacher_comment').textContent = data.teacher_comment;
    document.getElementById('head_comment').textContent = data.head_comment;
}

</script>
<script>
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 CSS links
    Array.from(document.querySelectorAll('link[rel="stylesheet"], style')).forEach(function(node){
        printWindow.document.write(node.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("");
        var class_id = $('#class_id').val();
        var section_id = $('#section_id').val();
        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 (section_id == obj.section_id) {
                        sel = "selected=selected";
                    }
                    div_data += "<option value=" + obj.id + ">" + obj.firstname + " " + obj.lastname + "</option>";
                });
                $('#student_id').append(div_data);
            }
        });
    }

    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>