<x-admin.layout>
    <x-slot name="title">Users</x-slot>
    <x-slot name="heading">Users</x-slot>

    <style>
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            background-color: var(--vz-primary) !important;
            border: 1px solid var(--vz-primary) !important;
        }
    </style>
    <div class="row" id="editContainer">
        <div class="col-sm-12">
            <div class="card">
                <form class="theme-form" name="editForm" id="editForm" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')

                    <input type="hidden" name="user_id" value="{{ $user->id }}">

                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="col-md-4 mt-3">
                                <label for="name">User Name<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" value="{{ old('name', $user->name) }}">
                                <span class="text-danger is-invalid name_err"></span>
                            </div>

                            <div class="col-md-4 mt-3">
                                <label for="email">User Email<span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="email" name="email" value="{{ old('email', $user->email) }}">
                                <span class="text-danger is-invalid email_err"></span>
                            </div>

                            <div class="col-md-4 mt-3">
                                <label for="mobile">User Mobile<span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="mobile" name="mobile" value="{{ old('mobile', $user->mobile) }}">
                                <span class="text-danger is-invalid mobile_err"></span>
                            </div>

                            <div class="col-md-4 mt-3">
                                <label for="role">Role<span class="text-danger">*</span></label>
                                <select id="role" name="role" class="form-control">
                                    <option value="">--Select Role--</option>
                                    @foreach ($roles as $role)
                                        <option value="{{ $role->id }}" {{ $user->roles->contains('id', $role->id) ? 'selected' : '' }}>
                                            {{ $role->name }}
                                        </option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid role_err"></span>
                            </div>
                        </div>

                        {{-- Department Groups --}}

                        <div class="assign-department col-12" id="department-container">
                            @foreach ($userDepartments as $index => $dept)
                                <div class="department-group row" id="department-group-{{ $index }}">
                                    <div class="col-md-3 mt-3">
                                        <label>Select Department <span class="text-danger">*</span></label>
                                        <select name="departments[{{ $index }}]" id="department_{{ $index }}" class="form-control select2 departments">
                                            <option value="">-- Select Department --</option>
                                            @foreach ($departments as $department)
                                                <option value="{{ $department->id }}" {{ $dept['department_id'] == $department->id ? 'selected' : '' }}>
                                                    {{ $department->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        <span class="text-danger is-invalid departments_err"></span>
                                    </div>

                                    {{-- Property Prabhag --}}
                                    <div class="col-md-4 mt-3 prabhag-select-block" style="display: {{ $dept['department_id'] == 4 ? 'block' : 'none' }}">
                                        <label>Select Prabhag</label>
                                        <select name="prabhag[{{ $index }}][]" id="prabhag_select_{{ $index }}" class="form-control select2 prabhag_select" multiple>
                                            @foreach ($propertyPrabhags as $prabhag)
                                                <option value="{{ $prabhag->id }}" {{ in_array($prabhag->id, $dept['prabhag_ids'] ?? []) ? 'selected' : '' }}>
                                                    {{ $prabhag->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    {{-- Water Prabhag --}}
                                    <div class="col-md-4 mt-3 water-prabhag-select-block" style="display: {{ $dept['department_id'] == 5 ? 'block' : 'none' }}">
                                        <label>Select Water Prabhag</label>
                                        <select name="water_prabhag[{{ $index }}][]" id="water_prabhag_select_{{ $index }}" class="form-control select2 water_prabhag_select" multiple>
                                            @foreach ($waterPrabhags as $prabhag)
                                                <option value="{{ $prabhag->id }}" {{ in_array($prabhag->id, $dept['water_prabhag_ids'] ?? []) ? 'selected' : '' }}>
                                                    {{ $prabhag->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    {{-- Wards for other depts --}}
                                    <div class="col-md-4 mt-3 ward-select-block" style="display: {{ !in_array($dept['department_id'], [4, 5]) ? 'block' : 'none' }}">
                                        <label>Select Wards</label>
                                        <select name="wards[{{ $index }}][]" id="ward_select_{{ $index }}" class="form-control select2 ward_select" multiple>
                                            @foreach ($wards as $ward)
                                                <option value="{{ $ward->id }}" {{ in_array($ward->id, $dept['ward_ids'] ?? []) ? 'selected' : '' }}>
                                                    {{ $ward->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    {{-- Prabhag Wards for Property / Water --}}
                                    <div class="col-md-4 mt-3 prabhagward-select-block" style="display: {{ in_array($dept['department_id'], [4, 5]) ? 'block' : 'none' }}">
                                        <label>Select Wards</label>
                                        <select name="prabhagward[{{ $index }}][]" id="prabhagward_select_{{ $index }}" class="form-control select2 prabhagward_select" multiple>
                                            @php
                                                $wardModel = $dept['department_id'] == 5 ? \App\Models\WaterPrabhagWards::class : \App\Models\PrabhagWard::class;
                                                $wardList = $wardModel::whereIn('id', $dept['prabhagWard_ids'])->get();
                                            @endphp
                                            @foreach ($wardList as $ward)
                                                @php
                                                    // Assuming prabhag_name is a property or relation on the $ward object
                                                    $label = $ward->ward_name . ' - (' . $ward->prabhag->name . ')'; // Combine ward_name and prabhag_name
                                                @endphp
                                                <option value="{{ $ward->id }}" selected data-prabhag="{{ $ward->prabhag_id }}" id="ward_{{ $ward->id }}">{{ $label }}</option>
                                            @endforeach
                                        </select>
                                    </div>


                                    <div class="col-1 mt-5">
                                        <a href="#" class="remove_department1 btn btn-danger"><i class="fa fa-trash"></i></a>
                                    </div>
                                </div>
                            @endforeach
                        </div>

                        <div class="col-12 text-right mt-2">
                            <a href="javascript:void(0);" class="add_more_department btn btn-primary">+ Add Department</a>
                        </div>

                          <span class="text-danger is-invalid duplicate_ward_edit_err"></span>
                    </div>

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary" id="editSubmit">Update</button>
                        <button type="reset" class="btn btn-warning">Reset</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</x-admin.layout>

<script>
    $('.select2').select2();

    $("#editForm").submit(function(e) {
        e.preventDefault();
        $("#editSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('users.update', $user->id) }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            success: function(data) {
                $("#editSubmit").prop('disabled', false);
                if (!data.error2)
                    swal("Updated!", data.success, "success").then(() => {
                        window.location.href = '{{ route('users.index') }}';
                    });
                else
                    swal("Error!", data.error2, "error");
            },
            statusCode: {
                422: function(responseObject) {
                    $("#editSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function() {
                    $("#editSubmit").prop('disabled', false);
                    swal("Error!", "Something went wrong. Please try again.", "error");
                }
            }
        });
    });

    // Department change logic
    $(document).on('change', '.departments', function() {
        // Clear previous errors
        $('.duplicate_ward_err').text('');

        const selectedDept = $(this).val();
        const parentGroup = $(this).closest('.department-group');

        // Clear prabhagward options and reset the select2
        parentGroup.find('.prabhagward_select').empty().trigger('change.select2'); // Clear prabhagwards
        parentGroup.find('.prabhagward_select').select2({
            placeholder: 'Select Wards',
            allowClear: true
        });

        // Hide all sections initially
        parentGroup.find('.prabhag-select-block').hide();
        parentGroup.find('.water-prabhag-select-block').hide();
        parentGroup.find('.ward-select-block').hide();
        parentGroup.find('.prabhagward-select-block').hide();

        // Show corresponding sections based on selected department
        if (selectedDept === '5') {
            parentGroup.find('.water-prabhag-select-block').show(); // Show water prabhag block for dept 5
        } else if (selectedDept === '4') {
            parentGroup.find('.prabhag-select-block').show(); // Show prabhag block for dept 4
        } else if (selectedDept) {
            console.log(parentGroup.find('.ward-select-block'));
            parentGroup.find('.ward-select-block').show(); // Show wards block for other departments
        }
    });


    $(document).on('click', '.add_more_department', function(e) {
        e.preventDefault();

        // Get the current index for new department groups
        const lastIndex = $('.department-group').length;

        // Create a new department group using HTML template
        const newDepartmentGroup = `
                <div class="department-group row" id="department-group-${lastIndex}">
                    <div class="col-md-3 mt-3">
                        <label class="col-form-label">Select Department <span class="text-danger">*</span></label>
                        <select name="departments[${lastIndex}]" id="department_${lastIndex}" class="form-control select2 departments">
                            <option value="">-- Select Department --</option>
                            @foreach ($departments as $dept)
                                <option value="{{ $dept->id }}">{{ $dept->name }}</option>
                            @endforeach
                        </select>
                        <span class="text-danger is-invalid departments_err" id="departments_err_${lastIndex}"></span> <!-- Error span for departments -->
                    </div>

                    {{-- Prabhag --}}
                    <div class="col-md-4 mt-3 prabhag-select-block" id="prabhag-select-block_${lastIndex}" style="display: none;">
                        <label class="col-form-label">Select Prabhag <span class="text-danger">*</span></label>
                        <select name="prabhag[${lastIndex}][]" id="prabhag_select_${lastIndex}" class="form-control select2 prabhag_select" multiple>
                            @foreach ($propertyPrabhags as $prabhag)
                                <option value="{{ $prabhag->id }}">{{ $prabhag->name }}</option>
                            @endforeach
                        </select>
                        <span class="text-danger is-invalid prabhag_err" id="prabhag_err_${lastIndex}"></span> <!-- Error span for prabhag -->

                    </div>

                    {{-- Water Prabhag --}}
                    <div class="col-md-4 mt-3 water-prabhag-select-block" id="water-prabhag-select-block_${lastIndex}" style="display: none;">
                        <label class="col-form-label">Select Water Prabhag <span class="text-danger">*</span></label>
                        <select name="water_prabhag[${lastIndex}][]" id="water_prabhag_select_${lastIndex}" class="form-control select2 water_prabhag_select" multiple>
                            @foreach ($waterPrabhags as $prabhag)
                                <option value="{{ $prabhag->id }}">{{ $prabhag->name }}</option>
                            @endforeach
                        </select>
                        <span class="text-danger is-invalid water_prabhag_err" id="water_prabhag_err_${lastIndex}"></span> <!-- Error span for water prabhag -->

                    </div>

                    {{-- Prabhag Ward --}}
                    <div class="col-md-4 mt-3 prabhagward-select-block" id="prabhagward-select-block_${lastIndex}" style="display: none;">
                        <label class="col-form-label">Select Wards <span class="text-danger">*</span></label>
                        <select name="prabhagward[${lastIndex}][]" id="prabhagward_select_${lastIndex}" class="form-control select2 prabhagward_select" multiple>
                            {{-- Options will be populated dynamically via AJAX --}}
                        </select>
                        <span class="text-danger is-invalid prabhagward_err" id="prabhagward_err_${lastIndex}"></span> <!-- Error span for prabhagward -->

                    </div>

                    {{-- General Wards --}}
                    <div class="col-md-4 mt-3 ward-select-block" id="ward-select-block_${lastIndex}" style="display: none;">
                        <label class="col-form-label">Select Wards <span class="text-danger">*</span></label>
                        <select name="wards[${lastIndex}][]" id="ward_select_${lastIndex}" class="form-control select2 ward_select" multiple>
                            @foreach ($wards as $ward)
                                <option value="{{ $ward->id }}">{{ $ward->name }}</option>
                            @endforeach
                        </select>
                    <span class="text-danger is-invalid wards_err" id="wards_err_${lastIndex}"></span> <!-- Error span for wards -->
                    </div>
                </div>`;

        // Append the new department group
        $('.assign-department').append(newDepartmentGroup);

        // Reinitialize Select2 for newly added selects
        $(`#department_${lastIndex}`).select2();
        $(`#prabhag_select_${lastIndex}`).select2();
        $(`#water_prabhag_select_${lastIndex}`).select2();
        $(`#prabhagward_select_${lastIndex}`).select2();
        $(`#ward_select_${lastIndex}`).select2();

        // Add a remove link to the newly added department group
        const removeLink = $('<a href="#" class="remove_department ms-2 btn btn-danger" title="Remove Department"><i class="fa fa-trash"></i></a>');

        // Create a new column div with the remove link inside
        const removeColumn = $('<div class="col-1 mt-5"></div>').append(removeLink);

        // Append the new column with the remove link to the department group
        $(`#department-group-${lastIndex}`).append(removeColumn);

        // Attach the event to remove the department group when the "Remove" link is clicked
        removeLink.on('click', function(e) {
            e.preventDefault();

            // Destroy Select2 instance before removal to avoid memory leaks or issues
            $(`#department_${lastIndex}`).select2('destroy');
            $(`#prabhag_select_${lastIndex}`).select2('destroy');
            $(`#water_prabhag_select_${lastIndex}`).select2('destroy');
            $(`#prabhagward_select_${lastIndex}`).select2('destroy');
            $(`#ward_select_${lastIndex}`).select2('destroy');

            // Remove the department group
            const departmentGroup = $(this).closest('.department-group');
            departmentGroup.remove();

            // Reindex remaining department groups
            $('.department-group').each(function(index) {
                // Update the ids and names for the remaining department groups
                const newIndex = index; // New index based on the current loop

                // Update the department select field IDs and names
                $(this).find(`#department_${index}`).attr('id', `department_${newIndex}`).attr('name', `departments[${newIndex}]`);

                // Update the prabhag select field IDs and names
                $(this).find(`#prabhag_select_${index}`).attr('id', `prabhag_select_${newIndex}`).attr('name', `prabhag[${newIndex}][]`);

                // Update the water prabhag select field IDs and names
                $(this).find(`#water_prabhag_select_${index}`).attr('id', `water_prabhag_select_${newIndex}`).attr('name', `water_prabhag[${newIndex}][]`);

                // Update the prabhag ward select field IDs and names
                $(this).find(`#prabhagward_select_${index}`).attr('id', `prabhagward_select_${newIndex}`).attr('name', `prabhagward[${newIndex}][]`);

                // Update the general ward select field IDs and names
                $(this).find(`#ward_select_${index}`).attr('id', `ward_select_${newIndex}`).attr('name', `wards[${newIndex}][]`);

                // Update the error message spans' IDs (optional for error handling)
                $(this).find(`#departments_err_${index}`).attr('id', `departments_err_${newIndex}`);
                $(this).find(`#prabhag_err_${index}`).attr('id', `prabhag_err_${newIndex}`);
                $(this).find(`#water_prabhag_err_${index}`).attr('id', `water_prabhag_err_${newIndex}`);
                $(this).find(`#prabhagward_err_${index}`).attr('id', `prabhagward_err_${newIndex}`);
                $(this).find(`#wards_err_${index}`).attr('id', `wards_err_${newIndex}`);
            });

            // Reinitialize Select2 for the remaining selects
            $('.select2').select2();
        });




        // Event listener for dynamic department change (update the relevant fields based on selected department)
        $(document).on('change', `#department_${lastIndex}`, function() {
            const selectedDept = $(this).val();
            const parentGroup = $(this).closest('.department-group');

            // Clear existing options and hide all blocks
            parentGroup.find('.prabhag-select-block').hide();
            parentGroup.find('.water-prabhag-select-block').hide();
            parentGroup.find('.ward-select-block').hide();
            parentGroup.find('.prabhagward-select-block').hide();

            // Show corresponding blocks based on selected department
            if (selectedDept === '5') {
                parentGroup.find('.water-prabhag-select-block').show();
            } else if (selectedDept === '4') {
                parentGroup.find('.prabhag-select-block').show();
            } else if (selectedDept) {
                parentGroup.find('.ward-select-block').show();
            }
        });
    });

    $(document).on('change', '.prabhag_select', function() {
        const selectedPrabhags = $(this).val();
        const parentGroup = $(this).closest('.department-group');
        updateWardsBasedOnPrabhag(selectedPrabhags, parentGroup);
    });

    // Handle water prabhag selection change and update wards based on selected water prabhag
    $(document).on('change', '.water_prabhag_select', function() {
        const selectedWaterPrabhags = $(this).val();
        const parentGroup = $(this).closest('.department-group');
        updateWardsBasedOnWaterPrabhag(selectedWaterPrabhags, parentGroup);
    });

    // Function to update wards based on selected Prabhag
    function updateWardsBasedOnPrabhag(selectedPrabhags, parentGroup) {
        const $wardSelect = parentGroup.find('.prabhagward_select');
        const existingSelected = $wardSelect.val() || [];

        // Hide if nothing selected
        if (!selectedPrabhags || selectedPrabhags.length === 0) {
            $wardSelect.empty().trigger('change'); // clear all options
            parentGroup.find('.prabhagward-select-block').hide();
            return;
        }

        const params = encodeURIComponent(selectedPrabhags.join(','));
        fetch(`/get-wards-by-prabhag/${params}`)
            .then(res => res.json())
            .then(data => {
                // Clear all options first
                $wardSelect.empty();

                // Append new options
                data.forEach(ward => {
                    const label = `${ward.ward_name} - (${ward.prabhag_name})`;
                    $wardSelect.append(new Option(label, ward.id, existingSelected.includes(String(ward.id)), existingSelected.includes(String(ward.id))));
                });

                // Re-initialize / refresh select2
                $wardSelect.trigger('change.select2');
                parentGroup.find('.prabhagward-select-block').show();
            })
            .catch(err => console.error('Error fetching wards:', err));
    }

    // Function to update wards based on selected Water Prabhag
    function updateWardsBasedOnWaterPrabhag(selectedWaterPrabhags, parentGroup) {
        const $wardSelect = parentGroup.find('.prabhagward_select');
        const existingSelected = $wardSelect.val() || [];

        if (!selectedWaterPrabhags || selectedWaterPrabhags.length === 0) {
            $wardSelect.empty().trigger('change');
            parentGroup.find('.prabhagward-select-block').hide();
            return;
        }

        const params = encodeURIComponent(selectedWaterPrabhags.join(','));
        fetch(`/get-water-wards-by-prabhag/${params}`)
            .then(res => res.json())
            .then(data => {
                $wardSelect.empty(); // clear old options

                data.forEach(ward => {
                    const label = `${ward.ward_name} - (${ward.prabhag_name})`;
                    $wardSelect.append(new Option(label, ward.id, existingSelected.includes(String(ward.id)), existingSelected.includes(String(ward.id))));
                });

                $wardSelect.trigger('change.select2');
                parentGroup.find('.prabhagward-select-block').show();
            })
            .catch(err => console.error('Error fetching water wards:', err));
    }

    $('.remove_department1').on('click', function(e) {
        e.preventDefault();

        // Get the department group container
        const departmentGroup = $(this).closest('.department-group');

        // Check if Select2 is initialized before destroying
        departmentGroup.find('.select2').each(function() {
            // Only destroy Select2 if it has been initialized
            if ($(this).data('select2')) {
                $(this).select2('destroy');
            }
        });

        // Remove the department group (the parent div)
        departmentGroup.remove();

        // Reindex remaining department groups
        $('.department-group').each(function(index) {
            // Update the ids and names for the remaining department groups
            const newIndex = index; // New index based on the current loop

            // Update the department select field IDs and names
            $(this).find(`#department_${index}`).attr('id', `department_${newIndex}`).attr('name', `departments[${newIndex}]`);

            // Update the prabhag select field IDs and names
            $(this).find(`#prabhag_select_${index}`).attr('id', `prabhag_select_${newIndex}`).attr('name', `prabhag[${newIndex}][]`);

            // Update the water prabhag select field IDs and names
            $(this).find(`#water_prabhag_select_${index}`).attr('id', `water_prabhag_select_${newIndex}`).attr('name', `water_prabhag[${newIndex}][]`);

            // Update the prabhag ward select field IDs and names
            $(this).find(`#prabhagward_select_${index}`).attr('id', `prabhagward_select_${newIndex}`).attr('name', `prabhagward[${newIndex}][]`);

            // Update the general ward select field IDs and names
            $(this).find(`#ward_select_${index}`).attr('id', `ward_select_${newIndex}`).attr('name', `wards[${newIndex}][]`);

            // Update the error message spans' IDs (optional for error handling)
            $(this).find(`#departments_err_${index}`).attr('id', `departments_err_${newIndex}`);
            $(this).find(`#prabhag_err_${index}`).attr('id', `prabhag_err_${newIndex}`);
            $(this).find(`#water_prabhag_err_${index}`).attr('id', `water_prabhag_err_${newIndex}`);
            $(this).find(`#prabhagward_err_${index}`).attr('id', `prabhagward_err_${newIndex}`);
            $(this).find(`#wards_err_${index}`).attr('id', `wards_err_${newIndex}`);
        });
    });

    function resetErrors() {
        // Reset error classes for all form fields
        $('.form-control').removeClass('is-invalid').removeClass('is-valid');

        // Clear error messages
        $('.text-danger').text('');
    }

    function printErrMsg(msg) {
        $.each(msg, function(key, value) {
            // Check if the error relates to a dynamically generated department
            console.log(key);
            if (key.startsWith('departments')) {
                let index = key.split('.')[1]; // Get the index from the error key (e.g., departments.0)
                // Update the error message for the dynamic field
                $(`#department_${index}`).addClass('is-invalid').removeClass('is-valid');
                $(`#department_${index}`).closest('.department-group').find('.departments_err').text(value);
            }

            // Handle Prabhag errors
            if (key.startsWith('prabhag')) {
                let index = key.split('.')[1]; // Get the index from the error key
                $(`#prabhag_select_${index}`).addClass('is-invalid').removeClass('is-valid');
                $(`#prabhag_select_${index}`).closest('.department-group').find('.prabhag_err').text(value);
            }

            // Handle Water Prabhag errors
            if (key.startsWith('water_prabhag')) {
                let index = key.split('.')[1]; // Get the index from the error key
                $(`#water_prabhag_select_${index}`).addClass('is-invalid').removeClass('is-valid');
                $(`#water_prabhag_select_${index}`).closest('.department-group').find('.water_prabhag_err').text(value);
            }

            // Handle Ward errors
            if (key.startsWith('wards')) {
                let index = key.split('.')[1]; // Get the index from the error key
                $(`#ward_select_${index}`).addClass('is-invalid').removeClass('is-valid');
                $(`#ward_select_${index}`).closest('.department-group').find('.wards_err').text(value);
            }

            if (key.startsWith('prabhagward')) {
                let index = key.split('.')[1]; // Get the index from the error key
                $(`#prabhagward_select_${index}`).addClass('is-invalid').removeClass('is-valid');
                $(`#prabhagward_select_${index}`).closest('.department-group').find('.prabhagward_err').text(value);
            }

            // For other fields like role, email, etc.
            else {
                $('#' + key).addClass('is-invalid').removeClass('is-valid');
                $('.' + key + '_err').text(value);
            }
        });
    }

     $(document).on('select2:open', '.prabhag_select, .water_prabhag_select, .prabhagward_select, .ward_select', function() {
                const selectId = $(this).attr('id');

                // Get the currently open Select2 dropdown
                const $dropdown = $('.select2-container--open');
                const $results = $dropdown.find('.select2-results');

                // Remove any existing button container to prevent duplicates
                $results.find('.select2-results_btns').remove();

                // Add Select All / Unselect All buttons
                let buttonsHtml = `
                    <div class="d-flex justify-content-between align-items-center p-2 border-bottom bg-light select2-results_btns">
                        <button type="button" class="btn btn-xs btn-success select-all-btn" data-target="${selectId}" style="font-size:12px;">Select All</button>
                        <button type="button" class="btn btn-xs btn-danger unselect-all-btn" data-target="${selectId}" style="font-size:12px;">Unselect All</button>
                    </div>
                `;

                $results.prepend(buttonsHtml);
            });

            // Handle Select All functionality
            $(document).on('click', '.select-all-btn', function() {
                let target = $(this).data('target');
                $('#' + target + ' > option').prop('selected', true);
                $('#' + target).trigger('change');
            });

            // Handle Unselect All functionality
            $(document).on('click', '.unselect-all-btn', function() {
                let target = $(this).data('target');
                $('#' + target + ' > option').prop('selected', false);
                $('#' + target).trigger('change');
            });

</script>
