<x-admin.layout>
    <x-slot name="title">Users</x-slot>
    <x-slot name="heading">Users</x-slot>
    {{-- <x-slot name="subheading">Test</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>
    @include('admin.user.create')
    @include('admin.user.edit')
        @php
            $userAuth =auth()->user();
            $canCreate = $userAuth->can('users.create');
            $canEdit = $userAuth->can('users.edit');
            $canDelete = $userAuth->can('users.delete');
            $canChangePassword = $userAuth->can('users.change_password');
            $canAssignRole = $userAuth->can('users.assign_role') || $userAuth->hasRole('Super Admin');
        @endphp
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="">
                                @if($canCreate)
                                    <button id="addToTable" class="btn btn-primary">Add <i class="fa fa-plus"></i></button>
                                    <button id="btnCancel" class="btn btn-danger" style="display:none;">Cancel</button>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>


                <div class="card-body">
                    <div class="table-responsive">
                        <table id="buttons-datatables" class="table table-bordered nowrap align-middle" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Sr No</th>
                                    <th>Full Name</th>
                                    <th>Email</th>
                                    <th>Mobile</th>
                                    <th>Registered On</th>
                                    <th>Departments</th>
                                    <th>Roles</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($users as $user)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $user->name }}</td>
                                        <td>{{ $user->email }}</td>
                                        <td>{{ $user->mobile }}</td>
                                        <td>{{ \Carbon\Carbon::parse($user->created_at)->timezone('Asia/Kolkata')->format('d M, y h:i:s') }}</td>

                                        {{-- Departments --}}
                                        <td>
                                            {{ $user->departmentUsers->pluck('department.name')->filter()->unique()->join(', ') ?: 'NA' }}
                                        </td>
                                        {{-- Roles --}}
                                        <td>
                                            @if ($user->roles->isNotEmpty())
                                                @foreach ($user->roles as $role)
                                                    {{ $role->name }}@if (!$loop->last)
                                                        ,
                                                    @endif
                                                @endforeach
                                            @else
                                                NA
                                            @endif
                                        </td>

                                        {{-- Action Buttons --}}
                                        <td>
                                             @if ($canEdit || $canDelete || $canChangePassword || $canAssignRole)
                                                @if ($canEdit)
                                                     <a href="{{ route('users.edit', $user->id) }}"
                                                    class="btn text-primary px-2 py-1"
                                                    title="Edit User">
                                                        <i data-feather="edit"></i>
                                                    </a>
                                                @endif

                                                @if ($canChangePassword)
                                                    <button class="btn text-primary change-password px-2 py-1" title="Change Password" data-id="{{ $user->id }}">
                                                        <i data-feather="lock"></i>
                                                    </button>
                                                @endif

                                                @if ($canAssignRole)
                                                    <button class="btn text-warning assign-role px-2 py-1" title="Assign Role" data-id="{{ $user->id }}">
                                                        <i data-feather="user-check"></i>
                                                    </button>
                                                @endif

                                                @if ($canDelete)
                                                    <button class="btn text-danger rem-element px-2 py-1" title="Delete Role" data-id="{{ $user->id }}">
                                                        <i data-feather="trash-2"></i>
                                                    </button>
                                                @endif
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="change-password-modal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form action="" id="changePasswordForm">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Change Password</h5>
                        <button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">

                        <input type="hidden" id="user_id" name="user_id" value="">

                        <div class="col-8 mx-auto my-2">
                            <div class="form-group">
                                <label for="new_password">Password</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-unlock-keyhole"></i></span>
                                    <input class="form-control" type="password" id="new_password" name="new_password">
                                    <span class="input-group-text" id="new_password_eye" style="cursor: pointer;">
                                        <i class="fas fa-eye-slash"></i>
                                    </span>
                                </div>
                                <span class="text-danger is-invalid password_err"></span>
                            </div>
                        </div>

                        <div class="col-8 mx-auto my-2">
                            <div class="form-group">
                                <label for="confirmed_password">Confirm Password</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-unlock-keyhole"></i></span>
                                    <input class="form-control" type="password" id="confirmed_password" name="confirmed_password">
                                    <span class="input-group-text" id="confirmed_password_eye" style="cursor: pointer;">
                                        <i class="fas fa-eye-slash"></i>
                                    </span>
                                </div>
                                <span class="text-danger is-invalid confirmed_password_err"></span>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
                        <button class="btn btn-primary" id="changePasswordSubmit" type="submit">Change</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div class="modal fade" id="assign-role-modal" role="dialog">
        <div class="modal-dialog" role="document">
            <form action="" id="assignRoleForm">
                @csrf
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Assign Role</h5>
                        <button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">

                        <input type="hidden" id="role_user_id" name="role_user_id" value="">

                        <div class="mb-3 row">
                            <label class="col-sm-3 col-form-label" for="name">User Name : </label>
                            <div class="col-sm-9">
                                <h6 id="role_user_name" class="pt-2"></h6>
                            </div>
                        </div>

                        <div class="mb-3 row">
                            <label class="col-sm-3 col-form-label" for="name">Role : </label>
                            <div class="col-sm-9" style="max-height: 60px">
                                <select class="js-example-basic-single" id="edit_role" name="edit_role">
                                    <option value="">--Select Role--</option>
                                </select>
                                <span class="text-danger is-invalid edit_role_err"></span>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
                        <button class="btn btn-primary" id="assignRoleSubmit" type="submit">Change</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</x-admin.layout>
