@extends('schoolLayout.app')
@section('content')
    <div class="bg-[#f9fafc] min-h-screen px-8 py-8">
        <div class="flex justify-between items-center">
            @include('stdFeeMgt.partialhead')
        </div>
        @include('successError')
        <div class="bg-white shadow-sm rounded-lg p-6 w-full">
            <h2 class="text-2xl font-bold text-gray-700 mb-4">
                Generate Fee Slips
            </h2>
            <form action="{{ route('generate-fee-structure') }}" method="POST">
                @csrf
                <div class="mb-4">
                    <div class="flex space-x-6">
                        <label class="flex items-center space-x-2">
                            <input type="radio" name="feeMode" checked="checked" class="form-radio text-blue-600"
                                value="single" />
                            <span>Single Student</span>
                        </label>
                        <label class="flex items-center space-x-2">
                            <input type="radio" name="feeMode" class="form-radio text-blue-600" value="class" />
                            <span>Whole Class</span>
                        </label>
                    </div>
                </div>
                <div class="grid grid-cols-3 gap-4 mb-4">
                    <div class="relative w-full" id="studentSearchDiv">
                        <label class="block font-medium text-gray-700 mb-1">Student</label>
                        <div class="relative ">
                            <span class="absolute inset-y-0 left-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-magnifying-glass"></i>
                            </span>
                            <input type="text" id="studentSearch" name="student"
                                class="w-full p-2 pl-10 border rounded focus:ring focus:ring-blue-300"
                                placeholder="Search student..." oninput="filterStudents()" onclick="showDropdown()" />

                        </div>
                        <ul id="studentDropdown" class="absolute w-full border rounded bg-white shadow-lg mt-1 hidden z-10">
                            @if ($students)
                                @foreach ($students as $student)
                                    <li data-cid="{{ $student->classes->first()->id }}"
                                        data-sid="{{ $student->sections->first()->id }}" data-std_id = "{{ $student->id }}"
                                        class="p-2 cursor-pointer hover:bg-gray-200"
                                        onclick="selectStudent('{{ $student->student_name }}|{{ $student->classes->first()->name }}|{{ $student->sections->first()->name }}|{{ $student->latestAdmission->reg_no }}',this)">
                                        {{ $student->student_name }} | {{ $student->classes->first()->name }} |
                                        {{ $student->sections->first()->name }} | {{ $student->latestAdmission->reg_no }}
                                    </li>
                                @endforeach
                            @endif
                        </ul>
                        @error('student')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Class</label>

                        <select id="classDropdown" name="class" class="w-full p-2 border rounded" disabled>
                            <option value=""> Select Class</option>
                            @foreach ($classes as $class)
                                <option value="{{ $class->id }}"> {{ $class->name }}</option>
                            @endforeach
                        </select>
                        @error('class')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Section</label>
                        <select id="sectionDropdown" name="section" class="w-full p-2 border rounded" disabled>
                            @foreach ($sections as $section)
                                <option value="{{ $section->id }}">Section {{ $section->name }}</option>
                            @endforeach
                        </select>
                        @error('section')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <div class="grid grid-cols-3 gap-4 mb-4">
                    @php
                        $currentYear = date('Y');
                        $years = range($currentYear - 10, $currentYear);
                        $months = [
                            '1' => 'January',
                            '2' => 'February',
                            '3' => 'March',
                            '4' => 'April',
                            '5' => 'May',
                            '6' => 'June',
                            '7' => 'July',
                            '8' => 'August',
                            '9' => 'September',
                            '10' => 'October',
                            '11' => 'November',
                            '12' => 'December',
                        ];
                        $currentMonth = date('m');
                    @endphp


                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Year</label>
                        <select name="year" class="w-full p-2 border rounded">
                            @foreach ($years as $year)
                                <option value="{{ $year }}" {{ $year == $currentYear ? 'selected' : '' }}>
                                    {{ $year }}
                                </option>
                            @endforeach
                        </select>

                        @error('year')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>


                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Month</label>
                        <select name="month" class="w-full p-2 border rounded">
                            @foreach ($months as $num => $month)
                                <option value="{{ $num }}" {{ $num == $currentMonth ? 'selected' : '' }}>
                                    {{ $month }}
                                </option>
                            @endforeach
                        </select>

                        @error('month')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>

                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Due Date</label>
                        <input type="date" name="dueDate" class="w-full p-2 border rounded" />
                        @error('dueDate')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <!-- Select Applicable Fees -->
                <h3 class="text-xl font-semibold text-gray-700 mt-8 mb-4">
                    Select Applicable Fees
                </h3>
                <div class="grid grid-cols-4 gap-4 mb-4 " id="feeStructureContainer">

                </div>

                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block font-medium text-gray-700 mb-1">Amount</label>
                        <div id="totalAmount" class="w-full p-2 border rounded bg-gray-100">
                            0.00
                        </div>
                    </div>

                </div>

                <!-- Buttons -->
                <div class="flex justify-end space-x-4 mt-4">
                    <button type="reset" class="px-4 py-2 border border-gray-300 text-gray-700 rounded">
                        Cancel
                    </button>
                    <button type="submit" id="generateFeeSlipBtn"
                        class="px-4 py-2 bg-[#1B9AF5] text-white rounded opacity-50">
                        Generate Fee Slip
                    </button>

                </div>
                <input type="hidden" name="total_fee_generated" id="total_fee_generated" value="">
                <input type="hidden" name="student_class" id="student_class" value="">
                <input type="hidden" name="student_section" id="student_section" value="">
                <input type="hidden" name="student_id" id="student_id" value="">
                <input type="hidden" name="student_name" id="student_name" value="">
                <input type="hidden" name="student_class_name" id="student_class_name" value="">
                <input type="hidden" name="student_section_name" id="student_section_name" value="">

            </form>
            <!-- Form End -->
        </div>
    </div>

