@extends('layouts.app')
@section('title', 'User List')
@section('pages')
    <style type="text/css">
        .breadcrumb-title {
            border-right: none;
        }

        .b adge {
            color: #222222;
            font-size: 0.7rem;
            border: 1px solid #cccccc;
            margin-top: 2px;
        }

        #ui-datepicker-div {
            z-index: 1500 !important;
        }

        .ui-widget-content {
            z-index: 1500;

        }
    </style>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
    <!--breadcrumb-->
    <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
        <div class="breadcrumb-title col-md-6"> User List
        </div>
        <div class="col-md-6">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb justify-content-md-end mb-0">
                    <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="8"
                            data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
                    <li class="breadcrumb-item" aria-current="page">Settings</li>
                    <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> User List</li>
                </ol>
            </nav>
        </div>
    </div>
    <!--end breadcrumb-->

    <div class="card style_table shadow-none radius-5 min-height">
        <div class="card-header py-3">
            @include('layouts.partials.nav-menu')
            <div class="row gx-2">
                <div class="col-lg-3 col-md-3 col-8">
                    <div class="position-relative">
                        <div class="position-absolute top-50 translate-middle-y search-icon px-3"><i
                                class="bi bi-search"></i></div>
                        <input class="form-control ps-5" type="search" id="search" placeholder="Search">
                    </div>
                </div>

                <div class="col-lg-2 col-md-2 col-4 dataTables_length" id="example_length">
                    <i class="bi bi-funnel"></i>
                    <select class="form-select sorting sorting-box" id="" name="example_length"
                        aria-controls="example">
                        <option value="10">Show: 10</option>
                        <option value="30">Show: 30</option>
                        <option value="50">Show: 50</option>
                    </select>
                </div>

                <div class="col-lg-2 col-md-2 col-4 dataTables_length" id="example_length">
                    <i class="bi bi-funnel"></i>
                    <select class="form-select role sorting-box" id="role" aria-controls="example">
                        <option value="">Select</option>
                        @foreach($roles as $role)
                            <option value="{!! $role !!}">{!! $role !!}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-lg-5 col-md-5">
                    <div class="ms-auto float-md-end">

                        <div class="btn-group">
                            <a href="javascript:history.back()" class="btn btn-outline-secondary me-1"><i
                                    class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
                        </div>

                        <div class="btn-group">
                            @if (in_array('users-create', $authRolePermissions))
                                <button type="button" class="btn btn-primary" id="create" data-bs-toggle="modal"
                                    data-bs-target="#commonModal"><i class="bx bx-plus"></i> Add New</button>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card-body" id="tables">

            @include('users.table')

            <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
            <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="name" />
            <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
        </div>
    @endsection
    @section('js')
        <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
        
        <script>
        $(document).ready(function() {
          $("body").on("change", 'select[name="user_type"]', function() {
            var userId = $(this).data('id');
            var userType = $(this).val();
            var url = '{{ route('users.change-user-type') }}';

            $.ajax({
              url: url,
              method: 'POST',
              data: {
                id: userId,
                user_type: userType
              },
              headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              },
              success: function(response) {
                if (response.success) {
                  showToast('success', response.message);
                } else {
                  showToast('error', response.message || "Something went wrong!");
                }
              },
              error: function(xhr) {
                console.error("Error: ", xhr);
                showToast('error', 'An error occurred: ' + xhr.responseText);
              }
            });
          });

          function showToast(type, message) {
            // Assuming you have a Toast function defined somewhere
            toastr[type](message);
          }
        });
        </script>



        <script>
            $(document).on('input',"[name='email']", function() {
                const input = $(this).val();
                $("[name='username']").val(input);
            });
            /***************** Global Delay Fucntion ***************/
            function delay(callback, ms) {
                var timer = 0;
                return function() {
                    var context = this,
                        args = arguments;
                    clearTimeout(timer);
                    timer = setTimeout(function() {
                        callback.apply(context, args);
                    }, ms || 0);
                };
            }


            var telInput = $('#phone_no , #whatsapp_no');
            telInput.intlTelInput({
                utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
                initialCountry: '{!! $countryCode !!}', // Set the new country code
                separateDialCode: true
            });

            $("#phone_no").on('input', function() {
                const onlyNumbers = allNumeric($(this).val());
                $("#phone_no").val(onlyNumbers);
            });
            $("#whatsapp_no").on('input', function() {
                const onlyNumbers = allNumeric($(this).val());
                $("#whatsapp_no").val(onlyNumbers);
            });

            $(document).ready(function() {
                function clear_icon() {
                    $('#id_icon').html('');
                    $('#post_title_icon').html('');
                }

                function fetch_data(page, sort_type, sort_by, query) {
                    var role = $("#role").val();
                    $.ajax({
                        url: "?page=" + page + "&sortby=" + sort_by + "&sorttype=" + sort_type + "&query=" +
                            query + "&role=" + role,
                        success: function(data) {
                            $('#tables').html('');
                            $('#tables').html(data);
                            $(document).ready(function() {
                                $.switcher();
                            });
                        }
                    })
                }

                $('body').on('change', '.role', function() {
                    var query = $('#search').val();
                    var column_name = $('.sorting').val();
                    var sort_type = $('#hidden_sort_type').val();
                    var page = 1 ? 1 : (this).attr('href').split('page=')[1];
                    fetch_data(page, sort_type, column_name, query);
                });

                /******** Change Like below ********/
                $(document).on('keyup', '#search', delay(function() {
                    var query = $('#search').val();

                    if (query.length < 2 && query.length != 0) {
                        return;
                    }

                    var column_name = $('.sorting').val();
                    var sort_type = $('#hidden_sort_type').val();
                    var page = 1 ? 1 : (this).attr('href').split('page=')[1];
                    fetch_data(page, sort_type, column_name, query);
                }, 700));

                $('body').on('change', '.sorting', function() {

                    var column_name = $(this).val();
                    console.log('perpage', column_name);
                    var order_type = $(this).data('sorting_type');
                    var reverse_order = '';
                    var page = 1 ? 1 : (this).attr('href').split('page=')[1];
                    var query = $('#search').val() ? $('#search').val() : '';
                    fetch_data(page, reverse_order, column_name, query);
                });
                $('body').on('click', '.pager a', function(event) {
                    event.preventDefault();
                    console.log('url', $(this).attr('href'));
                    var page = $(this).attr('href').split('page=')[1];
                    $('#hidden_page').val(page);
                    var column_name = $('.sorting').val() ? $('.sorting').val() : '';
                    var sort_type = $('#hidden_sort_type').val();
                    var query = $('#search').val() ? $('#search').val() : '';
                    $('li').removeClass('active');
                    $(this).parent().addClass('active');
                    fetch_data(page, sort_type, column_name, query);
                });

                $(document).on('click', '#create', function() {
                    $('#commonModalLabel').text('Add New User');
                    $('.save_button_span').text('Save User Details');
                    $.ajax({
                        url: "{!! route('users.create') !!}",
                        success: function(data) {
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').find('.modal-body').html(data);
                            $('.account-select').autocomplete({
                                autoFocus: true,
                                minLength: 0,
                                source: function(request, response) {
                                    if (request.term.length < 2) {
                                        $('[name="account_id"]').val('');
                                        return false;
                                    }

                                    $.ajax({
                                        url: '{{ route('users-search-accounts') }}',
                                        type: 'POST',
                                        dataType: 'json',
                                        data: {
                                            search_text: request.term
                                        },
                                        success: function(json) {
                                            if (json.error) {
                                                $('[name="account_id"]')
                                                    .val('');
                                                return false;
                                            }
                                            response($.map(json.result,
                                                function(item) {
                                                    return {
                                                        id: item.id,
                                                        name: item
                                                            .name,
                                                    };
                                                }));
                                        }
                                    });
                                },
                                select: function(event, ui) {
                                    event.preventDefault();
                                    $(this).val(ui.item.name);
                                    $('[name="account_id"]').val(ui.item.id);
                                    return false;
                                }
                            }).data("ui-autocomplete")._renderItem = function(ul, item) {
                                return $("<li>").append("<a>" + item.name + "</a>").appendTo(
                                ul);
                            };
                            var telInput = $('#phone_no, #whatsapp_no');

                            // Destroy the existing instances
                            telInput.intlTelInput('destroy');

                            // Reinitialize the input fields with the new country code
                            telInput.intlTelInput({
                                utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                                initialCountry: '{!! $countryCode !!}', // Set the new country code
                                separateDialCode: true
                            });
                        }
                    })
                })
                $(document).on('click', '.edit', function() {
                    $('#commonModalLabel').text('Edit User');
                    $('.save_button_span').text('Update User');
                    var id = $(this).data('id');
                    var url = `{!! route('users.edit', ':id') !!}`.replace(':id', id);

                    $.ajax({
                        url: url,
                        success: function(data) {
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').find('.modal-body').html(data);

                            var telInput = $('#phone_no, #whatsapp_no');

                            // Destroy the existing instances
                            telInput.intlTelInput('destroy');

                            // Reinitialize the input fields with the new country code
                            telInput.intlTelInput({
                                utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                                initialCountry: '{!! $countryCode !!}', // Set the new country code
                                separateDialCode: true
                            });
                            $('.account-select').autocomplete({
                                autoFocus: true,
                                minLength: 0,
                                source: function(request, response) {
                                    if (request.term.length < 2) {
                                        $('[name="account_id"]').val('');
                                        return false;
                                    }

                                    $.ajax({
                                        url: "{{ route('users-search-accounts') }}",
                                        type: 'POST',
                                        dataType: 'json',
                                        data: {
                                            action: 'users-search-accounts',
                                            search_text: request.term
                                        },
                                        success: function(json) {
                                            ;
                                            if (json.error) {
                                                $('[name="account_id"]')
                                                    .val('');
                                                return false;
                                            };
                                            response($.map(json.result,
                                                function(item) {
                                                    return {
                                                        id: item.id,
                                                        name: item
                                                            .name,
                                                    };
                                                }));
                                        }
                                    });
                                },
                                select: function(event, ui) {
                                    ;
                                    event.preventDefault();
                                    $(this).val(ui.item.name + "");
                                    $('[name="account_id"]').val(ui.item.id);
                                    return false;
                                }
                            }).data("ui-autocomplete")._renderItem = function(ul, item) {
                                ;
                                return $("<li>")
                                    .append("<a>" + item.name + "</a>")
                                    .appendTo(ul);
                            };
                        }
                    })
                })

                $(document).on('click', '.save_button', function(event) {
                    event.preventDefault();

                    if ($('#phone_no').val().trim() != '') {
                        var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                        var dailcode_array = dailcode_title.split("+");
                        $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
                    }

                    if ($('#whatsapp_no').val().trim() != '') {
                        var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                        var dailcode_array = dailcode_title.split("+");
                        $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
                    }

                    $('.error_company_id').hide();
                    $('.error_name').hide();
                    $('.error_username').hide();
                    $('.error_roles').hide();
                    $('.error_email').hide();
                    $('.error_prepared_by').hide();
                    var error = 0;

                    if ($('#commonModal').find('form').find('[name="company_id"]').val() == '') {
                        $('.error_company_id').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_company_id').hide();
                        }, 3000);

                    }
                    if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
                        $('.error_name').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_name').hide();
                        }, 3000);

                    }
                    if ($('#commonModal').find('form').find('input[name="username"]').val().trim() == '') {
                        $('.error_username').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_username').hide();
                        }, 3000);

                    }
                    if ($('#commonModal').find('form').find('[name="roles[]"]').val() == '') {
                        $('.error_roles').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_roles').hide();
                        }, 3000);

                    }
                    if ($('#commonModal').find('form').find('input[name="email"]').val().trim() == '') {
                        $('.error_email').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_email').hide();
                        }, 3000);

                    }
                    if ($('#commonModal').find('form').find('input[name="prepared_by"]').val().trim() == '') {
                        $('.error_prepared_by').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_prepared_by').hide();
                        }, 3000);
                    }
                    if ($('#commonModal').find('form').find('input[name="user_designation"]').val().trim() ==
                        '') {
                        $('.error_user_designation').show();
                        error = 1;
                        setTimeout(function() {
                            $('.error_user_designation').hide();
                        }, 3000);
                    }

                    if (error == 0) {
                        let formdata = new FormData($('#commonModal').find('form')[0]);

                        $.ajax({
                                url: $('#commonModal').find('form').attr('action'),
                                data: formdata,
                                processData: false,
                                contentType: false,
                                type: 'POST',
                                success: function(response) {
                                    if (response.success === true) {
                                        toastr.success(response.message, 'Success.');

                                        // hide modal
                                        $('#commonModal').modal('hide');
                                        $('#commonModal').find('.modal-body').html('');
                                        var page = $('.pager').find('.active a').attr('href') ==
                                            undefined ? 1 : $('.pager').find('.active a').attr('href')
                                            .split('page=')[1];
                                        var column_name = $('.sorting').val() ? $('.sorting').val() :
                                        '';
                                        var sort_type = $('#hidden_sort_type').val();
                                        var query = $('#search').val() ? $('#search').val() : '';

                                        fetch_data(page, sort_type, column_name, query);
                                    } else {
                                        toastr.error(response.message, 'Error!');
                                    }
                                }
                            })
                            .fail(function(jqXHR, textStatus, errorThrown) {
                                console.log('AJAX request failed:', textStatus, errorThrown);
                                toastr.error('An error occurred during the request.', 'Error!');

                                // hide modal
                                $('#commonModal').modal('hide');
                                $('#commonModal').find('.modal-body').html('');
                            });
                    }
                    error = 1;
                })

                /*********delete data**********/
                $("body").on("click", '.deleteDataCustom', function(event) {
                    dataString = {
                        "id": $(this).data('id')
                    };
                    var UrlValue = $(this).data('url');
                    var btn = $(this);

                    Swal.fire({
                        title: 'Are you sure you want to delete this?',
                        icon: 'warning',
                        showDenyButton: true,
                        showCancelButton: false,
                        confirmButtonText: 'Yes',
                        denyButtonText: 'No',
                    }).then((result) => {
                        /* Read more about isConfirmed, isDenied below */
                        if (result.isConfirmed) {
                            $.ajax({
                                url: UrlValue,
                                method: 'post',
                                data: {
                                    "_token": $('meta[name="csrf-token"]').attr('content'),
                                    "id": $(this).data('id')
                                },
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                },
                                beforeSend: function(xhr) {
                                    // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                                },
                                success: function(response) {
                                    if (response.success) {
                                        var ErroMsg = $(this).printErrorMsg(response
                                            .message);

                                        $(this).Toastshow('success', ErroMsg);

                                        var page = $('.pager').find('.active a').attr(
                                            'href') == undefined ? 1 : $('.pager').find(
                                            '.active a').attr('href').split('page=')[1];
                                        var column_name = $('.sorting').val() ? $(
                                            '.sorting').val() : '';
                                        var sort_type = $('#hidden_sort_type').val();
                                        var query = $('#search').val() ? $('#search')
                                        .val() : '';

                                        fetch_data(page, sort_type, column_name, query);
                                    } else {
                                        var ErroMsg = $(this).printErrorMsg(response
                                            .message);
                                        $(this).Toastshow('error', ErroMsg);
                                    }
                                },
                                error: function(data) {
                                    console.log("error ", data);
                                }
                            });
                        }
                    });
                });

                /*********change status**********/
                $("body").on("click", '.changeStatusCustom', function(event) {
                    dataString = {
                        "id": $(this).data('id'),
                        "status": $(this).data('status')
                    };
                    var UrlValue = $(this).data('url');
                    var status = $(this).data('status');
                    var changeStatus = $(this);
                    var btn = $(this);

                    Swal.fire({
                        title: 'Are you sure you want to change status?',
                        icon: 'warning',
                        showDenyButton: true,
                        showCancelButton: false,
                        confirmButtonText: 'Yes',
                        denyButtonText: 'No',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $.ajax({
                                url: UrlValue,
                                method: 'post',
                                data: dataString,
                                headers: {
                                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                },
                                beforeSend: function(xhr) {
                                    // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                                },
                                success: function(response) {
                                    if (response.success) {
                                        var ErroMsg = $(this).printErrorMsg(response
                                            .message);
                                        $(this).Toastshow('success', ErroMsg);

                                        var page = $('.pager').find('.active a').attr(
                                            'href') == undefined ? 1 : $('.pager').find(
                                            '.active a').attr('href').split('page=')[1];
                                        var column_name = $('.sorting').val() ? $(
                                            '.sorting').val() : '';
                                        var sort_type = $('#hidden_sort_type').val();
                                        var query = $('#search').val() ? $('#search')
                                        .val() : '';

                                        fetch_data(page, sort_type, column_name, query);
                                    } else {
                                        var ErroMsg = $(this).printErrorMsg(response
                                            .message);
                                        if (ErroMsg === '') {
                                            ErroMsg = "Something went wrong!";
                                        }
                                        $(this).Toastshow('error', ErroMsg);

                                        if (status == 1) {
                                            changeStatus.parent().find('.ui-switcher').attr(
                                                'aria-checked', false);
                                        } else {
                                            changeStatus.parent().find('.ui-switcher').attr(
                                                'aria-checked', true);
                                        }
                                    }
                                },
                                error: function(data) {
                                    console.log("error ", data);

                                    if (status == 1) {
                                        changeStatus.parent().find('.ui-switcher').attr(
                                            'aria-checked', false);
                                    } else {
                                        changeStatus.parent().find('.ui-switcher').attr(
                                            'aria-checked', true);
                                    }
                                }
                            });
                        } else if (result.isDenied) {
                            var page = $('.pager').find('.active a').attr('href') == undefined ? 1 : $(
                                '.pager').find('.active a').attr('href').split('page=')[1];
                            var column_name = $('.sorting').val() ? $('.sorting').val() : '';
                            var sort_type = $('#hidden_sort_type').val();
                            var query = $('#search').val() ? $('#search').val() : '';

                            fetch_data(page, sort_type, column_name, query);
                        }
                        //return false;
                    });
                    //return false;
                });
            });
        </script>
    @endsection