<script>
    $("#buttons-datatables").on("change", ".status", function(e) {
        e.preventDefault();
        var model_id = $(this).attr("data-id");
        var url = "{{ route('users.toggle', ':model_id') }}";

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'GET',
            data: {
                '_token': "{{ csrf_token() }}"
            },
            success: function(data, textStatus, jqXHR) {
                if (!data.error && !data.error2) {
                    swal("Success!", data.success, "success");
                } else {
                    if (data.error) {
                        swal("Error!", data.error, "error");
                    } else {
                        swal("Error!", data.error2, "error");
                    }
                }
            },
            error: function(error, jqXHR, textStatus, errorThrown) {
                swal("Error!", "Something went wrong", "error");
            },
        });
    });
</script>

<script>
    $("#buttons-datatables").on("click", ".change-password", function(e) {
        e.preventDefault();
        var user_id = $(this).attr("data-id");
        $('#user_id').val(user_id);
        $('#change-password-modal').modal('show');
    });
</script>

<script>
    $("#changePasswordForm").submit(function(e) {
        e.preventDefault();
        $("#changePasswordSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        formdata.append('_method', 'PUT');
        var model_id = $('#user_id').val();
        var url = "{{ route('users.change-password', ':model_id') }}";

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            success: function(data) {
                $("#changePasswordSubmit").prop('disabled', false);
                if (!data.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        $("#change-password-modal").modal('hide');
                        $("#changePasswordSubmit").prop('disabled', false);
                    });
                else
                    swal("Error!", data.error2, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#changePasswordSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#changePasswordSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            }
        });

        function resetErrors() {
            var form = document.getElementById('changePasswordForm');
            var data = new FormData(form);
            for (var [key, value] of data) {
                $('.' + key + '_err').text('');
                $('#' + key).removeClass('is-invalid');
                $('#' + key).addClass('is-valid');
            }
        }

        function printErrMsg(msg) {
            $.each(msg, function(key, value) {
                $('.' + key + '_err').text(value);
                $('#' + key).addClass('is-invalid');
                $('#' + key).removeClass('is-valid');
            });
        }

    });
</script>

<script>
    $(document).ready(function() {
        $('.department-checkbox').on('change', function() {
            if ($('.department-checkbox:checked').length === $('.department-checkbox').length) {
                $('#selectAllDepartments').prop('checked', true);
            } else {
                $('#selectAllDepartments').prop('checked', false);
            }
        });
    });
</script>

