@extends('layouts.master')
@section('styles')
<style>
    .select2-results__option {
    display: flex;
    align-items: center;
}
.select2-selection__rendered{
    display: none;
}
.select2-results__option .form-check-input {
    margin-right: 10px;
}

.select2-results__option {
    display: flex;
    align-items: center;
    gap: 10px;
}

.select2-results__option .form-check-input {
    margin-right: 5px;
}


</style>
@endsection
@section('content')
<div class="card">
    <div class="card-header pl-3 pt-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 table__top__txt">Multiple Student Assign</h6>
        <div class="m-0 float-right">
            
        </div>
    </div>
    <div class="card-body card__head">
        <form method="POST" action="{{ route('multi.assign_room.store') }}" class="row">
            @csrf
            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                {{ generateDropdown($hostels, 'class="form-control hostel_id" id="hostel_id" name="hostel_id" required', $hostel_id, "Select Hostel") }}
            </div>
            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                {{ generateDropdown('', 'class="form-control room_id" id="room_id" name="room_id" required', $room_id, "Select Room") }}
            </div>
            
            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                <select id="student_id_no" name="student_id[]" style="width: 100%;" ></select>
            </div>

            {{--<div class="col-lg-3">
                <div class="form-group mb-0">
                    {{ multiSelectDropdown($months, 'name="month[]" class="form-control form-control-sm" id="multiselect"', old('month', request()->month ?? getMonthsBasedOnCurrent(3,2)), 'Select months...') }}
                </div>
                <div id="student-list"></div>
            </div>--}}


            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                <button type="submit" class="btn btn-info ">Assign Room</button>
            </div>
        </form>
    </div>
</div>
@endsection
@section('scripts')
<script>

$('.hostel_id').on('change', function(){
    let hostel_id = $('.hostel_id').val();
    getRooms(hostel_id);
});
let hostel_id = "{{ isset($hostel_id) ? $hostel_id : '' }}";
let room_id = "{{ isset($room_id) ? $room_id : '' }}";

//------------------Get room list----------------
function getRooms(hostel_id){
    if(hostel_id){
        $.get('{{ route('rooms_by_hostel') }}', { hostel_id: hostel_id}, function(response) {
            let rooms = response;
            let option = '<option value="">Select Room</option>';
            for(let i=0;i<rooms.length;i++){
                if(room_id==rooms[i].id){
                    option += '<option value='+rooms[i].id+' selected>'+rooms[i].room_name+'</option>';
                }else{
                    option += '<option value='+rooms[i].id+' >'+rooms[i].room_name+'</option>';
                }
            }
            $('select.room_id').empty().append(option);
        });
    }
}

// $(document).ready(function() {
//     $('#student_id_no').select2({
//         placeholder: 'Search by ID or Mobile',
//         minimumInputLength: 2,
//         numberDisplayed: 3,              // Number of selected items to display
//         multiple: true, // Enable multiple selections
//         closeOnSelect: false, // Prevent dropdown from closing after selection
//         ajax: {
//             url: '{{ route('students.search') }}', // Adjust the route
//             dataType: 'json',
//             delay: 250,
//             data: function(params) {
//                 return {
//                     q: params.term // Search term
//                 };
//             },
//             processResults: function(data) {
//                 return {
//                     results: data.map(function(item) {
//                         return {
//                             id: item.id,
//                             text: `${item.first_name} ${item.last_name} (${item.student_id_no})`
//                         };
//                     })
//                 };
//             },
//             cache: true
//         },
//         escapeMarkup: function(markup) {
//             return markup; // Allow custom HTML
//         },
//         templateResult: function(data) {
//             if (!data.id) {
//                 return data.text;
//             }

//             // Add checkbox to each result
//             return $(`
//                 <div class="form-check">
//                     <input type="checkbox" class="form-check-input select2-checkbox" value="${data.id}">
//                     <label class="form-check-label">${data.text}</label>
//                 </div>
//             `);
//         },
//         templateSelection: function(data) {
//             return data.text; // Format selected items
//         }
//     });

//     // Function to update the selected item count
//     function updateSelectedCount() {
//         const selectedCount = $('#student_id_no').val()?.length || 0;
//         $('#selected-count').text(`Selected Items: ${selectedCount}`);
//     }

