@extends('layouts.master')
@section('content')
    <style>
        .error {
            color: red;
        }

        .password-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            /* Center align items vertically */
            height: 2.5em;
            /* Adjust based on your input field height */
        }

        .password-toggle {
            position: absolute;
            right: 10px;
            cursor: pointer;
            font-size: 1.2em;
            z-index: 1;
            /* Ensure it's on top of other elements */
        }

        input.form-control {
            padding-right: 40px;
            /* Add padding to ensure text does not overlap with the icon */
        }
        #overlay {
            position: fixed;
            top: 0;
            z-index: 1070;
            width: 100%;
            height: 100%;
            display: none;
            background: rgba(0, 0, 0, 0.6);
        }

        .cv-spinner {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px #ddd solid;
            border-top: 4px #2e93e6 solid;
            border-radius: 50%;
            animation: sp-anime 0.8s infinite linear;
        }
         .modal:nth-of-type(even) {
            z-index: 1052 !important;
        }
        .modal-backdrop.show:nth-of-type(even) {
            z-index: 1051 !important;
        } 
        #userNameModal{
            z-index: 1058 !important;
        }

    </style>
    <div class="content-wrapper">
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Team Member List</h1>
                    </div>
                    <div class="col-sm-6">

                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
                            <li class="breadcrumb-item active">Team Member List</li>
                        </ol>

                    </div>
                </div>
            </div>
        </div>
        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <!-- Default box -->
                        <div class="card">
                            <!-- <form action="" name="form"> -->
                            <form action="" name="form">
                                <div class="card-header">
                                    <h3 class="card-title">Team Member List
                                        <!-- <button type="submit" class="btn btn-primary">
                                                Submit
                                            </button> -->
                                    </h3>
                                    <div class="card-tools">
                                        <a onclick="openAddTeamMemberModal()" class="btn btn-sm btn-primary"><i
                                                class="fa fa-plus"></i> Add Team Member </a>
                                    </div>
                                    <div class="card-tools">
                                        <button type="button" class="btn btn-tool" data-card-widget="collapse"
                                            title="Collapse">
                                            <!-- <i class="fas fa-minus"></i> -->
                                        </button>
                                        <!-- <button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
                                            <i class="fas fa-times"></i>
                                        </button> -->
                                    </div>
                                </div>
                                <div class="card-body table-responsive">
                                    {{ $dataTable->table() }}
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-- <div class="col-6">
                        <img style="width: 800px;height:800px;" src="https://frenzinsoftwares.com/frenzincrm_help/team-member.gif" alt="category.gif">
                    </div> -->
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="assignEmailPopup" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
        aria-hidden="true">
    </div>

    <div class="modal fade" id="isadmin-modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modal-title"></h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="isAdminUpdateForm" method="post" data-url="{{ route('users.updateIsAdmin') }}">
                    @csrf
                    <div class="modal-body">
                        <input type="hidden" name="CustomerID" id="CustomerID">
                        <input type="hidden" name="isadminvalue" id="isadminvalue">
                        <input type="hidden" name="user_id" id="user_id">
                    </div>
                    <div class="modal-footer justify-content-between">
                        <button type="button" id="isAdminCloseBtn" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="submit" id="isAdminSubmitBtn"  class="btn btn-primary">OK</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<!-- Modal -->
    <div class="modal fade" id="userNameModal" role="dialog" tabindex="-1" aria-labelledby="userNameModalLabel" aria-hidden="true">
        <div  class="modal-dialog"  role="document">
            <div class="modal-content" >
                <div class="modal-header">
                    <h5 class="modal-title" id="userNameModalLabel">Update Name</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form  id="userUpdateForm" data-url="{{route('updateUserName')}}" name="userUpdateForm" >
                        <input class="form-control" id="userUpdateName" name="userUpdateName" />
                        <input type="hidden" id="userIdHidden" name="userIdHidden" />
                        <input type="hidden" id="userNameUpdateCustomerId" name="userNameUpdateCustomerId" />
                        <span class="text-danger userUpdateName-error modal-error"></span>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary closeBtnupdateuserNameModal" data-dismiss="modal">Close</button>
                    <button type="submit" form="userUpdateForm" id="modalSubmitFormBtn" name="submit" class="btn btn-primary modal-submit">
                        <span class="submit-text">Submit</span>
                        <div class="spinner-border text-light submit-loader" role="status" style="width:20px;height:20px;display:none;">
                            <span class="visually-hidden"></span>
                        </div>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
  <div class="modal fade" id="updateUserEmailModal" role="dialog" tabindex="-1" aria-labelledby="updateUserEmailModalLabel" aria-hidden="true">
    <div  class="modal-dialog"  role="document">
      <div class="modal-content" >
        <div class="modal-header">
          <h5 class="modal-title" id="updateUserEmailModalLabel">Update Email</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
            <form  id="userEmailUpdateForm"  name="userEmailUpdateForm" data-url="{{route('updateUserEmail')}}">
                <input class="form-control" id="userEmailUpdate" name="userEmailUpdate" />
            <input type="hidden" id="userEmailcustomerIdHidden" name="userEmailcustomerIdHidden" />

            <span class="text-danger userEmailUpdate-error modal-email-error"></span>
            </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary closeBtnupdateupdateUserEmailModal" data-dismiss="modal">Close</button>
          <button type="submit" form="userEmailUpdateForm" id="modalEmailSubmitFormBtn" name="submit" class="btn btn-primary modalEmailSubmitFormBtn">

            <span class="submit-text">Submit</span>
            <div class="spinner-border text-light submit-loader" role="status" style="width:20px;height:20px;display:none;">
                <span class="visually-hidden"></span>
            </div>
            </button>
        </div>
      </div>
    </div>
  </div>
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
  <div class="modal fade" id="updateUserPhoneModal" role="dialog" tabindex="-1" aria-labelledby="updateUserPhoneModalLabel" aria-hidden="true">
    <div  class="modal-dialog"  role="document">
      <div class="modal-content" >
        <div class="modal-header">
          <h5 class="modal-title" id="updateUserPhoneModalLabel">Update Phone</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
            <form  id="updateUserPhoneForm"  name="updateUserPhoneForm" data-url="{{route('updateUserPhone')}}">
                <label for="userPhoneUpdate">Old Phone</label>
                <input class="form-control" id="userPhoneUpdate" name="userPhoneUpdate" readonly />
                <span class="text-danger userPhoneUpdate-error modal-phone-error"></span>
                <label for="userNewPhoneUpdate">Enter New Phone</label>
                <input class="form-control" id="userNewPhoneUpdate" name="userNewPhoneUpdate" />
                <span class="text-danger userNewPhoneUpdate-error modal-phone-error"></span>
                <div class="userUpdatePhoneOtpBox" style="display: none;">
                    <label for="userUpdatePhoneOtp">Enter OTP</label>
                    <input class="form-control" id="userUpdatePhoneOtp" name="userUpdatePhoneOtp" />
                    <span class="text-danger userUpdatePhoneOtp-error modal-phone-error"></span>

                </div>
                <input type="hidden" id="userPhonecustomerIdHidden" name="userPhonecustomerIdHidden" />

            </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary closeBtnupdateupdateUserPhoneModal" data-dismiss="modal">Close</button>
          <button type="submit" form="updateUserPhoneForm" id="modalPhoneSubmitFormBtn" name="submit" class="btn btn-primary modalPhoneSubmitFormBtn">

            <span class="submit-text">Verify</span>
            <div class="spinner-border text-light submit-loader" role="status" style="width:20px;height:20px;display:none;">
                <span class="visually-hidden"></span>
            </div>
            </button>
        </div>
      </div>
    </div> 
  </div>

    <div class="modal" tabindex="-1" role="dialog" id="emailUpdateModel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Email</h5>
                </div>
                <div class="modal-body">
                    <div class="card-body">
                        <form action="{{ route('edit-user-email') }}" id="email_update_form" method="post">
                            @csrf
                            <input type="hidden" name="user_id" id="edit_email_user_id">
                            <div class="form-group">
                                <label class="form-label">Sender Name</label>
                                <input class="form-control col-lg-12" type="text" name="sender_name" id="sender_name">
                                <label class="form-label">Sender Email</label>
                                <input class="form-control col-lg-12" type="text" name="sender_email"
                                    id="sender_email">
                                <label class="form-label">CC Email</label>
                                <input class="form-control col-lg-12" type="text" name="cc_email" id="cc_email">
                                <label class="form-label">BCC Email</label>
                                <input class="form-control col-lg-12" type="text" name="bcc_email" id="bcc_email">
                            </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Edit</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Change Password Modal -->
    <div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form id="changePassword" method="post" data-url="{{ route('users.update_user_password') }}"
                    name="form" enctype="multipart/form-data">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Change Password</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input type='hidden' name="CustomerID" id="Customer_Id" value="">
                        <div class="form-group">
                            <label for="password">New Password</label>
                            <div class="password-wrapper">
                                <input minlength="6" type="password" name="password"
                                    class="form-control required" id="password" placeholder="Enter New Password"
                                    value="" autocomplete="current-password">
                                <span class="password-toggle" onclick="togglePassword()">
                                    <i id="password-icon" class="fas fa-eye"></i> <!-- Font Awesome eye icon -->
                                </span>
                            </div>
                            <label for="password" class="error"></label> <!-- Error message container -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="changePwdCloseBtn" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="changePwdSubmitBtn" class="btn btn-primary">Save Password</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add TeamMember Modal -->
    <div class="modal fade" id="addTeamMemberModal" tabindex="-1" role="dialog" aria-labelledby="addTeamMemberModalLabel"
    aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addTeamMemberModalLabel">Add Team Member</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form method="POST" id="addTeamMemberForm">
                        @csrf

                        <div class="row mb-3">
                            <label for="name" class="col-md-4 col-form-label text-md-end">{{ __('Username') }}</label>

                            <div class="col-md-6">
                                <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>

                                @error('name')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email">

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="phone" class="col-md-4 col-form-label text-md-end">{{ __('Mobile Number') }}</label>

                            <div class="col-md-6">
                                <input id="phone" maxlength="10" type="text" class="form-control @error('phone') is-invalid @enderror" name="phone" value="{{ old('phone') }}" required>

                                @error('phone')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">

                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                            <div style="position: relative;">

                                <input id="newPassword" type="password" style="padding-right: 35px;" class="form-control @error('password') is-invalid @enderror changePasswordTypeInput" name="new_password" required autocomplete="new-password">
                                <i class="fas fa-eye-slash changePasswordType" style="position: absolute;top:13px;right:12px;cursor:pointer;"></i>

                                </div>

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password-confirm" class="col-md-4 col-form-label text-md-end">{{ __('Confirm Password') }}</label>

                            <div class="col-md-6">
                            <div style="position: relative;">

                                <input id="password-confirm" type="password" style="padding-right: 35px;" class="form-control changePasswordTypeInput" name="password_confirmation" required autocomplete="new-password">
                                <i class="fas fa-eye-slash changePasswordType" style="position: absolute;top:13px;right:12px;cursor:pointer;"></i>
                           
                                </div>

                            </div>
                        </div>

                        <div class="row mt-1 mb-0">
                            <div class="col-md-6 offset-md-4">
                                <div class="error" id="cf-response-message"></div>
                            </div>
                        </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" id="addTeamMemberSubmitBtn"  class="btn btn-primary">Submit</button>
                </div>
                </form>
            </div>
        </div>
    </div>

    <!-- OTP Modal -->
    <div class="modal fade" id="otpModal" tabindex="-1" role="dialog" aria-labelledby="otpModalLabel"
    aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="otpModalLabel">Enter OTP</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="otpSubmitForm" data-url="{{ route('user-register.userCreate') }}" method="post">
                        @csrf
                        <input type="hidden" name="id" id="modalId" class="form-control" value="">
                        <input type="hidden" name="temp" id="modalTemp" class="form-control" value="">
                        <input type="hidden" name="name" id="modalName" class="form-control" value="">
                        <input type="hidden" name="email" id="modalEmail" class="form-control" value="">
                        <input type="hidden" name="phone" id="modalPhone" class="form-control" value="">
                        <input type="hidden" name="password" id="modalPassword" class="form-control" value="">
                        <input type="hidden" name="confirm_password" id="modalConfirmPassword" class="form-control" value="">
                        <div class="form-group">
                            <label for="">Otp</label>
                            <input type="text" name="otp" class="form-control" id="modalOtp" value=""
                                required>
                            <div class="error" id="otp-message"></div>
                        </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" id="otpSubmitBtn"  class="btn btn-primary">Submit</button>
                </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Open Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" role="dialog" aria-labelledby="settingsModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content" id="settingsModalContent">
                
            </div>
        </div>
    </div>

    <div id="overlay">
        <div class="cv-spinner">
            <span class="spinner"></span>
        </div>
    </div>


    @push('scripts')
        {{ $dataTable->scripts() }}

        <script>
            let otpVerify = false;
            function openAddTeamMemberModal() {
                // window.LaravelDataTables["users-table"].ajax.reload();
                $('#addTeamMemberModal').modal('show');
            }
            $(document).ready(function() {
                $(document).on('click',".changePasswordType",function(){
            var eye = $(this);
            var password = eye.parent().children("input.changePasswordTypeInput");
            var type = password.prop("type");
            console.log(type,password,eye);
            if(type == "password"){
                password.prop("type","text");
                console.log("hi");

                eye.addClass("fa-eye");
                eye.removeClass("fa-eye-slash");
            }
            else
            {
                eye.addClass("fa-eye-slash");
                eye.removeClass("fa-eye");
            
                password.prop("type","password");
            }
        })
                $('#addTeamMemberForm').validate({
                    rules: {
                        name: {
                            required: true,
                        },
                        email: {
                            required: true,
                        },
                        phone: {
                            required: true,
                            digits: true, 
                            maxlength: 10,
                            minlength: 10,
                        },
                        new_password: {
                            minlength: 6,
                        },
                        password_confirmation: {
                            minlength: 6,
                            equalTo: '[name="new_password"]'
                        }
                    },
                    errorPlacement: function(error, element) {
                        error.insertAfter(element);
                    },
                    submitHandler: function(form) {
                        $("#overlay").fadeIn(300);
                        // alert('ajax call');
                        // return;
                        // console.log($('#registerForm').serialize()); return false;
                        $.ajax({
                            url: '{{ route('user-register.getOtp') }}',
                            type: "POST",
                            data: {
                                "_token": "{{ csrf_token() }}",
                                "email": $('#email').val(),
                                "mobile": $('#phone').val()
                            },
                            success: function(response) {
                                // console.log(response.status);
                                if (response) {
                                    $('#cf-response-message').text(response.message);
                                }
                                if (response.status) {
                                    $('#modalTemp').val(response.data);
                                    $('#modalName').val($('#name').val());
                                    $('#modalEmail').val($('#email').val());
                                    $('#modalPhone').val($('#phone').val());
                                    $('#modalPassword').val($('#newPassword').val());
                                    $('#modalConfirmPassword').val($('#password-confirm').val());
                                    $('#otpModal').modal('show');
                                }
                                setTimeout(function() {
                                    $("#overlay").fadeOut(300);
                                }, 500);
                            },
                            error: function(data) {
                                console.log(data);
                                $('#cf-response-message').text(data.responseText);
                                setTimeout(function() {
                                    $("#overlay").fadeOut(300);
                                }, 500);
                            }
                        });
                    }
                });

                $("#otpSubmitBtn").click(function(e) {
                    e.preventDefault();
                    var url = $('#otpSubmitForm').data('url');
                    // console.log(atob($('#modalTemp').val()),$('#modalOtp').val());
                    if(atob($('#modalTemp').val()) != $('#modalOtp').val()){
                        $('#otp-message').text("Otp not matched!");
                        return false;
                    }else{
                        $("#overlay").fadeIn(300);
                        $('#otp-message').text(" ");
                        // console.log($('#otpSubmitForm').serialize()); return false;
                        // alert('ajax call');
                        $.ajax({
                            url: url,
                            type: "POST",
                            data: $('#otpSubmitForm').serialize(),
                            success: function(response) {
                                $('#otpModal').modal('hide');
                                if (response) {
                                    if (!response.status) {
                                        $('#otp-message').text(response.message);
                                    }else{
                                        $('#addTeamMemberModal').modal('hide');
                                        swal({
                                            title: "Success!",
                                            text: response.message,
                                            icon: "success"
                                        });
                                        // render datatable
                                        window.LaravelDataTables["users-table"].ajax.reload();
                                    }
                                }
                                setTimeout(function() {
                                    $("#overlay").fadeOut(300);
                                }, 500);
                            },
                            error: function(data) {
                                console.log(data);
                                $('#otp-message').text(data.responseText);
                                setTimeout(function() {
                                    $("#overlay").fadeOut(300);
                                }, 500);
                            }
                        });
                        return false;
                    }
                });

                $('#isAdminCloseBtn').click(function() {
                    var isChecked = $("#markAsAdmin").is(":checked");
                    if(isChecked){
                        $('#markAsAdmin').prop('checked', false);
                    }else{
                        $('#markAsAdmin').prop('checked', true);
                    }
                    $('#isadmin-modal').modal('hide');
                });

                $("#isAdminSubmitBtn").click(function(e) {
                    e.preventDefault();
                    var url = $('#isAdminUpdateForm').data('url');
                    $("#overlay").fadeIn(300);
                    // console.log($('#isAdminUpdateForm').serialize()); return false;
                    // alert('ajax call');
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: $('#isAdminUpdateForm').serialize(),
                        success: function(response) {
                            $('#isadmin-modal').modal('hide');
                            if (response) {
                                swal({
                                    title: "Success!",
                                    text: response.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(response.html);
                            }
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                        },
                        error: function(data) {
                            console.log(data);
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                        }
                    });
                    return false;
                });

                $('#changePwdCloseBtn').click(function() {
                    $('#changePassword')[0].reset();
                    $('.error').html('')
                    $('#changePasswordModal').modal('hide');
                });

                $("#changePwdSubmitBtn").click(function(e) {
                    e.preventDefault();
                    var url = $('#changePassword').data('url');
                    $("#overlay").fadeIn(300);
                    // console.log($('#changePassword').serialize()); return false;
                    // alert('ajax call');
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: $('#changePassword').serialize(),
                        success: function(response) {
                            $('#changePasswordModal').modal('hide');
                            if (response) {
                                swal({
                                    title: "Success!",
                                    text: response.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(response.html);
                            }
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                        },
                        error: function(data) {
                            console.log(data);
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                        }
                    });
                    return false;
                });

                $('#changePassword').validate({
                    rules: {
                        password: {
                            required: true,
                            minlength: 6
                        }
                    },
                    messages: {
                        password: {
                            required: "Please enter a password",
                            minlength: "Your password must be at least 6 characters long"
                        }
                    },
                    errorPlacement: function(error, element) {
                        // Custom placement of the error message
                        if (element.attr("name") === "password") {
                            error.insertAfter(element.parent().find('.password-toggle'));
                        } else {
                            error.insertAfter(element);
                        }
                    }
                });
            });
        </script>
        <script>
            function togglePassword() {
                const passwordField = document.getElementById('password');
                const passwordIcon = document.getElementById('password-icon');

                if (passwordField.type === 'password') {
                    passwordField.type = 'text';
                    passwordIcon.classList.remove('fa-eye');
                    passwordIcon.classList.add('fa-eye-slash');
                } else {
                    passwordField.type = 'password';
                    passwordIcon.classList.remove('fa-eye-slash');
                    passwordIcon.classList.add('fa-eye');
                }
            }
        </script>
        <script>
                function setModalLoader(state) {
        var text = $(".modal-submit").children(".submit-text");
        var loader = $(".modal-submit").children(".submit-loader");
        if (state) {
            loader.show()
            $(".modal-submit").prop("disabled", true);
        } else {
            $(".modal-submit").prop("disabled", false);
            loader.hide()
        }
    }

    function setEmailUpdateLoader(state) {
        var text = $(".modalEmailSubmitFormBtn").children(".submit-text");
        var loader = $(".modalEmailSubmitFormBtn").children(".submit-loader");
        if (state) {
            loader.show()
            $(".modalEmailSubmitFormBtn").prop("disabled", true);
        } else {
            $(".modalEmailSubmitFormBtn").prop("disabled", false);
            loader.hide()
        }
    }
    
    function setPhoneUpdateLoader(state) {
        var text = $(".modalPhoneSubmitFormBtn").children(".submit-text");
        var loader = $(".modalPhoneSubmitFormBtn").children(".submit-loader");
        if (state) {
            loader.show()
            $(".modalPhoneSubmitFormBtn").prop("disabled", true);
        } else {
            $(".modalPhoneSubmitFormBtn").prop("disabled", false);
            loader.hide()
        }
    }

    function changeUpdatePhoneBtn(isVerify){
        var text = $(".modalPhoneSubmitFormBtn").children(".submit-text");
        if(isVerify){
            $(".userUpdatePhoneOtpBox").hide();
            otpVerify = false;
            text.text("Verify");
        }
        else{
            otpVerify = true;

            $(".userUpdatePhoneOtpBox").show();
            text.text("Submit");
        }
    }

    $(document).ready(function(){
        $('#userNameModal').on('shown.bs.modal', function (event) {
            var ele = $(event.relatedTarget);
            var userName = ele.data("user-name");
            var userId = ele.data("user-id")
            $("#userIdHidden").val(userId);
            $("#userUpdateName").val(userName);
            $("#userNameUpdateCustomerId").val(ele.data("customer-id"));
            // $('#userNameModal').modal('hide');

        });
        $('#userNameModal').on('hide.bs.modal', function (event) {
            $("#userIdHidden").val("");
            $("#userUpdateName").val("");
            $("#userNameUpdateCustomerId").val("");
        });
        $('#updateUserEmailModal').on('shown.bs.modal', function (event) {
            var ele = $(event.relatedTarget);
            // console.log(ele.data());
            var userEmail = ele.data("user-email");
            var custId = ele.data("customer-id")
            $("#userEmailcustomerIdHidden").val(custId);
            $("#userEmailUpdate").val(userEmail);
            // // $('#userNameModal').modal('hide');

        });
        $('#updateUserEmailModal').on('hide.bs.modal', function (event) {
            $("#userEmailcustomerIdHidden").val("");
            $("#userEmailUpdate").val("");
        });
        $('#addTeamMemberModal').on('hide.bs.modal', function (event) {
            $("#name").val("");
            $("#email").val("");
            $("#phone").val("");
            $("#password-confirm").val("");
            $("#newPassword").val("");
            // $(".error").html('');
            $('#addTeamMemberForm').validate().resetForm();

        });
        
        $('#updateUserPhoneModal').on('shown.bs.modal', function (event) {
            var ele = $(event.relatedTarget);
            changeUpdatePhoneBtn(true);
            // console.log(ele.data());
            var userPhone = ele.data("user-phone");
            var custId = ele.data("customer-id")
            $("#userPhonecustomerIdHidden").val(custId);
            $("#userPhoneUpdate").val(userPhone);
            $("#userNewPhoneUpdate").val("");
            $("#userUpdatePhoneOtp").val("");

            
            // // $('#userNameModal').modal('hide');

        });
        $('#updateUserPhoneModal').on('hide.bs.modal', function (event) {
            $("#userPhonecustomerIdHidden").val("");
            $("#userPhoneUpdate").val("");
            $("#userNewPhoneUpdate").val("");
            $("#userUpdatePhoneOtp").val("");
            changeUpdatePhoneBtn(true);

        });
  

        $("#userUpdateForm").submit(function(e) {
            e.preventDefault();
            const Url = $(this).data('url')
            if ((Url !== undefined && Url !== null)) {
                var form_id = $(this)[
                    0];
                var formData = new FormData(form_id);
                $(".modal-error").html("");
                setModalLoader(true);
                $.ajax({
                    type: "POST",
                    url: Url,
                    data: formData,
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
                            'content')
                    },
                    success: function(response) {
                        setModalLoader(false);

                        console.log(response);
                        if (response.status) {
                                    swal({
                title: response.message,
                icon: 'success'
                                    });
                                    
                           
                                    $('.closeBtnupdateuserNameModal').click();
                                    $('.modal-backdrop').remove();
                                    $("#MemberDetailModalName").html(response.newName)
                                    $(".updateUserName").data("user-name",response.newName);
                              
                                    window.LaravelDataTables["users-table"].ajax.reload();

                            
                        } else {
                            swal({
                title: response.message,
                icon: 'error'
                                    });
                            
                        }
                    },
                    error: function(xhr) {
                        setModalLoader(false);
                        var error = xhr.responseJSON;
                        // console.log(xhr.responseJSON);
                        if (xhr.status == 422) {
                            Object.entries(error.error).forEach(function(item, index) {
                                const [key, value] = item;
                                $(`.${key}-error`).html(value);
                            })
                        } else {
                            // alert(error.message)
                            swal({
                title: error.message,
                icon: 'error'
                                    });
                          
                        }


                    }
                });

                
            }
        })

        $("#userEmailUpdateForm").submit(function(e) {
            e.preventDefault();
            const Url = $(this).data('url')
            if ((Url !== undefined && Url !== null)) {
                var form_id = $(this)[
                    0];
                var formData = new FormData(form_id);
                $(".modal-email-error").html("");
                setEmailUpdateLoader(true);
                $.ajax({
                    type: "POST",
                    url: Url,
                    data: formData,
                    dataType: "json",
                    cache: false,
                    processData: false,
                    contentType: false,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
                            'content')
                    },
                    success: function(response) {
                        setEmailUpdateLoader(false);

                        console.log(response);
                        if (response.status) {

                         
                                  
   swal({
                title: response.message,
                icon: 'success'
                                    });
                                    $('.closeBtnupdateupdateUserEmailModal').click();
                                    $('.modal-backdrop').remove();
                                    $("#MemberDetailModalEmail").html(response.newEmail)
                                    $(".updateUserEmail").data("user-email",response.newEmail);

                                    // $('.dataTable').DataTable().ajax.reload();
                                    window.LaravelDataTables["users-table"].ajax.reload();

                            
                        } else {
                            swal({
                title: response.message,
                icon: 'error'
                                    });
                        }
                    },
                    error: function(xhr) {
                        setEmailUpdateLoader(false);
                        var error = xhr.responseJSON;
                        // console.log(xhr.responseJSON);
                        if (xhr.status == 422) {
                            Object.entries(error.error).forEach(function(item, index) {
                                const [key, value] = item;
                                $(`.${key}-error`).html(value);
                            })
                        } else {
                            // alert(error.message)

                            swal({
                title: error.message,
                icon: 'error'
                                    });

                        }


                    }
                });

                
            }
        })

        $("#updateUserPhoneForm").submit(function(e) {
            e.preventDefault();
            const OtpUrl = "{{route('sendUserPhoneUpdateOtp')}}";
            var form_id = $(this)[
                        0];
                    var formData = new FormData(form_id);
                    $(".modal-phone-error").html("");
            if(!otpVerify){
                // console.log("call otp api");
                setPhoneUpdateLoader(true);

                $.ajax({
                        type: "POST",
                        url: OtpUrl,
                        data: formData,
                        dataType: "json",
                        cache: false,
                        processData: false,
                        contentType: false,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
                                'content')
                        },
                        success: function(response) {
                            setPhoneUpdateLoader(false);
    
                            console.log(response);
                            if (response.status) {
                                swal({
                title: response.message,
                icon: 'success'
                                    });
                               
                    $(".modal-phone-error").html("");

                                        changeUpdatePhoneBtn(false);
                                        // $('.closeBtnupdateupdateUserEmailModal').click();
                                        // $('.modal-backdrop').remove();
                                        // $('.dataTable').DataTable().ajax.reload();
                                  
                            } else {
                                swal({
                title: response.message,
                icon: 'error'
                                    });

                            }
                        },
                        error: function(xhr) {
                            setPhoneUpdateLoader(false);
                            var error = xhr.responseJSON;
                            // console.log(xhr.responseJSON);
                            if (xhr.status == 422) {
                                Object.entries(error.error).forEach(function(item, index) {
                                    const [key, value] = item;
                                    $(`.${key}-error`).html(value);
                                })
                            } else {
                                // alert(error.message)
    
                                swal({
                title: error.message,
                icon: 'error'
                                    });

                            }
    
    
                        }
                    });
            }
            else{
                const Url = $(this).data('url')
                if ((Url !== undefined && Url !== null)) {
                   
                    setPhoneUpdateLoader(true);
                    $.ajax({
                        type: "POST",
                        url: Url,
                        data: formData,
                        dataType: "json",
                        cache: false,
                        processData: false,
                        contentType: false,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr(
                                'content')
                        },
                        success: function(response) {
                            setPhoneUpdateLoader(false);
    
                            console.log(response);
                            if (response.status) {
    
                                swal({
                title: response.message,
                icon: 'success'
                                    });
                                        
                                        $('.closeBtnupdateupdateUserPhoneModal').click();
                                        $('.modal-backdrop').remove();
                                    window.LaravelDataTables["users-table"].ajax.reload();
                                    $("#MemberDetailModalPhone").html(response.newPhone)
                                    $(".updateUserPhone").data("user-phone",response.newPhone);


                                        // $('.dataTable').DataTable().ajax.reload();
                                        changeUpdatePhoneBtn(true);
                                 
                            } else {
                                swal({
                title: response.message,
                icon: 'error'
                                    });
                                // alert(response.message)
                            }
                        },
                        error: function(xhr) {
                            setPhoneUpdateLoader(false);
                            var error = xhr.responseJSON;
                            // console.log(xhr.responseJSON);
                            if (xhr.status == 422) {
                                Object.entries(error.error).forEach(function(item, index) {
                                    const [key, value] = item;
                                    $(`.${key}-error`).html(value);
                                })
                            } else {
                                // alert(error.message)
    
                                swal({
                title: error.message,
                icon: 'error'
                                    });
                            }
    
    
                        }
                    });
    
                    
                }
            }
        })
        
    })
            
        </script>
    @endpush
    <script>
        function blockUnblockMember(elm) {
            let id = $(elm).data('id');
            let url = $(elm).data('url');
            swal({
                title: 'Are you sure!',
                icon: 'error',
                dangerMode: true,
                buttons: true,
                confirm: "Confirm",
            }).then(function(isConfirm) {
                if (isConfirm === true) {
                    $.ajax({
                        type: 'GET',
                        url: url,
                        dataType: 'json',
                        success: function(data) {
                            if (data) {
                                swal({
                                    title: "Success!",
                                    text: data.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(data.html);
                                window.LaravelDataTables["users-table"].ajax.reload();
                            }
                            // window.location.reload();
                            // console.log(data);
                        },
                        error: function(data) {
                            console.log(data);
                        }
                    });
                }
            });
        }
        function updateIsAdmin(elm) {
            var CustomerID = $(elm).attr('data-CustomerID');
            var user_id = $(elm).attr('data-user_id');
            var isadminvalue = elm.value;
            if (isadminvalue != "true") {
                $("#modal-title").html("Are you sure? you want to make it admin?");
            } else {
                $("#modal-title").html("Are you sure? you want to remove admin?");
            }

            $("#CustomerID").val(CustomerID);
            $("#user_id").val(user_id);
            $("#isadminvalue").val(isadminvalue);
            $("#isadmin-modal").modal('show');
        }

        function emailupdate(elm) {
            $('#edit_email_user_id').val(elm.id);
            $('#sender_name').val($('#' + elm.id).attr('sender_name'));
            $('#sender_email').val($('#' + elm.id).attr('sender_email'));
            $('#cc_email').val($('#' + elm.id).attr('cc_email'));
            $('#bcc_email').val($('#' + elm.id).attr('bcc_email'));
            $('#emailUpdateModel').modal('show');
        }

        function assignEmail(elm) {
            $.ajax({
                type: "POST",
                url: "{{ url('user/popup-assign-email') }}" + '/' + elm.id,
                data: {
                    "_token": "{{ csrf_token() }}"
                },
                success: function(data) {
                    $('#assignEmailPopup').html(data.html);
                    $('#assignEmailPopup').modal('show');
                }
            });
        }

        function change_password(elm) {
            var Customer_Id = $(elm).attr('data-id');
            $("#Customer_Id").val(Customer_Id);
            $('#changePassword')[0].reset();
            $('.error').html('')
            $('#changePasswordModal').modal('show');
        }


        function addremoveAdmin(elm) {
            let id = $(elm).data('id');
            let url = $(elm).data('url');
            swal({
                title: 'Are you sure!',
                icon: 'success',
                dangerMode: true,
                buttons: true,
                confirm: "Confirm",
            }).then(function(isConfirm) {
                if (isConfirm === true) {
                    $.ajax({
                        type: 'GET',
                        url: url,
                        dataType: 'json',
                        success: function(data) {
                            $('#isadmin-modal').modal('hide');
                            if (data) {
                                swal({
                                    title: "Success!",
                                    text: data.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(data.html);
                            }
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                            // window.location.reload();
                            // console.log(data);
                        },
                        error: function(data) {
                            console.log(data);
                        }
                    });
                }else{
                    var isChecked = $("#pcAccess").is(":checked");
                    if(isChecked){
                        $('#pcAccess').prop('checked', false);
                    }else{
                        $('#pcAccess').prop('checked', true);
                    }
                }
            });
        }

        function settings_popup(elm) {
            let id = $(elm).data('id');
            let url = $(elm).data('url');
            $.ajax({
                url: url+'/'+id,
                method: 'GET',
                success: function (result) {
                    $('#settingsModalContent').html(result);
                    $('#settingsModal').modal('show');
                }, error: function (error) {
                }
            });
        }

        function updatePermissionNew(elm) {
            let CustomerID = $(elm).data('customerid');
            let userId = $(elm).data('userid');
            let permissionName = $(elm).data('permissionname');
            var isChecked = $(elm).is(":checked");
            if(isChecked){
                var permissionValue = "1";
            }else{
                var permissionValue = "0";
            }
            let url = $(elm).data('url');
            swal({
                title: 'Are you sure!',
                icon: 'success',
                dangerMode: true,
                buttons: true,
                confirm: "Confirm",
            }).then(function(isConfirm) {
                if (isConfirm === true) {
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data:{
                            "_token": "{{ csrf_token() }}",
                            'userId' : userId,
                            'CustomerID' : CustomerID,
                            'permissionName' : permissionName,
                            'permissionValue' : permissionValue,
                        },
                        dataType: 'json',
                        success: function(data) {
                            if (data) {
                                swal({
                                    title: "Success!",
                                    text: data.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(data.html);
                            }
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                            // window.location.reload();
                            // console.log(data);
                        },
                        error: function(data) {
                            console.log(data);
                        }
                    });
                }else{
                    var isChecked = $(elm).is(":checked");
                    if(isChecked){
                        $(elm).prop('checked', false);
                    }else{
                        $(elm).prop('checked', true);
                    }
                }
            });
        }

        function updateDivisionNew(elm) {
            let CustomerID = $(elm).data('customerid');
            let userId = $(elm).data('userid');
            let divisionId = $(elm).data('divisionid');
            var isChecked = $(elm).is(":checked");
            if(isChecked){
                var divisionValue = "1";
            }else{
                var divisionValue = "0";
            }
            let url = $(elm).data('url');
            swal({
                title: 'Are you sure!',
                icon: 'success',
                dangerMode: true,
                buttons: true,
                confirm: "Confirm",
            }).then(function(isConfirm) {
                if (isConfirm === true) {
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data:{
                            "_token": "{{ csrf_token() }}",
                            'userId' : userId,
                            'CustomerID' : CustomerID,
                            'divisionId' : divisionId,
                            'divisionValue' : divisionValue,
                        },
                        dataType: 'json',
                        success: function(data) {
                            if (data) {
                                swal({
                                    title: "Success!",
                                    text: data.message,
                                    icon: "success"
                                });
                                $('#settingsModalContent').html(data.html);
                            }
                            setTimeout(function() {
                                $("#overlay").fadeOut(300);
                            }, 500);
                            // window.location.reload();
                            // console.log(data);
                        },
                        error: function(data) {
                            console.log(data);
                        }
                    });
                }else{
                    var isChecked = $(elm).is(":checked");
                    if(isChecked){
                        $(elm).prop('checked', false);
                    }else{
                        $(elm).prop('checked', true);
                    }
                }
            });
        }
        
    </script>
@endsection
