@extends('layouts.master')
@section('content')
    <div class="card marks__entry__head">
        <div class="card-header py-3 card__head">
            <form method="POST" action="{{ route('student_by_class') }}">
                @csrf
                <div class="row">
                    <div class="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6">
                        <select name="exam_id" class="form-control select2 exam_id" id="exam_id" required>
                            <option value="">Exam</option>
                            @foreach ($exams as $exam)
                                <option value="{{ $exam->id }}" {{ getCurrentActiveExamId() == $exam->id ? 'selected' : '' }}>
                                    {{ $exam->exam_name . ' ' . $exam->academic_year->year }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6">
                        <select name="shift_id" class="form-control shift_id" id="shift_id" required>
                            <option value="">Shift</option>
                            @foreach ($shifts as $shift)
                                <option value="{{ $shift->id }}" {{ $loop->first ? 'selected' : '' }}>
                                    {{ $shift->shift_name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6">
                        {{ generateDropdown($studentClasses, 'class="form-control select2 student_class student_class_id" id="student_class" name="student_class_id" required', $student_class_id, "Class") }}
                    </div>
                    <div class="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6">
                        {{ generateDropdown([], 'class="form-control section_id" id="section_id" name="section_id"', $section_id, 'Section') }}
                    </div>
                    <x-group-selector name="group_id" label="" labelText="Group" col="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6"
                                      :student_class_id="$student_class_id" :required="$student_class_id >= 11" :selected="old('group_id') ?? $group_id"/>
                    <div class="form-group col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6">
                        {{ generateDropdown('', 'class="form-control subject_id" id="subject_id" name="subject_id" required', '', "Subject") }}
                    </div>
                    <div  class="col-lg-4 col-xl-2 col-xxl-2 col-md-6 col-6 btn__search">
                        <div class="form-group">
                            <button type="submit" class="btn btn-info">Search</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    @if (isset($students))
        <div class="card mt-4 marks__entry__body">
            <div class="row justify-content-center">
                <div class="col-md-12">
                    <form method="POST" action="{{ route('marks.store') }}" class="form-inline">
                        @csrf
                        <div class="table-responsive">
                            @if($assignedMarksHead)
                                <input type="hidden" name="exam_id" value="{{$exam_id ?? ''}}">
                                <input type="hidden" name="student_class_id" value="{{$student_class_id ?? ''}}">
                                <input type="hidden" name="shift_id" value="{{$shift_id ?? ''}}">
                                <input type="hidden" name="branch_id" value="{{$branch_id ?? ''}}">
                                <input type="hidden" name="section_id" value="{{$section_id ?? ''}}">
                                <input type="hidden" name="subject_id" value="{{$subject_id ?? ''}}">
                                <input type="hidden" name="group_id" value="{{$group_id ?? ''}}">
                                <input type="hidden" name="academic_year" value="{{$academic_year ?? ''}}">
                                <table class="table">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>Sl No</th>
                                        <th>Roll</th>
                                        <th>Student ID</th>
                                        <th class="th__name">Name</th>
                                        @php
                                            $head_marks_array = json_decode($assignedMarksHead->head_marks, true);
                                        @endphp
                                        @foreach ($markHeads as $head)
                                            @if (isset($head_marks_array[$head->id]) && $head_marks_array[$head->id] !== null)
                                                <th class="th__marks__entry"
                                                    style="width: 10%; max-width: 10%; overflow: hidden;">
                                                    {{ $head->short_name }}({{ $head_marks_array[$head->id] }})
                                                </th>
                                            @endif
                                        @endforeach
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @foreach ($students as $key=>$student)
                                        <tr>
                                            <td>{{ $key + 1 }}</td>
                                            <td>{{ $student->class_roll }}</td>
                                            <td>{{ $student->student_id_no }}</td>
                                            <td class="td__name">
                                                {{ $student->first_name }} {{ $student->last_name }}
                                                <input type="hidden" name="student_id[]" value="{{ $student->id }}">
                                            </td>
                                            {{--                                        <td>{{ $student->section?->section_name ?? '--' }}</td>--}}
                                            @php
                                                $head_wise_marks = $student->examRecords->isNotEmpty()
                                                    ? json_decode($student->examRecords->first()->head_wise_marks, true)
                                                    : [];
                                            @endphp
                                            @foreach ($markHeads as $head)
                                                @if (isset($head_marks_array[$head->id]) && $head_marks_array[$head->id] !== null)
                                                    <td class="w-15">
                                                        <input
                                                            type="number"
                                                            name="marks[{{ $student->id }}][]"
                                                            value="{{ $head_wise_marks[$head->id] ?? 0 }}"
                                                            class="form-control"
                                                            oninput="this.value = Math.abs(this.value)"
                                                            onchange="MinMaxInput(this, 0, {{ $head_marks_array[$head->id] }}, true)"
                                                        >
                                                        <input type="hidden" value="{{ $head->id }}"
                                                               name="head_id[{{ $student->id }}][]"
                                                               class="form-control">
                                                    </td>
                                                @endif
                                            @endforeach
                                        </tr>
                                    @endforeach
                                    </tbody>
                                </table>
                            @else
                                <h5>Mark's head is not assigned for this Exam/Class yet. Please assign Mark's head, and
                                    then try.</h5>
                            @endif
                        </div>
                        @if($assignedMarksHead)
                            <div class="form-group flex d-flex w-100 justify-content-end">
                                <button type="submit" class="btn btn-submit m-4">Submit</button>
                            </div>
                        @endif
                    </form>
                </div>
            </div>
        </div>
    @endif
@stop


@section('scripts')
<script>
$(document).ready(function () {

    const $studentClass   = $('.student_class');
    const $department     = $('.department_id');
    const $sectionSelect  = $('select.section_id');
    const $subjectSelect  = $('select.subject_id');

    // On class change
    $studentClass.on('change', function () {
        const student_class_id = $(this).val();
        const department_id = $department.val();

        getSection(student_class_id);
        getSubjects(student_class_id, department_id);
    });

    // On department change
    $department.on('change', function () {
        const student_class_id = $studentClass.val();
        const department_id = $(this).val();

        getSubjects(student_class_id, department_id);
    });

    // Load on page reload (edit/filter)
    let student_class_id = "{{ $student_class_id ?? '' }}";
    let department_id    = "{{ $department_id ?? '' }}";

    if (student_class_id) {
        getSection(student_class_id);
        getSubjects(student_class_id, department_id);
    }

    function getSection(student_class_id) {
        let section_id = "{{ $section_id ?? '' }}";

        if (!student_class_id) return;

        $.get('{{ route('sections.list_by_class') }}', {
            student_class_id: student_class_id
        }).done(function (response) {

            let option = '<option value="">Section</option>';

            response.forEach(function (section) {
                const selected = section_id == section.id ? ' selected' : '';
                option += `<option value="${section.id}"${selected}>${section.section_name}</option>`;
            });

            $sectionSelect.html(option);
        });
    }

    function getSubjects(student_class_id, department_id = '') {

        let subject_id = "{{ $subject_id ?? '' }}";

        if (!student_class_id) return;

        $.get('{{ route('subjects.list_by_class') }}', {
            student_class_id: student_class_id,
            department_id: department_id // ✅ send department
        }).done(function (response) {

            let option = '<option value="">Subject</option>';

            response.forEach(function (item) {
                const selected = subject_id == item.subject_id ? ' selected' : '';
                option += `<option value="${item.subject_id}"${selected}>
                                ${item.subject.subject_name}
                           </option>`;
            });

            $subjectSelect.html(option);
        });
    }
});

// Marks validation
function MinMaxInput(element, min, max, zeroAllowed) {
    if (element.value == 0 && zeroAllowed) return;
    if (element.value > max) element.value = max;
    if (element.value < min) element.value = min;
}
</script>
@endsection


@section('scripts2')
    <script>
        $(document).ready(function () {
            // Cache selectors
            const $studentClass = $('.student_class');
            const $department = $('.department_id');
            const $sectionSelect = $('select.section_id');
            const $subjectSelect = $('select.subject_id');
            $studentClass.on('change', function () {
                const student_class_id = $(this).val();
                getSection(student_class_id);
                getSubjects(student_class_id);
            });
            let student_class_id = "{{ isset($student_class_id) ? addslashes($student_class_id) : '' }}";
            if (student_class_id !== '') {
                getSection(student_class_id);
                getSubjects(student_class_id);
            }
            function getSection(student_class_id) {
                let section_id = "{{ isset($section_id) ? addslashes($section_id) : '' }}";
                if (student_class_id) {
                    $.get('{{ route('sections.list_by_class') }}', {student_class_id: student_class_id})
                        .done(function (response) {
                            let option = '<option value="">Section</option>';
                            response.forEach(function (section) {
                                const selected = section_id == section.id ? ' selected' : '';
                                option += `<option value="${section.id}"${selected}>${section.section_name}</option>`;
                            });
                            $sectionSelect.empty().append(option);
                        })
                        .fail(function (jqXHR, textStatus) {
                            console.error('Section load failed:', textStatus);
                        });
                }
            }
            function getSubjects(student_class_id) {
                let subject_id = "{{ isset($subject_id) ? addslashes($subject_id) : '' }}";
                if (student_class_id) {
                    $.get('{{ route('subjects.list_by_class') }}', {student_class_id: student_class_id})
                        .done(function (response) {
                            let option = '<option value="">Subject</option>';
                            response.forEach(function (item) {
                                if (item.student_class_id == student_class_id) {
                                    const selected = subject_id == item.subject_id ? ' selected' : '';
                                    option += `<option value="${item.subject_id}"${selected}>${item.subject.subject_name}</option>`;
                                }
                            });
                            $subjectSelect.empty().append(option);
                        })
                        .fail(function (jqXHR, textStatus) {
                            console.error('Subjects load failed:', textStatus);
                        });
                }
            }
        });
        function MinMaxInput(element, min, max, zeroAllowed) {
            if (element.value == 0 && zeroAllowed) return;
            if (element.value > max) element.value = max;
            if (element.value < min) element.value = min;
        }
    </script>
@endsection