@extends('layouts.master')
@section('content')
    <div class="card">
        <div class="card-body card__head">
            <form method="POST" action="{{ route('reports.grade.count_by_class') }}" class="row">
                @csrf
                <div class="col-md-6">
                    <div class="row">
                        <div class="form-group col-lg-4 col-md-12 col-sm-12">
                            {{ generateDropdown($exams, 'class="form-control exam_id" id="exam_id" name="exam_id" required', $exam_id, 'Exam') }}
                        </div>

                        <div class="form-group col-lg-4 col-md-6 col-sm-6">
                            {{ generateDropdown($academicYears, 'name="academic_year" class="form-control academic_year" id="academic_year" required', $academic_year, 'Year') }}
                        </div>

                        <div class="form-group col-lg-4 col-md-6 col-sm-6">
                            {{ generateDropdown($shifts, 'class="form-control shift_id" id="shift_id" name="shift_id" ', $shift_id, 'Shift') }}
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="row">
                        <div class="form-group col-lg-3 col-md-6 col-sm-6">
                            {{ generateDropdown($studentClasses, 'class="form-control select2 student_class" id="student_class" name="student_class_id"', $student_class_id, 'Class') }}
                        </div>

                        <div class="form-group col-lg-3 col-md-6 col-sm-6">
                            {{ generateDropdown([], 'class="form-control section_id" id="section_id" name="section_id" ', $section_id, 'Section') }}
                        </div>

                        <div class="form-group col-lg-3 col-md-6 col-sm-6">
                            {{ generateDropdown($groups, 'class="form-control group_id" id="group_id" name="group_id"', $group_id, 'Group') }}
                        </div>
                        <div class="form-group col-lg-3 col-md-6 col-sm-6">
                            <button type="submit" class="btn btn-info">Search</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

@if (isset($students) && !$students->isEmpty())
    @php

    $total_grade_count = [];
    for ($i=1; $i <= count($total_grade_count_arr); $i++) { 
        $total_grade_count_arr[$i];
        $total_grade_count["total_grade_count$i"] = 0;
    }

        $grades_str = '';
        $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;

        // Calculate grand total obtained for each student
        $students_with_grand_total = [];

        foreach ($students as $student) {
            $grand_total_obtain = 0;
            $examRecords = $student?->examRecords ?? '';

            if ($examRecords->isNotEmpty()) {
                foreach ($examRecords as $record) {
                    $head_wise_marks_record = json_decode($record->head_wise_marks);
                    $head_marks_data = $subject_head_marks[$record->subject->id];
                    $head_marks_array = json_decode($head_marks_data);
                    $total_marks_obtain = 0;

                    foreach ($markHeads as $head) {
                        if (in_array($head->id, $head_id_array)) {
                            $total_marks_obtain += $head_wise_marks_record?->{$head->id} ?? 0;
                        }
                    }

                    $grand_total_obtain += $total_marks_obtain;
                }
            }

            // Add student and their total obtained marks
            $students_with_grand_total[] = [
                'student' => $student,
                'grand_total_obtain' => $grand_total_obtain
            ];

            // Update highest total if this student's grand_total_obtain is higher
            if ($grand_total_obtain > $highest_grand_total_obtain) {
                $highest_grand_total_obtain = $grand_total_obtain;
            }
        }

        // Sort students by grand_total_obtain in descending order
        usort($students_with_grand_total, function ($a, $b) {
            return $b['grand_total_obtain'] <=> $a['grand_total_obtain'];
        });

        $position = 1; // To assign position based on sorted order
    @endphp

    @foreach ($students_with_grand_total as $data)
        @php
            $student = $data['student'];
            $grand_total_obtain = $data['grand_total_obtain'];
            $grand_total = 0;
            $fail_count = 0;
            $examRecords = $student?->examRecords ?? '';
            $section = $sections[$student->section_id] ?? '';
            $class = $studentClasses[$student->student_class_id] ?? '';
            $academicYear = $academicYears[$academic_year] ?? '';
        @endphp

        @if ($examRecords->isNotEmpty())
            @foreach ($examRecords as $record)
                @php
                    $full_marks = 0;
                    $head_wise_total_obtain = [];
                    $total_marks_obtain = 0;

                    $head_wise_marks_record = json_decode($record->head_wise_marks);
                    $head_marks_data = $subject_head_marks[$record->subject->id];
                    $head_marks_array = json_decode($head_marks_data);
                @endphp

                @if (isset($head_wise_marks_record))
                    @foreach ($markHeads as $head)
                        @if (in_array($head->id, $head_id_array))
                            @php
                                $full_marks += $head_marks_array->{$head?->id};
                                $total_marks_obtain += $head_wise_marks_record?->{$head?->id} ?? 0;
                            @endphp
                        @endif
                    @endforeach

                    @php
                        $grand_total += $full_marks;
                    @endphp
                @endif
            @endforeach
        @endif

            @php
                $grade_name = '';
                $grade_point = '';
                $grade_name_remarks = '';
                $grand_total_percentage = $grand_total_obtain > 0 && $grand_total > 0
                    ? round(($grand_total_obtain * 100) / $grand_total)
                    : 0;
                foreach ($grades as $grade) {
                    if ($grade->mark_from <= $grand_total_percentage && $grade->mark_to >= $grand_total_percentage) {
                        $grade_name = $grade->name;
                        //count total grade
                        for ($i=1; $i <= count($total_grade_count_arr); $i++) { 
                            $total_grade_count_arr[$i];
                            if($grade_name === $total_grade_count_arr[$i]){
                               
                                $total_grade_count["total_grade_count$i"]++;
                            }
                        }
                        $grade_point = $grade;
                        $grade_name_remarks = $grade->remark;
                    }
                }
            @endphp
    @endforeach


<!-- ===========new table -->
<div class="card mt-4">
    <div class="card-header d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 table__top__txt">Total Grade Count (Total Student: {{ count($students) }})</h6>
        <div class="m-0 float-right">
            
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="card-header">Branch: {{auth()->user()->branch->branch_name}}, Shift: {{ $shift_name}}, Class: {{ $class}}

        </div>
            <div class="table-responsive" >
                <table class="table">
                    <thead class="thead-light">
                        <tr>
                            <th>Section</th>
                            @php
                                for($i=1; $i <= count($total_grade_count_arr); $i++){ 
                                    echo "<th>".$total_grade_count_arr[$i]."<th>";
                                }
                            @endphp
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>{{ $section }}</td>
                            @php
                                for($i=1; $i <= count($total_grade_count_arr); $i++){ 
                                    echo "<td>".$total_grade_count["total_grade_count$i"]."<td>";
                                }
                            @endphp
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


    @endif
@endsection

@section('scripts')
    <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 = "{{ isset($student_class_id) ? $student_class_id : '' }}";

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

        function getSection(student_class_id) {

            let section_id = "{{ isset($section_id) ? $section_id : '' }}";
            if (student_class_id) {
                $.get('{{ route('sections.list_by_class') }}', {
                    student_class_id: student_class_id
                }, function(response) {
                    let sections = response;
                    console.log(sections);
                    let option = '<option value="">--Select Section--</option>';
                    for (let i = 0; i < sections.length; i++) {
                        // if(sections[i].student_class_id == student_class_id){
                        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>
@endsection