//     // Sync checkboxes with selections
//     $('#student_id_no').on('select2:open', function() {
//         // Sync checkboxes with current selected values
//         const selectedValues = $('#student_id_no').val() || [];
//         $('.select2-checkbox').each(function() {
//             const checkboxValue = $(this).val();
//             $(this).prop('checked', selectedValues.includes(checkboxValue));
//         });
//     });

//     // Handle checkbox click events
//     $(document).on('change', '.select2-checkbox', function() {
//         const selectedValues = $('#student_id_no').val() || [];
//         const checkboxValue = $(this).val();

//         if (this.checked) {
//             // Add the value if checked
//             if (!selectedValues.includes(checkboxValue)) {
//                 selectedValues.push(checkboxValue);
//             }
//         } else {
//             // Remove the value if unchecked
//             const index = selectedValues.indexOf(checkboxValue);
//             if (index > -1) {
//                 selectedValues.splice(index, 1);
//             }
//         }

//         // Update the Select2 field with the new selection
//         $('#student_id_no').val(selectedValues).trigger('change');

//         // Update the selected item count
//         updateSelectedCount();
//     });

//     // Update count on initial load
//     updateSelectedCount();

//     // Update count whenever the value changes
//     $('#student_id_no').on('change', function() {
//         updateSelectedCount();
//     });
// });

$(document).ready(function() {
    $('#student_id_no').select2({
        placeholder: 'Search by ID or Mobile',
        minimumInputLength: 2,
        multiple: true, // Enable multiple selections
        closeOnSelect: false, // Prevent dropdown from closing after selection
        ajax: {
            url: '{{ route('students.search') }}', // Adjust the route
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    q: params.term // Search term
                };
            },
            processResults: function(data) {
                return {
                    results: data.map(function(item) {
                        return {
                            id: item.id,
                            text: `${item.first_name} ${item.last_name} (${item.student_id_no})`
                        };
                    })
                };
            },
            cache: true
        },
        escapeMarkup: function(markup) {
            return markup; // Allow custom HTML
        },
        templateResult: function(data) {
            if (!data.id) {
                return data.text;
            }

            // Add checkbox to each result with label click support
            const uniqueId = `checkbox-${data.id}`; // Unique ID for each checkbox
            return $(`
                <div class="form-check">
                    <input type="checkbox" id="${uniqueId}" class="form-check-input select2-checkbox" value="${data.id}">
                    <label for="${uniqueId}" class="form-check-label">${data.text}</label>
                </div>
            `);
        },
        templateSelection: function(data) {
            return data.text; // Format selected items
        }
    });

    // Function to update the selected item count
    function updateSelectedCount() {
        const selectedCount = $('#student_id_no').val()?.length || 0;
        $('#selected-count').text(`Selected Items: ${selectedCount}`);
    }

    // Sync checkboxes with selections
    $('#student_id_no').on('select2:open', function() {
        // Sync checkboxes with current selected values
        const selectedValues = $('#student_id_no').val() || [];
        $('.select2-checkbox').each(function() {
            const checkboxValue = $(this).val();
            $(this).prop('checked', selectedValues.includes(checkboxValue));
        });
    });

    // Handle checkbox click events
    $(document).on('change', '.select2-checkbox', function() {
        const selectedValues = $('#student_id_no').val() || [];
        const checkboxValue = $(this).val();

        if (this.checked) {
            // Add the value if checked
            if (!selectedValues.includes(checkboxValue)) {
                selectedValues.push(checkboxValue);
            }
        } else {
            // Remove the value if unchecked
            const index = selectedValues.indexOf(checkboxValue);
            if (index > -1) {
                selectedValues.splice(index, 1);
            }
        }

        // Update the Select2 field with the new selection
        $('#student_id_no').val(selectedValues).trigger('change');

        // Update the selected item count
        updateSelectedCount();
    });

    // Update count on initial load
    updateSelectedCount();

    // Update count whenever the value changes
    $('#student_id_no').on('change', function() {
        updateSelectedCount();
    });
});


// $('#multiselect').multiselect({
//     // Customization Options
//     enableFiltering: true,           // Search/Filter option
//     filterPlaceholder: 'Search...',  // Filter placeholder text
//     maxHeight: 250,                  // Maximum dropdown height
//     numberDisplayed: 3,              // Number of selected items to display
//     disableIfEmpty: true,            // Disable if no options
//     includeSelectAllOption: true,
//     // Text Configurations
//     nonSelectedText: 'Select Options',
//     allSelectedText: 'All Selected',
    
//     // Button Width
//     buttonWidth: '100%',
    