@endsection

@section('script')
    <script>
        function showDropdown() {
            document.getElementById("studentDropdown").classList.remove("hidden");
        }

        function filterStudents() {
            let input = document
                .getElementById("studentSearch")
                .value.toLowerCase();
            let dropdown = document.getElementById("studentDropdown");
            let options = dropdown.getElementsByTagName("li");

            for (let i = 0; i < options.length; i++) {
                let txtValue = options[i].textContent || options[i].innerText;
                options[i].style.display = txtValue.toLowerCase().includes(input) ?
                    "" :
                    "none";
            }
        }


        document.addEventListener("click", function(event) {
            if (!event.target.closest(".relative")) {
                document.getElementById("studentDropdown").classList.add("hidden");
            }
        });

        document.addEventListener("change", function(event) {
            let classDropdown = document.getElementById("classDropdown");
            let sectionDropdown = document.getElementById("sectionDropdown");
            if (event.target.name === "feeMode") {
                const studentSearch = document.querySelector('input[name="feeMode"]:checked').value;
                const studentSearchDiv = document.getElementById("studentSearchDiv");

                if (studentSearch === "class") {
                    classDropdown.disabled = false;
                    sectionDropdown.disabled = false;
                    studentSearchDiv.classList.add("hidden");
                } else {
                    classDropdown.disabled = true;
                    sectionDropdown.disabled = true;
                    studentSearchDiv.classList.remove("hidden");
                }
            }
        });

        function selectStudent(studentData, thisElement) {
            let [name, studentClass, studentSection, reg_no] = studentData.split('|');
            let class_id_selected = thisElement.getAttribute('data-cid');
            let section_id_selected = thisElement.getAttribute('data-sid');
            let student_id = thisElement.getAttribute('data-std_id');
            document.getElementById("studentSearch").value = name;

            let classDropdown = document.getElementById("classDropdown");
            let sectionDropdown = document.getElementById("sectionDropdown");

            // Set the selected values for class and section
            if (classDropdown) classDropdown.value = class_id_selected;
            if (sectionDropdown) sectionDropdown.value = section_id_selected;

            // Get the currently selected feeMode value
            let feeMode = document.querySelector('input[name="feeMode"]:checked')?.value;

            // Disable dropdowns if feeMode is "single", otherwise enable them
            let isSingleMode = feeMode === "single";
            classDropdown.disabled = isSingleMode;
            sectionDropdown.disabled = isSingleMode;
            if (isSingleMode) {
                document.getElementById("student_section").value = section_id_selected;
                document.getElementById("student_class").value = class_id_selected;
                document.getElementById("student_id").value = student_id;
                document.getElementById("student_name").value = name;
                document.getElementById("student_class_name").value = studentClass;
                document.getElementById("student_section_name").value = studentSection;

            }

            document.getElementById("studentDropdown").classList.add("hidden");

            $.ajax({
                url: "{{ route('fetch-fee-by-student') }}",
                type: 'GET',
                data: {
                    class_id: class_id_selected,
                    student_id: student_id
                },
                success: function(response) {
                    $('#feeStructureContainer').html(response.html);
                    updateTotalAmount();
                },
                error: function() {
                    alert('Error fetching fee structure.');
                }
            });

        }

        function updateTotalAmount() {
            let total = 0;

            document.querySelectorAll('.feeCheckbox').forEach(function(checkbox) {
                if (checkbox.checked) {
                    const amountInput = checkbox.closest('label').querySelector('.amountInput');
                    const amount = parseFloat(amountInput.value) || 0;
                    total += amount;
                }
            });

            document.getElementById('totalAmount').innerText = total.toFixed(2);
        }

        $(document).on('change', '.feeCheckbox', updateTotalAmount);
        $(document).on('input', '.amountInput', updateTotalAmount);

        // Fetch fee structure when class is changed and fee mode is 'class'
        document.getElementById("classDropdown").addEventListener("change", function() {
            const feeMode = document.querySelector('input[name="feeMode"]:checked')?.value;

            if (feeMode === "class") {
                const classId = this.value;

                // Optional loading message
                document.getElementById("feeStructureContainer").innerHTML =
                    '<p class="text-gray-500">Loading...</p>';

                // AJAX request to fetch class fee structure
                $.ajax({
                    url: "{{ route('fetch-fee-structure-fee-bulk') }}",
                    type: 'GET',
                    data: {
                        class_id: classId
                    },
                    success: function(response) {
                        $('#feeStructureContainer').html(response.html);
                        updateTotalAmount();
                    },
                    error: function() {
                        alert('Error loading fee structure.');
                    }
                });
            }
        });
    </script>
@endsection
