<?php $__env->startSection('content'); ?>
<?php echo $__env->make('report.exam-result.header-menu', ['active_header' => 'result_report'], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <div class="card mt-4">
        <div class="card-body card__head">
            <form method="POST" action="<?php echo e(route('reports.marks_by_class')); ?>" class="row">
                <?php echo csrf_field(); ?>
                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    <select name="exam_id" class="form-control select2 exam_id" id="exam_id" required>
                        <option value="">Exam</option>
                        <?php $__currentLoopData = $exams; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $examItem): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($examItem->id); ?>" <?php if($exam_id == $examItem->id || (!$exam_id && getCurrentActiveExamId() )): echo 'selected'; endif; ?> >
                                <?php echo e($examItem->exam_name . ' ' . $examItem->academic_year->year); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?> 
                    </select>
                </div>

                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    <select name="shift_id" class="form-control select2 shift_id" id="shift_id" >
                        <option value="">Shift</option>
                        <?php $__currentLoopData = $shifts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shift): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($shift->id); ?>" <?php if($shift_id == $shift->id || (!$shift_id && $loop->first)): echo 'selected'; endif; ?>>
                                <?php echo e($shift->shift_name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    <?php echo e(generateDropdown($studentClasses, 'class="form-control select2 student_class_id student_class" id="student_class" name="student_class_id" required', $student_class_id, 'Class')); ?>

                </div>
                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    <?php echo e(generateDropdown([], 'class="form-control section_id" id="section_id" name="section_id" ', $section_id, 'Section')); ?>

                </div>

                <?php if (isset($component)) { $__componentOriginal24102f1ac62c394be69e2bc4df251128 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal24102f1ac62c394be69e2bc4df251128 = $attributes; } ?>
<?php $component = App\View\Components\GroupSelector::resolve(['name' => 'group_id','label' => '','labelText' => 'Group','col' => 'form-group col-lg-2 col-md-6 col-sm-6','required' => (int) request()->input('student_class') >= 11,'selected' => old('group_id') ?? request()->input('group_id')] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('group-selector'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\GroupSelector::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['student_class_id' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute((int) request()->input('student_class'))]); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal24102f1ac62c394be69e2bc4df251128)): ?>
<?php $attributes = $__attributesOriginal24102f1ac62c394be69e2bc4df251128; ?>
<?php unset($__attributesOriginal24102f1ac62c394be69e2bc4df251128); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal24102f1ac62c394be69e2bc4df251128)): ?>
<?php $component = $__componentOriginal24102f1ac62c394be69e2bc4df251128; ?>
<?php unset($__componentOriginal24102f1ac62c394be69e2bc4df251128); ?>
<?php endif; ?>

                
                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    <button type="submit" class="btn btn-info">Search</button>
                </div>

            </form>
        </div>
    </div>

    <?php if(isset($students) && !$students->isEmpty()): ?>
        <div class="card mt-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom">
                <h6 class="m-0 table__top__txt">Result Report (Total Result: <?php echo e(count($students)); ?>)</h6>
                <div class="m-0 float-right">
                    <button class="btn btn-sm btn-primary" onclick="printDiv()">Print</button>
                </div>
            </div>
            <div class="table_content">
                <section class="page-section">
                    <div class="table-responsive">
                        <table class="table" width="100%">
                            <thead class="thead-light">
                                <tr>
                                    <th>Roll</th>
                                    <th>Std. ID</th>
                                    <th>Name</th>
                                    <th>Position</th>
                                    <th>Class</th>
                                    <th>Section</th>
                                    <th class="bg-gray">Full Marks</th>
                                    <th>Total Obt.</th>
                                    <th>Obt. Percentage</th>
                                    <th>Highest Marks</th>
                                    <th>GPA</th>
                                    <th>Grade</th>
                                </tr>
                            </thead>
                            <tbody>

                                <?php
                                $head_marks_array = json_decode($assignedMarksHead->first(), true);
                                $head_id_array = array_keys($head_marks_array);

                                $subject_head_marks = $assignedMarksHead;
                                $highest_grand_total_obtain = 0;

                                $passedStudents = [];
                                $failedStudents = [];

                                $head_marks_array = json_decode($assignedMarksHead->first(), true);
                                $head_id_array = array_keys($head_marks_array);

                                $subject_head_marks = $assignedMarksHead;
                                $highest_grand_total_obtain = 0;

                                foreach ($students as $student) {

                                    $grand_total_obtain = 0;
                                    $fail_count = 0;
                                    $head_wise_fail_count = 0;

                                    $examRecords = $student?->examRecords ?? '';

                                    if ($examRecords->isNotEmpty()) {
                                        foreach ($examRecords as $record) {

                                            // ==============================
                                            // SUBJECT HEADS (WRITTEN / VIVA)
                                            // ==============================
                                            $head_marks_data = $subject_head_marks[$record->subject->id];
                                            $head_marks_array = json_decode($head_marks_data);
                                            $head_wise_marks_record = json_decode($record->head_wise_marks);

                                            $head_marks_array2 = json_decode($head_marks_data, true); // total marks per head
                                            $head_wise_marks_record2 = json_decode($record->head_wise_marks, true); // student marks

                                            $head_wise_pass_fail = []; // store pass/fail for each head

                                            // ====================================
                                            // HEAD-WISE PASS FAIL CALCULATION
                                            // ====================================
                                            foreach ($head_marks_array2 as $head_id => $total_marks) {
                                                $pass_marks = $total_marks * 0.33;  // 33% pass
                                                $marks_obtained = $head_wise_marks_record2[$head_id] ?? 0;

                                                $head_wise_pass_fail[$head_id] =
                                                    ($marks_obtained >= $pass_marks) ? 'Pass' : 'Fail';
                                            }

                                            // ====================================
                                            // IF ANY HEAD FAIL → SUBJECT FAIL
                                            // ====================================
                                            if (in_array('Fail', $head_wise_pass_fail)) {
                                                $head_wise_fail_count++;  // student failed this subject
                                            }


                                            // ====================================
                                            // TOTAL MARKS OBTAINED FOR THIS SUBJECT
                                            // ====================================
                                            $total_marks_obtain = 0;
                                            $subject_gp = 0; // store GP for this single subject
                                            foreach ($markHeads as $head) {
                                                if (in_array($head->id, $head_id_array)) {
                                                    $total_marks_obtain += $head_wise_marks_record2[$head->id] ?? 0;
                                                }
                                            }

                                            $grand_total_obtain += $total_marks_obtain;

                                            // ====================================
                                            // (OPTIONAL) OVERALL GRADE CHECK
                                            // You can remove this if not needed
                                            // ====================================
                                            
                                            if($head_wise_fail_count == 0){
                                                $full_marks = array_sum((array) $head_marks_array2);
                                                $percentage = $full_marks > 0 ? round(($total_marks_obtain * 100) / $full_marks) : 0;
                                                foreach ($grades as $grade) {
                                                    if ($percentage >= $grade->mark_from && $percentage <= $grade->mark_to) {
                                                        $subject_gp = (float) $grade->gpa;   // save GP for this subject
                                                        if ($grade->name === 'F') {
                                                            $fail_count++;
                                                        }
                                                    }
                                                }
                                            }else {
                                                $fail_count++;
                                            }
                                        }
                                    }

                                    // ====================================
                                    // STORE STUDENT FINAL RESULT
                                    // ====================================
                                    $studentData = [
                                        'student' => $student,
                                        'grand_total_obtain' => $grand_total_obtain,
                                        'fail_count' => $fail_count
                                    ];

                                    if ($fail_count > 0) {
                                        $failedStudents[] = $studentData;
                                    } else {
                                        $passedStudents[] = $studentData;
                                    }

                                }



                                // Sort FAILED students
                                usort($failedStudents, function ($a, $b) {
                                    // Sort by marks DESC
                                    if ($a['grand_total_obtain'] !== $b['grand_total_obtain']) {
                                        return $b['grand_total_obtain'] <=> $a['grand_total_obtain'];
                                    }

                                    // Sort by fail count ASC
                                    return $a['fail_count'] <=> $b['fail_count'];
                                });

                                // Sort PASSED students
                                usort($passedStudents, function ($a, $b) {
                                    // Sort by marks DESC
                                    if ($a['grand_total_obtain'] !== $b['grand_total_obtain']) {
                                        return $b['grand_total_obtain'] <=> $a['grand_total_obtain'];
                                    }

                                    // Sort by fail count ASC
                                    return $a['fail_count'] <=> $b['fail_count'];
                                });



                                // Merge results
                                $students_with_grand_total = array_merge($passedStudents, $failedStudents);

                                $position = 1;
                                ?>

                                


                                <?php $__currentLoopData = $students_with_grand_total; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $data): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <?php
                                        $student = $data['student'];
                                        $grand_total_obtain = $data['grand_total_obtain'];
                                        $grand_total = 0;
                                        $fail_count = 0;
                                        $total_gp_sum = 0;
                                        $total_subjects_count = 0;

                                        $examRecords = $student?->examRecords ?? '';
                                        $section = $sections[$student->section_id] ?? '';
                                        $class = $studentClasses[$student->student_class_id] ?? '';
                                        $academic_year = request()->query('academic_year') ?? $defaultYear;
                                        $academicYear = $academicYears[$academic_year] ?? '';

                                        if ($grand_total_obtain > $highest_grand_total_obtain) {
                                            $highest_grand_total_obtain = $grand_total_obtain;
                                        }
                                    ?>

                                    <?php if($examRecords->isNotEmpty()): ?>

                                        <?php $__currentLoopData = $subjects_assigns; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $subjects_assign): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php
                                                $full_marks = 0;
                                                $head_wise_fail_count = 0;
                                                $total_marks_obtain = 0;

                                                
                                                

                                                $subject_id = $subjects_assign->subject_id;

                                                // exam record for this subject
                                                $recoards = $examRecords->firstWhere('subject_id', $subject_id);
                                                
                                                // ----- FIXED: Get correct head marks -----
                                                $head_marks_data = $subject_head_marks[$subject_id] ?? '{}';
                                                $head_marks_array = json_decode($head_marks_data);              // object
                                                $head_marks_array2 = json_decode($head_marks_data, true);       // array

                                                // student marks
                                                $head_wise_marks_record = $recoards ? json_decode($recoards->head_wise_marks) : null;     // object
                                                $head_wise_marks_record2 = $recoards ? json_decode($recoards->head_wise_marks, true) : []; // array

                                                // ==============================
                                                // HEAD-WISE PASS FAIL CHECK
                                                // ==============================
                                                $head_wise_pass_fail = [];

                                                foreach ($head_marks_array2 as $head_id => $total_marks) {
                                                    $pass_marks = $total_marks * 0.33;  // 33%
                                                    $marks_obtained = $head_wise_marks_record2[$head_id] ?? 0;

                                                    $head_wise_pass_fail[$head_id] = ($marks_obtained >= $pass_marks)
                                                        ? 'Pass'
                                                        : 'Fail';
                                                }

                                                // subject fail if ANY head failed
                                                if (in_array('Fail', $head_wise_pass_fail)) {
                                                    $head_wise_fail_count++;
                                                }

                                                // skip if no marks available
                                                $all_marks_null = true;
                                                if ($head_wise_marks_record) {
                                                    foreach ($head_id_array as $head_id) {
                                                        if (isset($head_wise_marks_record->{$head_id}) && $head_wise_marks_record->{$head_id} !== null) {
                                                            $all_marks_null = false;
                                                            break;
                                                        }
                                                    }
                                                }
                                                if ($all_marks_null) {
                                                    continue;
                                                }
                                            ?>

                                            
                                            <?php if($head_wise_marks_record): ?>
                                                <?php $__currentLoopData = $markHeads; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $head): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                    <?php if(in_array($head->id, $head_id_array)): ?>
                                                        <?php
                                                            $full_marks += $head_marks_array->{$head->id} ?? 0;
                                                            $total_marks_obtain += $head_wise_marks_record->{$head->id} ?? 0;

                                                            $head_wise_grand_total[$head->id] =
                                                                ($head_wise_grand_total[$head->id] ?? 0) +
                                                                ($head_wise_marks_record->{$head->id} ?? 0);
                                                        ?>
                                                    <?php endif; ?>
                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                            <?php else: ?>
                                                <?php
                                                    foreach ($markHeads as $head) {
                                                        if (in_array($head->id, $head_id_array)) {
                                                            $full_marks += $head_marks_array->{$head->id} ?? 0;
                                                        }
                                                    }
                                                ?>
                                            <?php endif; ?>

                                            <?php
                                                $grand_total += $full_marks;

                                                // FINAL SUBJECT GRADE
                                                $total_percentage = ($full_marks > 0)
                                                    ? round(($total_marks_obtain * 100) / $full_marks)
                                                    : 0;

                                                $subject_grade_name = 'F';
                                                $subject_gp = 0; // store GP for this single subject

                                                // SUBJECT GRADE POINT CALCULATION
                                    if ($head_wise_fail_count == 0) {

                                        foreach ($grades as $grade) {
                                            if ($grade->mark_from <= $total_percentage && $grade->mark_to >= $total_percentage) {

                                                $subject_grade_name = $grade->name;
                                                $subject_gp = $grade->gpa;

                                                // FAIL CHECK
                                                if ($subject_grade_name == 'F') {
                                                    $fail_count++;
                                                }

                                                // Only add if not fail
                                                if ($subject_gp > 0) {
                                                    $total_gp_sum += $subject_gp;
                                                }

                                                $total_subjects_count++;
                                            }
                                        }

                                    } else {
                                        // Head-wise fail
                                        $fail_count++;
                                        $total_subjects_count++;
                                    }
                                            ?>

                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    <?php endif; ?>

                                    
                                    <tr>
                                        <td><?php echo e($student->class_roll); ?></td>
                                        <td><?php echo e($student->student_id_no); ?></td>
                                        <td><?php echo e($student->name); ?></td>
                                        <td><?php echo e($position++); ?></td>
                                        <td><?php echo e($class); ?></td>
                                        <td><?php echo e($section ?? '--'); ?></td>

                                        <td class="bg-gray"><b><?php echo e($grand_total); ?></b></td>
                                        <td><b><?php echo e($grand_total_obtain); ?></b></td>

                                        <?php
                                            $grade_name = 'F';
                                            $grand_total_percentage = $grand_total > 0
                                                ? round(($grand_total_obtain * 100) / $grand_total)
                                                : 0;
                                        ?>

                                        <td><b><?php echo e($grand_total_percentage); ?>%</b></td>
                                        <td class="highest-grand-total"></td>
                                        <td>
                                            <?php if($fail_count > 0): ?>
                                                <b>0.00</b>
                                            <?php else: ?>
                                                <b> <?php echo e(number_format($total_gp_sum / $total_subjects_count, 2)); ?> </b>
                                            <?php endif; ?>

                                        </td>

                                        <td>
                                            <?php if($fail_count > 0): ?>
                                                <b>F</b>
                                            <?php else: ?>
                                                <?php
                                                    $grade_name = gradeCalculation(number_format($total_gp_sum / $total_subjects_count, 2))
                                                ?>
                                                <b><?php echo e($grade_name); ?></b>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                            </tbody>
                        </table>
                    </div>
                    <div class="page-break"></div>
                </section>
            </div>
        </div>
    <?php else: ?>

        <?php if(isset($students) &&  $students->isEmpty()): ?>
            <div class="card mt-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom">
                    <h6 class="m-0 table__top__txt">Result Report (Total Result: 0)</h6>
                    <div class="m-0 float-right">
                        <button class="btn btn-sm btn-primary">Print</button>
                    </div>
                </div>
                <div class=" table_content">
                    <section class="page-section">
                        <div class="table-responsive">
                            <table class="table" width="100%">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Roll</th>
                                        <th>Std. ID</th>
                                        <th>Name</th>
                                        <th>Position</th>
                                        <th>Position</th>
                                        <th>Class</th>
                                        <th>Section</th>
                                        <th class="bg-gray">Full Marks</th>
                                        <th>Total Obt.</th>
                                        <th>Obt. Percentage</th>
                                        <th>Highest Marks</th>
                                        <th>GPA</th>
                                        <th>Grade</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td colspan="20" class="text-center">No data available in table</td></tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="page-break"></div>
                    </section>
                </div>
            </div>
        <?php endif; ?>
        
    <?php endif; ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var highestGrandTotalObtain = <?php echo e($highest_grand_total_obtain ?? 0); ?>;
            var elements = document.querySelectorAll('.highest-grand-total');
            elements.forEach(function(element) {
                element.innerHTML = '<b>' + highestGrandTotalObtain + '</b>';
            });
        });

        $('.student_class').on('change', function() {
            let student_class_id = $('.student_class').val();
            getSection(student_class_id);
        });

        let student_class_id = "<?php echo e(isset($student_class_id) ? $student_class_id : ''); ?>";

        if (student_class_id != '') {
            getSection(student_class_id);
        }

        function getSection(student_class_id) {

            let section_id = "<?php echo e(isset($section_id) ? $section_id : ''); ?>";
            if (student_class_id) {
                $.get('<?php echo e(route('sections.list_by_class')); ?>', {
                    student_class_id: student_class_id
                }, function(response) {
                    let sections = response;
                    console.log(sections);
                    let option = '<option value="">Section</option>';
                    for (let i = 0; i < sections.length; i++) {
                        if (section_id == sections[i].id) {
                            option += '<option value=' + sections[i].id + ' selected>' + sections[i].section_name +
                                '</option>';
                        } else {
                            option += '<option value=' + sections[i].id + ' >' + sections[i].section_name +
                                '</option>';
                        }
                    }
                    console.log(option);
                    $('select.section_id').empty().append(option);
                });
            }
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/html/EdueasyCollege/resources/views/report/exam-result/result_report.blade.php ENDPATH**/ ?>