<div class="row" id="addContainer" style="display:none;">
    <div class="col-sm-12">
        <div class="card">
            <form class="theme-form" name="addForm" id="addForm">
                @csrf
                <div class="card-header pb-0">
                    <h4>Create User</h4>
                </div>
                <div class="card-body pt-0">
                    <div class="mb-3 row">
                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="name">User Name<span class="text-danger">*</span></label>
                            <input class="form-control" id="name" name="name" type="text" placeholder="Enter User Name">
                            <span class="text-danger is-invalid name_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="email">User Email <span class="text-danger">*</span></label>
                            <input class="form-control" id="email" name="email" type="email" placeholder="Enter User Email">
                            <span class="text-danger is-invalid email_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="mobile">User Mobile <span class="text-danger">*</span></label>
                            <input class="form-control" id="mobile" name="mobile" type="number" min="0" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" placeholder="Enter User Mobile">
                            <span class="text-danger is-invalid mobile_err"></span>
                        </div>

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

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="password">Password <span class="text-danger">*</span></label>
                            <input class="form-control" id="password" name="password" type="password" placeholder="********">
                            <span class="text-danger is-invalid password_err"></span>
                        </div>

                        <div class="col-md-4 mt-3">
                            <label class="col-form-label" for="confirm_password">Confirm Password <span class="text-danger">*</span></label>
                            <input class="form-control" id="confirm_password" name="confirm_password" type="password" placeholder="********">
                            <span class="text-danger is-invalid confirm_password_err"></span>
                        </div>

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

                                {{-- Prabhag --}}
                                <div class="col-md-4 mt-3 prabhag-select-block" id="prabhag-select-block" style="display: none;">
                                    <label class="col-form-label">Select Prabhag <span class="text-danger">*</span></label>
                                    <select name="prabhag[0][]" id="prabhag_select_0" class="form-control select2 prabhag_select" multiple>
                                        @foreach ($propertyprabhag as $prabhag)
                                            <option value="{{ $prabhag->id }}" {{ is_array(old('prabhag')) && in_array($prabhag->id, old('prabhag')) ? 'selected' : '' }}>{{ $prabhag->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid prabhag_err" id="prabhag_err_0"></span>
                                </div>

                                {{-- Water Prabhag --}}
                                <div class="col-md-4 mt-3 water-prabhag-select-block" id="water-prabhag-select-block" style="display: none;">
                                    <label class="col-form-label">Select Water Prabhag <span class="text-danger">*</span></label>
                                    <select name="water_prabhag[0][]" id="water_prabhag_select_0" class="form-control select2 water_prabhag_select" multiple>
                                        @foreach ($waterPrabhag as $prabhag)
                                            <option value="{{ $prabhag->id }}" {{ is_array(old('water_prabhag')) && in_array($prabhag->id, old('water_prabhag')) ? 'selected' : '' }}>{{ $prabhag->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid water_prabhag_err" id="water_prabhag_err_0"></span>
                                </div>

                                {{-- Prabhag Ward --}}
                                <div class="col-md-4 mt-3 prabhagward-select-block" id="prabhagward-select-block" style="display: none;">
                                    <label class="col-form-label">Select Wards <span class="text-danger">*</span></label>
                                    <select name="prabhagward[0][]" id="prabhagward_select_0" 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_0"></span>
                                </div>

                                {{-- General Wards --}}
                                <div class="col-md-4 mt-3 ward-select-block" id="ward-select-block" style="display: none;">
                                    <label class="col-form-label">Select Wards <span class="text-danger">*</span></label>
                                    <select name="wards[0][]" id="ward_select_0" class="form-control select2 ward_select" multiple>
                                        @foreach ($wards as $ward)
                                            <option value="{{ $ward->id }}" {{ is_array(old('wards')) && in_array($ward->id, old('wards')) ? 'selected' : '' }}>{{ $ward->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid wards_err" id="wards_err_0"></span>
                                </div>
                            </div>


                        </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>
                    </div>

                    <span class="text-danger is-invalid duplicate_ward_err"></span>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary" id="addSubmit">Submit</button>
                    <button type="reset" class="btn btn-warning">Reset</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
    <script>
        $(document).ready(function() {
            // Initialize Select2 for existing select elements on page load
            $('.select2').select2();

            // Handle department selection change (when the user selects a department)
            $(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
                }
            });

            // Handle prabhag selection change and update wards based on selected prabhag
            $(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);
            });

            // Handle Add More Department click event
            $(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[]" 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 ($propertyprabhag 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 ($waterPrabhag 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('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');
            });


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

                if (selectedPrabhags.length === 0) {
                    $wardSelect.find('option[data-prabhag]').remove();
                    $wardSelect.val([]).trigger('change.select2');
                    parentGroup.find('.prabhagward-select-block').hide();
                    return;
                }

                const params = encodeURIComponent(selectedPrabhags.join(','));
                fetch(`/get-wards-by-prabhag/${params}`)
                    .then(res => res.json())
                    .then(data => {
                        // Remove wards for unselected prabhags
                        $wardSelect.find('option[data-prabhag]').each(function() {
                            const prabhagId = $(this).data('prabhag');
                            if (!selectedPrabhags.includes(String(prabhagId))) {
                                $(this).remove();
                            }
                        }).trigger('change.select2');

                        // Add new wards based on selected prabhags
                        data.forEach(ward => {
                            if ($wardSelect.find(`#ward_${ward.id}`).length === 0) {
                                const label = `${ward.ward_name} - (${ward.prabhag_name})`;
                                $wardSelect.append(`<option value="${ward.id}" data-prabhag="${ward.prabhag_id}" id="ward_${ward.id}">${label}</option>`).trigger('change.select2');
                            }
                        });

                        parentGroup.find('.prabhagward-select-block').show();
                        $wardSelect.val(existingSelected).trigger('change.select2');
                    })
                    .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.length === 0) {
                    $wardSelect.find('option[data-water-prabhag]').remove();
                    $wardSelect.val([]).trigger('change.select2');
                    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 => {
                        // Remove wards for unselected water prabhags
                        $wardSelect.find('option[data-water-prabhag]').each(function() {
                            const prabhagId = $(this).data('water-prabhag');
                            if (!selectedWaterPrabhags.includes(String(prabhagId))) {
                                $(this).remove();
                            }
                        }).trigger('change.select2');

                        // Add new wards based on selected water prabhags
                        data.forEach(ward => {
                            if ($wardSelect.find(`#ward_${ward.id}`).length === 0) {
                                const label = `${ward.ward_name} - (${ward.prabhag_name})`;
                                $wardSelect.append(`<option value="${ward.id}" data-water-prabhag="${ward.prabhag_id}" id="ward_${ward.id}">${label}</option>`).trigger('change.select2');
                            }
                        });

                        parentGroup.find('.prabhagward-select-block').show();
                        $wardSelect.val(existingSelected).trigger('change.select2');
                    })
                    .catch(err => console.error('Error fetching water wards:', err));
            }
        });
        $("#addForm").submit(function(e) {
            e.preventDefault();
            $("#addSubmit").prop('disabled', true);

            var formdata = new FormData(this);
            $.ajax({
                url: '{{ route('users.store') }}',
                type: 'POST',
                data: formdata,
                contentType: false,
                processData: false,
                success: function(data) {
                    $("#addSubmit").prop('disabled', false);
                    if (!data.error2)
                        swal("Successful!", data.success, "success")
                        .then((action) => {
                            window.location.href = '{{ route('users.index') }}';
                        });
                    else
                        swal("Error!", data.error2, "error");
                },
                statusCode: {
                    422: function(responseObject, textStatus, jqXHR) {
                        $("#addSubmit").prop('disabled', false);
                        resetErrors();
                        printErrMsg(responseObject.responseJSON.errors);
                    },
                    500: function(responseObject, textStatus, errorThrown) {
                        $("#addSubmit").prop('disabled', false);
                        swal("Error occured!", "Something went wrong please try again", "error");
                    }
                }
            });
        });

        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);
                }
            });
        }
    </script>
@endpush
