@extends('schoolLayout.app')
@section('content')
    <div class="px-6 py-6 bg-[#f9fafc] min-h-screen">
        @include('successError')
        @include('student.stdProfilePartials')

        <!-- Tabs Section -->
        <div class="flex justify-between mt-4 w-full px-4 bg-white pt-2 border-b border-gray-200 items-center">
            <div class="flex space-x-4 bg-white">
                <button class="tab-btn pb-4 pt-2 text-gray-500 font-semibold"
                    onclick="location.href='{{ route('student.profile', $student->id) }}'">
                    Admission & Personal Details
                </button>
                <button class="tab-btn px-4 pb-4 bg-white pt-2   font-semibold ">
                    Academic Information
                </button>
                {{-- <button class="tab-btn pb-4 pt-2 text-gray-500 font-semibold">
            Assignments & Homework
          </button>
          <button class="tab-btn pb-4 pt-2 text-gray-500 font-semibold">
            Exam & Performance
          </button> --}}
                <button class="tab-btn pb-4 pt-2 text-gray-500 font-semibold"
                    onclick="location.href='{{ route('student.profile.attendance', $student->id) }}'">
                    Attendance Records
                </button>
                <button class="tab-btn pb-4 pt-2 text-gray-500 font-semibold"
                    onclick="location.href='{{ route('student.profile.documents', $student->id) }}'">
                    Documents & Certificates
                </button>
                <button class="tab-btn px-4 pb-4 bg-white pt-2 border-b-2 border-blue-500 font-semibold  "
                    onclick="location.href='{{ route('student.profile.promote', $student->id) }}'">
                    Promote Student
                </button>
            </div>
        </div>

        <div class="flex gap-6 mt-10 flex-col md:flex-row">
            <!-- Left Section (Form) -->
            <div class="md:w-[70%] w-full bg-white shadow p-6 rounded">
                <form method="POST" action="{{ route('student.profile.promote.store') }}" id="admForm">
                    @csrf

                    <h2 class="text-2xl font-bold mb-6 text-blue-700">Promote Student</h2>

                    <!-- Promote to Class -->
                    <div class="mb-6">
                        <label for="next-class-select" class="block mb-2 font-semibold text-gray-700">Promote to Class
                        </label>
                        <select name="next_class_id" class="w-full p-3 border rounded focus:ring-2 focus:ring-blue-400"
                            id="next-class-select">
                            <option value="" disabled {{ old('class') == '' ? 'selected' : '' }}>Select Class</option>
                            @foreach ($classes as $class)
                                <option value="{{ $class->id }}"
                                    {{ old('class', $student->latestAdmission->class_id ?? '') == $class->id ? 'selected' : '' }}>
                                    {{ $class->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Fee Structure -->
                    <div id="fee-structure-container" class="mb-6">
                        <label class="block mb-2 font-semibold">Fee Structure</label>
                        <p id="fee-error" class="text-red-500 text-sm hidden">Please select at least one fee.</p>
                        <div id="fee-checkboxes" class="grid grid-cols-1 md:grid-cols-2 gap-2">
                            <!-- Fees will be loaded here -->
                        </div>
                        <div class="mt-4">
                            <label class="block font-semibold">Total Amount</label>
                            <input type="text" name="total_amount" id="total_amount"
                                class="w-full p-2 border rounded bg-gray-100" readonly value="0.00" />
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="mt-8 text-right">
                        <button type="submit"
                            class="bg-blue-600 text-white px-8 py-2 rounded-lg shadow hover:bg-blue-700 transition">
                            Submit Promotion
                        </button>
                    </div>
                    <input type="hidden" name="student_id" value="{{ $student->id }}">
                    <input type="hidden" name="current_class_id" value="{{ $student->latestAdmission->class_id }}">
                </form>
            </div>s

            <!-- Right Section (Class Info) -->
            <div class="md:w-[30%] w-full bg-white min-h-44 p-6 shadow rounded-lg self-start flex-grow-0 mb-6 md:mb-0"
                id="class-info-box" data-current-class-id="{{ $student->latestAdmission->class_id ?? '' }}">
                <h2 class="text-xl font-semibold mb-4 text-blue-700">Class Information</h2>
                <div class="mb-4">
                    <h3 class="text-gray-400 text-md">Current Class</h3>
                    <span class="inline-block bg-blue-100 text-blue-700 px-3 py-1 rounded-2xl text-base font-semibold mt-1">
                        {{ $student->latestAdmission->class->name ?? 'Not Enrolled' }}
                    </span>
                </div>
                <div>
                    <h3 class="text-gray-400 text-md">Academic Year</h3>
                    <span
                        class="inline-block bg-green-100 text-green-700 px-3 py-1 rounded-2xl text-base font-semibold mt-1">
                        {{ $student->latestAdmission->session_year }}
                    </span>
                </div>
            </div>
        </div>
    </div>

    <style>
        label.error {
            color: #ef4444;
            /* Tailwind's red-500 */
            font-size: 0.875rem;
            /* text-sm */
            margin-top: 0.25rem;
            display: block;
        }
    </style>
   <script>
    $(document).ready(function () {
        // Load fee structure on page load if class is pre-selected
        const defaultClassId = $('#next-class-select').val();
        if (defaultClassId) {
            fetchFeeStructureHTML(defaultClassId);
        }

        // Handle class change
        $('#next-class-select').on('change', function () {
            let selectedClassId = $(this).val();
            if (selectedClassId) {
                fetchFeeStructureHTML(selectedClassId);
            } else {
                $('#fee-checkboxes').html('');
                $('#total_amount').val('0.00');
            }
        });

        // Fetch and render fee structure
        function fetchFeeStructureHTML(classId) {
            $.get(`{{ route('fetch-fee-structure') }}?class_id=${classId}`, function (response) {
                $('#fee-checkboxes').html(response.html);
                attachChangeEvents(); // attach events to new inputs
                calculateTotalFee();
            });
        }

        // Calculate total from checked checkboxes and their corresponding editable inputs
        function calculateTotalFee() {
            let total = 0;
            $('.feeCheckbox:checked').each(function () {
                let $checkbox = $(this);
                let amountInput = $checkbox.closest('label').find('.editableAmountInput');
                let value = parseFloat(amountInput.val());
                if (!isNaN(value)) {
                    total += value;
                }
            });
            $('#total_amount').val(total.toFixed(2));
        }

        // Attach change events after new elements are loaded
        function attachChangeEvents() {
            $(document).off('change', '.feeCheckbox');
            $(document).off('input', '.editableAmountInput');

            $(document).on('change', '.feeCheckbox', function () {
                calculateTotalFee();
            });

            $(document).on('input', '.editableAmountInput', function () {
                calculateTotalFee();
            });
        }

        // Validation
        $.validator.addMethod("greaterThanCurrent", function (value, element) {
            let currentClassId = $('#class-info-box').data('current-class-id');
            return parseInt(value) > parseInt(currentClassId);
        }, "Promotion class must be greater than current class");

        $('#admForm').validate({
            ignore: [],
            rules: {
                next_class_id: {
                    required: true,
                    greaterThanCurrent: true
                }
            },
            messages: {
                next_class_id: {
                    required: "Please select promotion class",
                    greaterThanCurrent: "Promotion class must be greater than current class"
                }
            },
            submitHandler: function (form) {
                if ($('.feeCheckbox:checked').length === 0) {
                    $('#fee-error').removeClass('hidden');
                    return false;
                } else {
                    $('#fee-error').addClass('hidden');
                }
                form.submit();
            }
        });

        // Initial bind (if page preloaded)
        attachChangeEvents();
    });
</script>

@endsection
