<div class="row" id="editContainer" style="display:none;">
    <div class="col-sm-12">
        <div class="card">
            <form class="theme-form" name="editForm" id="editForm">
                @csrf
                <input type="hidden" name="edit_model_id" id="edit_model_id">

                <div class="card-header pb-0">
                    <h4>Edit 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="edit_name">User Name<span class="text-danger">*</span></label>
                            <input class="form-control" id="edit_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="edit_email">User Email <span class="text-danger">*</span></label>
                            <input class="form-control" id="edit_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="edit_mobile">User Mobile <span class="text-danger">*</span></label>
                            <input class="form-control" id="edit_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="edit_role">Select User Type / Role <span class="text-danger">*</span></label>
                            <select class="form-select" id="edit_role" name="role">
                                <option value="">--Select Role--</option>
                                @foreach ($roles as $role)
                                    <option value="{{ $role->id }}">{{ $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="edit_departments">Select Department <span class="text-danger">*</span></label>
                            <select name="departments" id="edit_departments" class="form-control select2">
                                <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"></span>
                        </div>

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

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

                        {{-- Prabhag Ward --}}
                        <div class="col-md-4 mt-3" id="edit-prabhagward-select-block" style="display: none;">
                            <label class="col-form-label">Select Wards <span class="text-danger">*</span></label>
                            <select name="prabhagward[]" id="edit_prabhagward_select" class="form-control select2" multiple></select>
                            <span class="text-danger is-invalid prabhagward_err"></span>
                        </div>

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

                    </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>
@push('scripts')
    <script>
        $(document).ready(function() {
            $('.select2').select2();

            // ------------------ EDIT FORM SUBMIT ------------------
            $("#editForm").submit(function(e) {
                e.preventDefault();
                $("#editSubmit").prop('disabled', true);
                let formdata = new FormData(this);
                formdata.append('_method', 'PUT');
                let model_id = $('#edit_model_id').val();

                $.ajax({
                    url: "{{ route('users.update', ':id') }}".replace(':id', model_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(resp) {
                            $("#editSubmit").prop('disabled', false);
                            resetErrors();
                            printErrMsg(resp.responseJSON.errors);
                        },
                        500: function() {
                            $("#editSubmit").prop('disabled', false);
                            swal("Error!", "Something went wrong", "error");
                        }
                    }
                });
            });

            // ------------------ DEPARTMENT CHANGE ------------------
            $('#edit_departments').on('change', function() {

                $('.duplicate_ward_edit_err').text('');
                const selectedDept = $(this).val();
                $('#edit_prabhagward_select').empty().select2({
                    placeholder: 'Select Wards',
                    allowClear: true
                });

                $('#edit-prabhag-select-block, #edit-water-prabhag-select-block, #edit-ward-select-block, #edit-prabhagward-select-block').hide();

                if (selectedDept === '5') {
                    $('#edit-water-prabhag-select-block').show();
                } else if (selectedDept === '4') {
                    $('#edit-prabhag-select-block').show();
                } else if (selectedDept) {
                    $('#edit-ward-select-block').show();
                }
            });

            // ------------------ PRABHAG CHANGE ------------------
            $('#edit_prabhag_select').on('change', function() {
                $('.duplicate_ward_edit_err').text('');
                const selected = $(this).val() || [];
                const $wardSelect = $('#edit_prabhagward_select');
                const existing = $wardSelect.val() || [];

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

                fetch(`/get-wards-by-prabhag/${encodeURIComponent(selected.join(','))}`)
                    .then(res => res.json())
                    .then(data => {
                        $wardSelect.find('option[data-prabhag]').each(function() {
                            const id = $(this).data('prabhag');
                            if (!selected.includes(String(id))) $(this).remove();
                        });
                        data.forEach(w => {
                            if ($wardSelect.find(`#ward_${w.id}`).length === 0) {
                                $wardSelect.append(`<option value="${w.id}" data-prabhag="${w.prabhag_id}" id="ward_${w.id}">${w.ward_name} - (${w.prabhag_name})</option>`);
                            }
                        });
                        $('#edit-prabhagward-select-block').show();
                        $wardSelect.val(existing).trigger('change.select2');
                        $wardSelect.select2({
                            placeholder: 'Select Wards',
                            allowClear: true
                        });
                    });
            });

            // ------------------ WATER PRABHAG CHANGE ------------------
            $('#edit_water_prabhag_select').on('change', function() {
                $('.duplicate_ward_edit_err').text('');
                const selected = $(this).val() || [];
                const $wardSelect = $('#edit_prabhagward_select');
                const existing = $wardSelect.val() || [];

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

                fetch(`/get-water-wards-by-prabhag/${encodeURIComponent(selected.join(','))}`)
                    .then(res => res.json())
                    .then(data => {
                        $wardSelect.find('option[data-water-prabhag]').each(function() {
                            const id = $(this).data('water-prabhag');
                            if (!selected.includes(String(id))) $(this).remove();
                        });
                        data.forEach(w => {
                            if ($wardSelect.find(`#ward_${w.id}`).length === 0) {
                                $wardSelect.append(`<option value="${w.id}" data-water-prabhag="${w.prabhag_id}" id="ward_${w.id}">${w.ward_name} - (${w.prabhag_name})</option>`);
                            }
                        }).trigger('change.select2');
                        $('#edit-prabhagward-select-block').show();
                        $wardSelect.val(existing).trigger('change.select2');
                        $wardSelect.select2({
                            placeholder: 'Select Wards',
                            allowClear: true
                        });
                    });
            });

            // ------------------ OPEN EDIT FORM ------------------
            // ------------------ OPEN EDIT FORM ------------------
            $("#buttons-datatables").on("click", ".edit-element", function(e) {
                $('.duplicate_ward_edit_err').text('');
                e.preventDefault();
                let id = $(this).data("id");

                $.get("{{ route('users.edit', ':id') }}".replace(':id', id), function(data) {
                    if (data.result === 1) {
                        const user = data.user;
                        $('#edit_model_id').val(user.id);
                        $('#edit_name').val(user.name);
                        $('#edit_email').val(user.email);
                        $('#edit_mobile').val(user.mobile);

                        // Role
                        if (user.roles && user.roles.length > 0) {
                            $('#edit_role').val(user.roles[0].id).trigger('change');
                        }

                        // Department
                        $('#edit_departments').val(data.department_id).trigger('change');

                        // Clear previous wards
                        $('#edit_prabhagward_select').empty().trigger('change.select2');

                        // Prefill Prabhag
                        $('#edit_prabhag_select').val(data.prabhag_ids).trigger('change');

                        // Prefill Water Prabhag
                        $('#edit_water_prabhag_select').val(data.water_prabhag_ids).trigger('change');

                        // Fetch wards for prabhag and select
                        if (data.prabhag_ids.length > 0) {
                            fetch(`/get-wards-by-prabhag/${data.prabhag_ids.join(',')}`)
                                .then(res => res.json())
                                .then(wards => {
                                    wards.forEach(w => {
                                        if ($('#ward_' + w.id).length === 0) {
                                            $('#edit_prabhagward_select').append(`<option value="${w.id}" data-prabhag="${w.prabhag_id}" id="ward_${w.id}">${w.ward_name} - (${w.prabhag_name})</option>`);
                                        }
                                    });
                                    $('#edit_prabhagward_select').val(data.prabhagward_ids).trigger('change.select2');
                                    if (data.prabhagward_ids.length) {
                                        $('#edit-prabhagward-select-block').show();
                                    }
                                });
                        }

                        // Fetch wards for water prabhag and select
                        if (data.water_prabhag_ids.length > 0) {
                            fetch(`/get-water-wards-by-prabhag/${data.water_prabhag_ids.join(',')}`)
                                .then(res => res.json())
                                .then(wards => {
                                    wards.forEach(w => {
                                        if ($('#ward_' + w.id).length === 0) {
                                            $('#edit_prabhagward_select').append(`<option value="${w.id}" data-water-prabhag="${w.prabhag_id}" id="ward_${w.id}">${w.ward_name} - (${w.prabhag_name})</option>`);
                                        }
                                    });
                                    $('#edit_prabhagward_select').val(data.prabhagward_ids).trigger('change.select2');
                                    if (data.prabhagward_ids.length) {
                                        $('#edit-prabhagward-select-block').show();
                                    }
                                });
                        }

                        // Prefill general wards
                        $('#edit_ward_select').val(data.ward_ids).trigger('change');

                        $('#addContainer').hide();
                        $('#editContainer').show();
                    } else {
                        swal("Error!", data.message || data.error, "error");
                    }
                });
            });


            $('#edit_prabhag_select, #edit_water_prabhag_select, #edit_prabhagward_select ,#edit_ward_select').select2({
                placeholder: "Select options",
                width: '100%'
            });

            // Loop through only those 3 dropdowns
            $('#edit_prabhag_select, #edit_water_prabhag_select, #edit_prabhagward_select, #edit_ward_select').on('select2:open', function() {
                const selectId = $(this).attr('id');

                // Get the currently opened dropdown container
                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
                const 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
            $(document).on('click', '.select-all-btn', function() {
                let target = $(this).data('target');
                $('#' + target + ' > option').prop('selected', true);
                $('#' + target).trigger('change.select2');
            });

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

        });
    </script>
@endpush
