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


.select2-results__option .form-check .form-check-label{
    margin-left: 20px;
}
.select2-selection.select2-selection--multiple{
    border-bottom: none;
}
/* .select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple {
    position: relative;
} */

.select2-container--default .select2-search--inline .select2-search__field{
    position: absolute;
}

</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('transport-multiple-student-assign.store') }}" class="row">
            @csrf
            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                {{ generateDropdown($transport_routes, 'class="form-control select2 route_id" id="route_id" name="route_id" required', '', "Route") }}
            </div>
            <div class="form-group col-lg-3 col-md-3 col-sm-6">
                {{ generateDropdown([], 'class="form-control select2 stoppage_id" id="stoppage_id" name="stoppage_id" required', '', "Stoppage") }}
            </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="form-group col-lg-3 col-md-3 col-sm-6">
                <button type="submit" class="btn btn-info ">Assign Transport</button>
            </div>
        </form>
    </div>
</div>
@endsection
@section('scripts')
<script>

$('.route_id').on('change', function(){
    let route_id = $(this).val();
    let stoppage_id = '';
    getStoppage(route_id, stoppage_id);
});

let route_id = "{{ isset($route_id) ? $route_id : '' }}";
let stoppage_id = "{{ isset($stoppage_id) ? $stoppage_id : '' }}";

function getStoppage(route_id, stoppage_id){

    if(route_id){
        $.get('{{ route('stoppage-list-by-route') }}', { route_id: route_id }, function(response) {
            let stoppages = response;

            let option = '<option value="">Stoppage</option>';
            for(let i=0;i<stoppages.length;i++){

                if(stoppage_id==stoppages[i].id){
                    option += '<option value='+stoppages[i].id+' selected>'+stoppages[i].name+ ' -> ( Tk. '+stoppages[i].monthly_cost+')</option>';
                }else{
                    option += '<option value='+stoppages[i].id+' >'+stoppages[i].name+ ' -> ( Tk. '+stoppages[i].monthly_cost+')</option>';
                }

            }
            $('select.stoppage_id').empty().append(option);
        });
    }
}

$(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
