@extends('schoolLayout.app')
@section('content')
    <style>
        /* Increase height of the Select2 container */
        .custom-select2+.select2-container .select2-selection--single {
            height: 38px !important;
            display: flex;
            align-items: center;
            border-radius: 0.375rem;
            /* Tailwind's rounded */
            border: 1px solid #d1d5db;
            /* Tailwind gray-300 */
            padding-left: 0.75rem;
            padding-right: 0.75rem;
        }

        /* Optional: increase font size */
        .custom-select2+.select2-container .select2-selection__rendered {
            font-size: 16px;
            line-height: 48px;
        }
    </style>
    <div>
        <!-- Top Section: Tabs & New Admission Button -->
        <div class="flex justify-between items-center border-b pb-4">
            <!-- Tabs: Current & Alumni -->
            <div class="flex space-x-4">
                <button class="tab-btn px-4 bg-white py-2 border-b-2 border-blue-500 font-semibold text-blue-500">
                    Current Students
                </button>
                <button class="tab-btn text-gray-700 font-semibold"
                    onclick="window.location.href='{{ route('student.studentAlumni') }}'">
                    Alumni Students
                </button>
            </div>
            <!-- New Admission Button -->
            <button class="px-4 py-2 bg-[#0197FF] flex items-center gap-x-4 text-white rounded-lg"
                onclick="window.location.href='{{ route('student.admission') }}'">
                <img src="{{ asset('assets/new.png') }}" alt="icon" />
                <span>New Admission</span>
            </button>
        </div>
        <!-- Selection Bar (Initially Hidden) -->
        <div id="selectionBar" class="  p-3 flex gap-x-2 bg-white shadow-sm items-center rounded-lg mt-4">
            <span id="selectedCount" class="font-medium ">
                <div class="" id="selected_students"></div>
            </span>
            <div class="flex gap-2">
                <button class="bg-[#0197FF] text-white px-4 py-2 rounded-sm" onclick="markAsAlumni()">
                    Mark as Alumni
                </button>
            </div>
        </div>

        <!-- Filters Section -->
        <div class="mt-4 flex flex-wrap gap-4">
            <div class="flex flex-wrap items-center gap-4 mb-4 w-full">
                <!-- Search Input -->
                <div class="relative flex-grow min-w-[300px] max-w-[500px]">
                    <div class="border border-gray-200 rounded-md bg-white flex items-center px-3">
                        <span class="text-gray-500">
                            <img src="{{ asset('assets/search.png') }}" alt="icon" />
                        </span>
                        <input id="search" name="search_query" type="text" placeholder="Search Students..."
                            class="w-full px-3 py-2 text-sm border-none rounded-lg focus:outline-none"
                            onkeyup="fetchStudents()" />
                    </div>
                </div>

                <!-- Class Filter -->
                <div class="w-[180px]">
                    <select id="class_filter" name="class_filter"
                        class="border p-2 rounded-lg w-full select2 custom-select2" onchange="fetchStudents()">
                        <option value="">All Classes</option>
                        @foreach ($classes as $class)
                            <option value="{{ $class->id }}"
                                {{ request('class_filter') == $class->id ? 'selected' : '' }}>
                                {{ $class->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- Section Filter -->
                <div class="w-[180px]">
                    <select id="section_filter" name="section_filter" class="border p-2 rounded-lg w-full"
                        onchange="fetchStudents()">
                        <option value="">All Sections</option>
                        @foreach ($sections as $section)
                            <option value="{{ $section->id }}"
                                {{ request('section_filter') == $section->id ? 'selected' : '' }}>
                                {{ $section->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <!-- PDF Export Button -->
                <div>
                    <button type="button" onclick="downloadPdf()"
                        class="px-4 py-2 bg-[#0197FF] hover:bg-blue-600 text-white rounded-lg">
                        Export PDF
                    </button>
                </div>
            </div>


            <!-- View Toggle -->
            <!-- <div class="flex">
                                                                <button class="view-btn px-4 py-2 bg-gray-200">
                                                                    <img src="{{ asset('assets/list.png') }}" alt="icon" />
                                                                </button>
                                                                <button class="view-btn px-4 py-2" onclick="window.location='{{ route('student.currentStudentGrid') }}'">
                                                                <img src="{{ asset('assets/grid.png') }}" alt="icon" />
                                                            </button>

                                                            </div> -->
        </div>
        <div class="bg-white py-3 rounded-lg shadow mt-6 relative">
            <!-- Form for Marking Students as Alumni -->
            <form id="markAsAlumniForm" action="{{ route('mark.as.alumni') }}" method="POST">
                @csrf
                <!-- Results Container -->
                <span id="student-list">

                    @include('student.current-student-search-results', [
                        'students' => $students,
                    ])
                </span>
            </form>

            <!-- Pagination -->
            {{ $students->links('vendor.pagination.custom-pagination') }}
        </div>
    </div>

    <!-- Modal -->
    <!-- Modal -->
    <div id="admissionletterModal" class="fixed inset-0 flex items-center justify-center bg-gray-900 bg-opacity-50 hidden">
        <div class="bg-white rounded-md w-[45rem] max-h-[80vh] overflow-auto shadow-lg p-6 relative">
            <!-- Close Button -->
            <button onclick="closeModal('admissionletterModal')"
                class="absolute top-3 right-3 text-gray-500 hover:text-gray-700 no-print">
                <i class="fa-solid fa-xmark text-xl"></i>
            </button>

            <!-- School Info -->
            <div class="text-center pb-4">
                <i class="fa-solid fa-school text-blue-500 text-2xl"></i>
                <h1 class="text-xl font-bold">{{ $schoolSettings['school_name'] ?? 'School Management System' }}</h1>
                <p class="text-gray-600">{{ $schoolSettings['school_address'] ?? '' }}</p>
                <p class="text-gray-600">Phone: {{ $schoolSettings['phone_number'] ?? '' }} | Email:
                    {{ $schoolSettings['email'] ?? '' }}</p>
            </div>

            <!-- Date -->
            <p class="mt-4 text-right text-gray-700">Date: <span id="modalDate"></span></p>

            <!-- Title -->
            <h2 class="text-lg font-bold mt-4 pb-2">ADMISSION CONFIRMATION LETTER</h2>

            <!-- Student Details -->
            <div class="mt-4">
                <p><strong>Student Name:</strong> <span id="modalStudentName"></span></p>
                <p><strong>Admission ID:</strong> <span id="modalStudentId"></span></p>
                <p><strong>Class & Section:</strong> <span id="modalStudentClass"></span> - <span
                        id="modalStudentSection"></span></p>
                <p><strong>Academic Year:</strong> 2024/2025</p>
                <p><strong>Parent/Guardian:</strong> <span id="modalStudentPhone"></span></p>
            </div>

            <!-- Message -->
            <div class="mt-4">
                <p>Dear <span id="modalGuardianName"></span>,</p> <!-- Guardian Name Placeholder -->
                <p class="mt-2">
                    We are pleased to confirm the admission of your ward, <span id="modalStudentName2"></span>, to
                    <span id="modalStudentClass2"></span> for the academic year
                    {{ $schoolSettings['academic_year'] ?? '' }}. This admission is
                    subject to the school’s terms and conditions as outlined in our admission policy.
                </p>
                <p class="mt-2 font-semibold">Please note the following important details:</p>
                <ul class="list-disc pl-5 mt-2">
                    <li>Classes commence on {{ $schoolSettings['session_start'] ?? '' }} </li>
                    <li>School timings: {{ $schoolSettings['school_timings'] ?? '' }} </li>
                    <li>Uniform is mandatory</li>
                </ul>
            </div>

            <div class="flex justify-between items-center">
                <!-- Signature -->
                <div class="mt-6 text-right">
                    <p class="font-semibold">Principal's Signature</p>
                    <div class="border-t-2 border-gray-400 mt-8"></div>
                </div>
                <div class="mt-6 text-right border border-gray-400 rounded-sm">
                    <p class="font-semibold text-gray-400 px-4 py-4">School <br /> Stamp</p>
                </div>
            </div>

            <div class="flex justify-end mt-10 no-print">
                <button onclick="printModalContent()"
                    class="px-4 py-2 bg-[#0197FF] text-white flex items-center gap-x-2 rounded-md hover:bg-blue-600">
                    <i class="fa-solid fa-print"></i> Print Admission Letter
                </button>
            </div>
        </div>
    </div>
    <!-- End Modal -->
@endsection
@section('script')
    <script>
        function downloadPdf() {
            let search = document.getElementById("search").value;
            let classFilter = document.getElementById("class_filter").value;
            let sectionFilter = document.getElementById("section_filter").value;

            let url = "{{ route('pdf.current.student') }}?search_query=" + encodeURIComponent(search) +
                "&class_filter=" + encodeURIComponent(classFilter) +
                "&section_filter=" + encodeURIComponent(sectionFilter);

            window.open(url, '_blank');
        }

        $(document).ready(function() {
            $('.select2').select2({
                placeholder: "Select",
                allowClear: true,
                width: '100%' // Ensure full width
            });
        });
        // Focus on the search field when the Select2 dropdown opens
        $(document).on('select2:open', function() {
            const searchField = $('.select2-search__field');
            if (searchField.length) {
                searchField[0].focus();
            }
        });
        // Get the "all_check" checkbox element
        let all_check = document.getElementById('all_check');

        // Get all the "select_student" checkboxes
        let select_students = document.querySelectorAll('.select_student');

        // Add an event listener to the "all_check" checkbox
        all_check.addEventListener('click', function() {
            // Loop through all the "select_student" checkboxes
            select_students.forEach(function(studentCheckbox) {
                // Set the checked state of each "select_student" checkbox to match the "all_check" checkbox
                studentCheckbox.checked = all_check.checked;
            });
        });


        select_students.forEach(function(studentCheckbox) {
            studentCheckbox.addEventListener('click', function() {
                // Check if all "select_student" checkboxes are checked
                let allChecked = true;
                select_students.forEach(function(checkbox) {
                    if (!checkbox.checked) {
                        allChecked = false;
                    }
                });

                // Set the "all_check" checkbox state based on whether all "select_student" checkboxes are checked
                all_check.checked = allChecked;
            });
        });

        function markAsAlumni() {
            // Get all checkboxes with name "students[]"
            const checkboxes = document.querySelectorAll('input[name="students[]"]:checked');

            // Check if at least one checkbox is selected
            if (checkboxes.length > 0) {
                document.getElementById('markAsAlumniForm').submit();
            } else {
                alert('Please select at least one student.');
            }
        }

        function openModal(modalId) {
            document.getElementById(modalId).classList.remove("hidden");
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.add("hidden");
        }

        function openStudentModal(student) {
            // Parse the student data (if it's a JSON string)
            if (typeof student === 'string') {
                student = JSON.parse(student);
            }

            // Populate modal fields
            document.getElementById('modalStudentName').textContent = student.student_name;
            document.getElementById('modalStudentId').textContent = student.admission;
            document.getElementById('modalStudentClass').textContent = student.class;
            document.getElementById('modalStudentSection').textContent = student.section;
            document.getElementById('modalStudentPhone').textContent = student.guardian_name;
            document.getElementById('modalStudentName2').textContent = student.student_name;
            document.getElementById('modalStudentClass2').textContent = student.class;

            // Populate guardian name
            document.getElementById('modalGuardianName').textContent = student.guardian_name;

            // Set the current date
            const currentDate = new Date().toLocaleDateString();
            document.getElementById('modalDate').textContent = currentDate;

            // Show the modal
            document.getElementById('admissionletterModal').classList.remove('hidden');
        }

        function printModalContent() {
            // Get the modal content
            const modalContent = document.getElementById('admissionletterModal').cloneNode(true);

            // Remove unnecessary elements (e.g., buttons)
            const noPrintElements = modalContent.querySelectorAll('.no-print');
            noPrintElements.forEach(element => element.remove());

            // Create a new container for printing
            const printContainer = document.createElement('div');
            printContainer.id = 'print-container';
            printContainer.appendChild(modalContent);

            // Append the print container to the body
            document.body.appendChild(printContainer);

            // Hide everything except the print container
            const style = document.createElement('style');
            style.innerHTML = `
        body * {
            visibility: hidden;
        }
        #print-container, #print-container * {
            visibility: visible;
        }
        #print-container {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: auto;
            margin: 0;
            padding: 0;
            box-shadow: none;
        }
    `;
            document.head.appendChild(style);

            // Trigger the print dialog
            window.print();

            // Clean up after printing
            document.body.removeChild(printContainer);
            document.head.removeChild(style);
        }

        // search Student Functionality
        function fetchStudents() {
            let search = document.getElementById("search").value;
            let classFilter = document.getElementById("class_filter").value;
            let sectionFilter = document.getElementById("section_filter").value;

            $.ajax({
                url: "{{ route('student.currentStudent') }}",
                method: "GET",
                data: {
                    search_query: search,
                    class_filter: classFilter,
                    section_filter: sectionFilter
                },
                success: function(response) {
                    $('#student-list').html(response);
                }
            });
        }
    </script>
@endsection