<script>
    $("#buttons-datatables").on("click", ".assign-role", function(e) {
        e.preventDefault();
        var model_id = $(this).attr("data-id");
        var url = "{{ route('users.get-role', ':model_id') }}";
        $('#role_user_id').val(model_id);

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'GET',
            data: {
                '_token': "{{ csrf_token() }}"
            },
            success: function(data, textStatus, jqXHR) {

                if (!data.error) {
                    $("#editForm input[name='edit_model_id']").val(data.user.id);
                    $("#edit_role").html(data.roleHtml);
                    $("#role_user_name").text(data.user.name);
                } else {
                    swal("Error!", data.error, "error");
                }
            },
            error: function(error, jqXHR, textStatus, errorThrown) {
                swal("Error!", "Some thing went wrong", "error");
            },
        });

        $('#assign-role-modal').modal('show');
    });
</script>

<script>
    $("#assignRoleForm").submit(function(e) {
        e.preventDefault();
        $("#assignRoleSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        formdata.append('_method', 'PUT');
        var model_id = $('#role_user_id').val();
        var url = "{{ route('users.assign-role', ':model_id') }}";

        $.ajax({
            url: url.replace(':model_id', model_id),
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            success: function(data) {
                $("#assignRoleSubmit").prop('disabled', false);
                if (!data.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        $("#assign-role-modal").modal('hide');
                    });
                else
                    swal("Error!", data.error2, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#assignRoleSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#assignRoleSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            }
        });

        function resetErrors() {
            var form = document.getElementById('assignRoleForm');
            var data = new FormData(form);
            // $('[class$="_err"]').text('');
            for (var [key, value] of data) {
                $('.' + key + '_err').text('');
                $('#' + key).removeClass('is-invalid');
                $('#' + key).addClass('is-valid');
            }
        }

        function printErrMsg(msg) {
            $.each(msg, function(key, value) {
                $('.' + key + '_err').text(value);
                $('#' + key).addClass('is-invalid');
                $('#' + key).removeClass('is-valid');
            });
        }

    });

    function validateMobile() {
        var mobile = document.getElementById("mobile");
        var errorSpan = document.getElementById("mobile-error");

        var mobileValue = mobile.value.replace(/\D/g, '');
        if (mobileValue.length > 10) {
            mobileValue = mobileValue.substring(0, 10);
        }

        mobile.value = mobileValue;

        if (mobileValue.length === 10) {
            errorSpan.textContent = "";
            mobile.classList.remove("is-invalid");
        } else {
            errorSpan.textContent = "Please enter a valid 10-digit mobile number.";
            mobile.classList.add("is-invalid");
        }
    }
    document.getElementById("mobile").addEventListener("input", validateMobile);

    function togglePasswordVisibility(inputId, toggleId) {
        var passwordField = document.getElementById(inputId);
        var toggleIcon = document.getElementById(toggleId).querySelector('i');

        if (passwordField.type === 'password') {
            passwordField.setAttribute('type', 'text');
            toggleIcon.classList.remove('fa-eye-slash');
            toggleIcon.classList.add('fa-eye');
        } else {
            passwordField.setAttribute('type', 'password');
            toggleIcon.classList.remove('fa-eye');
            toggleIcon.classList.add('fa-eye-slash');
        }
    }

    document.getElementById('new_password_eye').addEventListener('click', function() {
        togglePasswordVisibility('new_password', 'new_password_eye');
    });

    document.getElementById('confirmed_password_eye').addEventListener('click', function() {
        togglePasswordVisibility('confirmed_password', 'confirmed_password_eye');
    });
</script>

<script>
    $("#buttons-datatables").on("click", ".rem-element", function(e) {
        e.preventDefault();

        swal({
                title: "Are you sure to delete this user?",
                icon: "warning",
                buttons: ["Cancel", "Confirm"],
                dangerMode: true
            })
            .then((willDelete) => {
                if (willDelete) {
                    var model_id = $(this).attr("data-id");
                    var url = "{{ route('user.destroy', ':model_id') }}";

                    $.ajax({
                        url: url.replace(':model_id', model_id),
                        type: 'POST',
                        data: {
                            '_method': "DELETE",
                            '_token': "{{ csrf_token() }}"
                        },
                        success: function(data) {
                            if (!data.error) {
                                swal("Success!", data.success, "success")
                                    .then(() => window.location.reload());
                            } else {
                                swal("Error!", data.error, "error");
                            }
                        },
                        error: function() {
                            swal("Error!", "Something went wrong", "error");
                        },
                    });
                }
            });
    });
</script>