//     // Custom Styling
//     buttonClass: 'btn btn-light',
    
//     // Event Handlers
//     onChange: function(option, checked) {
//         var selectedOptions = $('#multiselect').val();  // Get selected options as an array
//         console.log('Selected options:', selectedOptions);
//         // Your AJAX call logic here
//         $.ajax({
//             url: '{{ route('students.search') }}',
//             dataType: 'json',
//             data: {
//                 selectedOptions: selectedOptions,
//                 _token: '{{ csrf_token() }}'
//             },
//             success: function(response) {
//                 console.log('AJAX success:', response);
//             },
//             error: function(xhr, status, error) {
//                 console.log('AJAX error:', error);
//             }
//         });
//     },

//     // Filter event handler
//     onFiltering: function(event, value) {
//         // Ensure value is the search query
//         var searchValue = value || '';  // Use `value` or an empty string if undefined
//         console.log('Searching for:', searchValue);

//         // Trigger AJAX when the user is searching
//         $.ajax({
//             url: '{{ route('students.search') }}',
//             dataType: 'json',
//             data: {
//                 searchQuery: searchValue,  // Send the search query as data
//                 _token: '{{ csrf_token() }}'
//             },
//             success: function(response) {
//                 console.log('AJAX success:', response);
//             },
//             error: function(xhr, status, error) {
//                 console.log('AJAX error:', error);
//             }
//         });
//     }
// });



// $('#multiselect').multiselect({
//     // Customization Options
//     enableFiltering: true,           // Search/Filter option
//     filterPlaceholder: 'Search...',  // Filter placeholder text
//     maxHeight: 250,                  // Maximum dropdown height
//     numberDisplayed: 3,              // Number of selected items to display
//     disableIfEmpty: true,            // Disable if no options
//     includeSelectAllOption: true,
//     // Text Configurations
//     nonSelectedText: 'Select Options',
//     allSelectedText: 'All Selected',
    
//     // Button Width
//     buttonWidth: '100%',
    
//     // Custom Styling
//     buttonClass: 'btn btn-light',
    
//     // Event Handlers
//     onChange: function(option, checked) {
//         var selectedOptions = $('#multiselect').val();  // Get selected options as an array
//         console.log('Selected options:', selectedOptions);

//         // Trigger AJAX on change
//         $.ajax({
//             url: '{{ route('students.search') }}',
//             dataType: 'json',
//             data: {
//                 selectedOptions: selectedOptions,
//                 _token: '{{ csrf_token() }}'
//             },
//             success: function(response) {
//                 console.log('AJAX success:', response);
//                 // Assuming the response is an array of student objects, update the HTML here

//                 var html = '';
//                 response.forEach(function(student) {
//                     html += `<div class="student-info">
//                                 <p>Student ID: ${student.student_id_no}</p>
//                                 <p>Name: ${student.first_name} ${student.last_name}</p>
//                                 <p>Guardian Mobile: ${student.guardian_mobile || 'N/A'}</p>
//                              </div>`;
//                 });

//                 // Assuming you have a div with id `student-list` to display the results
//                 $('#student-list').html(html);  // Update the content of the div with the result
//             },
//             error: function(xhr, status, error) {
//                 console.log('AJAX error:', error);
//             }
//         });
//     },

//     // Filter event handler (optional)
//     onFiltering: function(event, value) {
//         var searchValue = value || '';  // Ensure value is the search query
//         console.log('Searching for:', searchValue);

//         // Trigger AJAX when the user is searching
//         $.ajax({
//             url: '{{ route('students.search') }}',
//             dataType: 'json',
//             data: {
//                 searchQuery: searchValue,  // Send the search query as data
//                 _token: '{{ csrf_token() }}'
//             },
//             success: function(response) {
//                 console.log('AJAX success:', response);
//                 var html = '';
//                 response.forEach(function(student) {
//                     html += `<div class="student-info">
//                                 <p>Student ID: ${student.student_id_no}</p>
//                                 <p>Name: ${student.first_name} ${student.last_name}</p>
//                                 <p>Guardian Mobile: ${student.guardian_mobile || 'N/A'}</p>
//                              </div>`;
//                 });

//                 // Assuming you have a div with id `student-list` to display the results
//                 $('#student-list').html(html);  // Update the content of the div with the result
//             },
//             error: function(xhr, status, error) {
//                 console.log('AJAX error:', error);
//             }
//         });
//     }
// });



    </script>
@endsection
