@extends('schoolLayout.app')

@section('content')
   @if(session('success'))
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
        <strong class="font-bold">Success!</strong>
        <span class="block sm:inline">{{ session('success') }}</span>
    </div>
   @endif
   @if(session('error'))
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
        <strong class="font-bold">Error!</strong>
        <span class="block sm:inline">{{ session('error') }}</span>
    </div>
   @endif
<!-- Form Container -->
     <h1 class="text-3xl font-bold mb-6 text-gray-800 pt-4">Generate  DMC</h1>

   <form action="{{ route('dmc.bulk_generate') }}" class="bg-white p-6 rounded-sm min-h-screen shadow-md w-full space-y-6" method="post">

   <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>
    @csrf
      <!-- Row 1 -->

      <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 class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-md font-medium text-gray-700">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 text-md font-medium text-gray-700">Section</label>
          <select id="sectionDropdown" name="section" class="w-full p-2 border rounded" disabled>
                            <option value=""> Select Section</option>
                            @foreach ($sections as $section)
                                <option value="{{ $section->id }}"> {{ $section->name }}</option>
                            @endforeach
                        </select>
                        @error('section')
                            <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
                        @enderror
        </div>
        <div>
          <label class="block text-md font-medium text-gray-700">Session</label>
            <select
                name="session"
                class="mt-1 px-2 outline-none py-2 block w-full border border-gray-300">
                <option value="">Select Session</option>
                @foreach ($sessions as $session)
                    <option value="{{ $session->id }}">{{ $session->session_year }}</option>
                @endforeach
            </select>
            @error('session')
                <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
            @enderror
        </div>
        <div>
          <label class="block text-md font-medium text-gray-700">Exam</label>
            <select
                name="exam"
                class="mt-1 px-2 outline-none py-2 block w-full border border-gray-300"
            >
                <option value="">Select Exam</option>
                @foreach ($exams as $exam)
                    <option value="{{ $exam->id }}">{{ $exam->title }}</option>
                @endforeach
            </select>
            @error('exam')
                <p class="text-red-500 text-sm mt-1">{{ $message }}</p>
            @enderror
        </div>
      </div>

      <!-- Row 2 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label class="block text-md font-medium text-gray-700">Date</label>
          <input
            type="date"
            name="issue_date"
            class="mt-1 px-2 outline-none py-2 block w-full border border-gray-300"
          />
        </div>
         
        <div>
          <label class="block text-md font-medium text-gray-700"
            >Class Teacher Name</label
          >
          <input
            type="text"
            placeholder="Test"
            class="mt-1 px-2 outline-none py-2 block w-full border border-gray-300"
          />
        </div>
      </div>

      <!-- Row 3 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        
        <div>
          <label class="block text-md font-medium text-gray-700"
            >Print Grade or Position</label
          >
          <select
            class="mt-1 px-2 outline-none py-2 block w-full border border-gray-300"
          >
            <option value="">Select Option</option>
            <option value="grade">Grade</option>
            <option value="position">Position</option>
          </select>
        </div>
        <div class="pt-[26px]">
          <button
            type="submit"
            class="w-full bg-[#1B9AF5] text-white py-2 px-4 rounded-sm transition"
          >
            Generate
          </button>
        </div>
      </div>
      <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>

@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";
            }
        }

        /*     function selectStudent(name) {
              document.getElementById("studentSearch").value = name;
              document.getElementById("studentDropdown").classList.add("hidden");
            } */

        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) {
            // Explode the string into name, class, and section
            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');
            // Set the student name in the input field
            document.getElementById("studentSearch").value = name;

            // Get the class and section dropdowns
            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;

            }
            // Hide the student dropdown list
            document.getElementById("studentDropdown").classList.add("hidden");

             

        }

        $(document).on("change", "#classDropdown", function() {
            let class_id_selected = $(this).val();

            $.ajax({
                url: "{{ route('fetch-fee-structure') }}", // Ensure this is correctly defined in your routes
                type: 'GET',
                data: {
                    class_id: class_id_selected
                },
                success: function(response) {
                    $('#feeStructureContainer').html(response.html);
                },
                error: function() {
                    alert('Error fetching fee structure.');
                }
            });
        });

    // document.addEventListener('DOMContentLoaded', function() {
    //     const subjectSelect = document.getElementById('subject');
    //     const examSelect = document.querySelector('select[name="exam"]');

    //     subjectSelect.addEventListener('change', function() {
    //         const selectedSubject = this.value;
    //         // Fetch exams based on selected subject
    //         fetch(`/dmc/subject?subject_id=${selectedSubject}`)
    //             .then(response => response.json())
    //             .then(data => {
    //                 console.log(data);
    //                 document.getElementById('totalMarks').value = data.total_marks;
    //                 document.getElementById('passingMarks').value = data.passing_marks;
    //             })
    //             .catch(error => console.error('Error fetching exams:', error));
    //     });
    // }); 
</script>
@endsection