@extends('layouts.master')
@section('content')
    @include('report.exam-result.header-menu', ['active_header' => 'class-rank-report'])
    <div class="card mt-4">
        <div class="card-body card__head">
            <form method="GET" action="{{ route('exam-result.class-rank.report') }}" class="row">
                <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>
                        @foreach ($exams as $examItem)
                            <option value="{{ $examItem->id }}" @selected($exam_id == $examItem->id || (!$exam_id && getCurrentActiveExamId())) >
                                {{ $examItem->exam_name . ' ' . $examItem->academic_year->year }}
                            </option>
                        @endforeach
                    </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>
                        @foreach ($shifts as $shift)
                            <option value="{{ $shift->id }}" @selected($shift_id == $shift->id || (!$shift_id && $loop->first))>
                                {{ $shift->shift_name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    {{ generateDropdown($studentClasses, 'class="form-control select2 student_class_id student_class" id="student_class" name="student_class_id" required', request()->query('student_class_id'), 'Class') }}
                </div>
                <div class="form-group col-lg-2 col-md-6 col-sm-6">
                    {{ generateDropdown([], 'class="form-control section_id" id="section_id" name="section_id" ', request()->query('section_id'), 'Section') }}
                </div>

                <x-group-selector
    name="group_id"
    label=""
    labelText="Group"
    col="form-group col-lg-2 col-md-6 col-sm-6"
    :student_class_id="(int) request()->input('student_class')"
    :required="(int) request()->input('student_class') >= 11"
    :selected="old('group_id') ?? request()->input('group_id')"
/>
                <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>

    @if($students->count() > 0 && count($assignedMarksHead) > 0 && count($subjects_assigns) > 0)
        <div class="card mt-4" id="print-layout">
            <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">Class Rank Report (Total Result: {{ $students->count() }})</h6>
                <div class="m-0 float-right">
                    <x-report-actions
                        :export_pdf="true"
                        :print="true"
                    />
                    <a class="btn btn-secondary btn__export mr-1" title="All Mark Sheet Download" target="_blank" href="{{ route('all-mark-sheet-download',['student_class_id'=> $student_class_id,  'exam_id'=> $exam_id, 'shift_id'=> $shift_id, 'section_id'=> $section_id, 'group_id'=> $group_id ]) }}">
                        All Mark Sheet
                    </a>
                </div>
            </div>
            <div class="row pt-2">
                <div class="col-md-12">
                    <div class="table-responsive table_content">
                        <table class="table table-strip">
                            <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 <br> Marks</th>
                                    <th>Total Obt.</th>
                                    <th>Obt. Percentage</th>
                                    <th>Highest Marks</th>
                                    <th>GPA</th>
                                    <th>Grade</th>
                                    <th>Status</th>
                                    <th>Download</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;
@endphp

{{-- {{ dd($student->id, $students_with_grand_total, $head_wise_fail_count, $subjects_assigns) }} --}}


@foreach ($students_with_grand_total as $data)
    @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;
        }
    @endphp

    @if ($examRecords->isNotEmpty())

        @foreach ($subjects_assigns as $subjects_assign)
            @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;
                }
            @endphp

            {{-- CALCULATE TOTALS --}}
            @if ($head_wise_marks_record)
                @foreach ($markHeads as $head)
                    @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);
                        @endphp
                    @endif
                @endforeach
            @else
                @php
                    foreach ($markHeads as $head) {
                        if (in_array($head->id, $head_id_array)) {
                            $full_marks += $head_marks_array->{$head->id} ?? 0;
                        }
                    }
                @endphp
            @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++;
    }
            @endphp

        @endforeach
    @endif

    {{-- TABLE ROW START --}}
    <tr>
        <td>{{ $student->class_roll }}</td>
        <td>{{ $student->student_id_no }}</td>
        <td>{{ $student->name }}</td>
        <td>{{ $position++ }}</td>
        <td>{{ $class }}</td>
        <td>{{ $section ?? '--' }}</td>

        <td class="bg-gray"><b>{{ $grand_total }}</b></td>
        <td><b>{{ $grand_total_obtain }}</b></td>

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

        <td><b>{{ $grand_total_percentage }}%</b></td>
        <td class="highest-grand-total"></td>
        <td>
            @if ($fail_count > 0)
                <b>0.00</b>
            @else
                <b> {{ number_format($total_gp_sum / $total_subjects_count, 2) }} </b>
            @endif
        </td>

        <td>
            @if ($fail_count > 0)
                <b>F</b>
            @else
                @php
                    $grade_name = gradeCalculation(number_format($total_gp_sum / $total_subjects_count, 2))
                @endphp
                <b>{{ $grade_name }}</b>
            @endif
        </td>

        <td>
            @if ($fail_count > 0)
                <span class="badge " style="border: 1px solid rgb(255, 99, 99); font-size: 13px; color: rgb(255, 99, 99); padding: 8px; border-radius: 1px; width: 100px;">
                    <i class="fas fa-exclamation-triangle"></i> Fail
                </span>
            @else
                <span class="badge " style="border: 1px solid #0abb75;font-size: 14px;color: var(--white);padding: 8px !important;border-radius: 1px;width: 100px;background: #0abb75;">
                    <i class="far fa-check-circle"></i> Pass
                </span>
            @endif
        </td>

        <td>
            <a target="_blank" href="{{ route('individule-mark-sheet-download',['student_id'=> $student->student_id_no, 'student_class_id'=> $student->student_class_id, 'exam_id'=> $exam_id, 'shift_id'=> $shift_id, 'section_id'=> $student->section_id ]) }}">
                <span class="badge " style="border: 1px solid var(--light-blue-active);font-size: 14px;color: #377dff;padding: 8px !important;border-radius: 1px;background: rgba(55, 125, 255, .15);">
                    <i class="fa fa-arrow-down" aria-hidden="true" style="margin-right: 6px;"></i>
                Download
                </span>
            </a>
        </td>
    </tr>
@endforeach

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    @else

        @if (isset($students) && empty($students))
            <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">Class Rank 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 <br> 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>
        @endif
    @endif

    @push('scripts')
        <script src="{{ asset('js/report-actions.js') }}"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                var highestGrandTotalObtain = {{ $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 = "{{ request()->query('student_class_id') ?? '' }}";

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

            function getSection(student_class_id){

                let section_id = "{{ request()->query('section_id') ?? '' }}";
                if(student_class_id){
                    $.get('{{ route('sections.list_by_class') }}', { student_class_id: student_class_id }, function(response) {
                        let sections = response;
                        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>';
                            }
                        }
                        $('select.section_id').empty().append(option);
                    });
                }
            }

            const exportPrintOptions = {
                url: '{{ route("exam-result.class-rank.print") }}',
                filename: 'class-rank-report',
                extraData: @json(request()->query()),
            };

            const exportPdfOptions = {
                url: '{{ route("exam-result.class-rank.pdf") }}',
                filename: 'class-rank-report',
                extraData: @json(request()->query()),
            };
        </script>
    @endpush
@endsection

