@extends('app.app')

@section('title')
    Users
@endsection

@section('customcss')
    <style>
        /* .select2-container {
			z-index: 99999;
		} */
    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Users (<span id="count_users">0</span>)</p>
                                </div>
                                @can('user.create')
                                    <div class="col text-end">
                                        <a href="#" class="btn btn-sm btn-danger" id="btnAddNewUserModal">Add New User</a>
                                    </div>
                                @endcan
                                <div class="col-auto text-end ps-0">
                                    {{-- <button class="btn btn-sm btn-danger">Upload</button> --}}
                                    {{-- <button class="btn btn-sm btn-danger">Download</button> --}}
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="tUsers" class="table table-hover dataTable w-100">
                                    <thead>
                                        <tr class="">
                                            <th class="">#</th>
                                            <th class="text-center">Action</th>
                                            <th class="text-nowrap">Name</th>
                                            <th class="text-nowrap">Address</th>
                                            <th class="text-nowrap">Phone</th>
                                            <th class="text-nowrap">Email</th>
                                            <th class="text-nowrap">Join Date</th>
                                            <th class="text-nowrap">Last Login</th>
                                            <th class="text-nowrap">Company</th>
                                            <th class="text-start">Role</th>
                                            <th class="text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="">
                                            <td class="">1</td>
                                            <td class="">Emrsyf</td>
                                            <td class="">Jl. Letjen Mt. Haryono No.Kav. 20, RW.1, Cawang, Kec.
                                                Kramat jati, Kota Jakarta Timur, Daerah Khusus Ibukota Jakarta 13630</td>
                                            <td class="text-nowrap">021 83782235</td>
                                            <td class="text-nowrap">mail.us@jne.co.id</td>
                                            <td class="text-nowrap">Jan 22, 2022 14:02</td>
                                            <td class="text-nowrap">JNE</td>
                                            <td class="text-nowrap">
                                                <small class="text-muted">Administrator</small>
                                            </td>
                                            <th class="text-center">
                                                <span class="btn btn-sm btn-outline-success">Active</span>
                                            </th>
                                            <td class="align-baseline text-center text-nowrap">
                                                <a href="#" class="text-decoration-none me-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="View">
                                                    <span class="icon ion-eye fz-16"></span>
                                                </a>
                                                <a href="#" class="text-decoration-none me-1" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                                                    <span class="icon ion-edit fz-16"></span>
                                                </a>
                                                <a href="#" class="text-decoration-none text-danger" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                                    <span class="icon ion-trash-b fz-16"></span>
                                                </a>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-8"></div>
            </div>
        </div>
    </div>

    {{-- MODAL --}}
    <div class="modal fade" id="addNewUserModal" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="addNewUserModal" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addNewUserModal">Add New User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body pb-0">
                    <div class="row">
                        <div class="col-sm-6">
                            <h6>User Infomation</h6>
                            <div class="mb-3">
                                <label for="add-first_name" class="form-label">Name</label>
                                <input type="text" class="form-control form-control-sm" name="add-first_name" id="add-first_name">
                            </div>
                            <div class="mb-3">
                                <label for="add-phone" class="form-label">Phone</label>
                                <input type="number" class="form-control form-control-sm" name="add-phone" id="add-phone" placeholder="without zero">
                            </div>
                            <div class="mb-3">
                                <label for="add-email" class="form-label">Email</label>
                                <input type="mail" class="form-control form-control-sm" name="add-email" id="add-email">
                            </div>
                            <div class="mb-3">
                                <label for="add-fulladdress" class="form-label">Address</label>
                                <textarea name="add-fulladdress" id="add-fulladdress" class="form-control form-control-sm" rows="3"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="add-password" class="form-label">Password</label>
                                <input type="password" class="form-control form-control-sm" name="add-password" id="add-password">
                            </div>
                            <div class="mb-4">
                                <label for="add-conf_password" class="form-label">Password Confirmation</label>
                                <input type="password" class="form-control form-control-sm" name="add-conf_password" id="add-conf_password">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <h6>Company & Roles</h6>
                            <div class="mb-3">
                                <label for="add-clients" class="form-label">Company</label>
                                <select id="add-clients" name="add-clients" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    @foreach ($clients as $client)
                                        <option value="{{ $client->id }}">{{ $client->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="add-roles" class="form-label">Roles</label>
                                <select id="add-roles" name="add-roles" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    @foreach ($roles as $role)
                                        <option value="{{ $role->id }}">{{ $role->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            {{-- <div class="mb-3">
                                <label for="add-pernu_id" class="form-label">Menu Permission</label>
                                <select id="add-pernu_id" name="add-pernu_id" class="form-control" style="width:100%;">
                                    <option value="">Tidak Ada</option>
                                    @foreach ($pernus as $pernu)
                                        <option value="{{ $pernu->id }}">{{ $pernu->name }}</option>
                                    @endforeach
                                </select>
                            </div> --}}
                            {{-- <div id="add-group-chk_type" class="mb-3 d-none">
                                <label for="add-chk_type" class="form-label">Checker Type</label>
                                <select id="add-chk_type" name="add-chk_type" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    <option value="{{ \App\Models\Users::CHK_TYPE_PICKUP }}">Pickup</option>
                                    <option value="{{ \App\Models\Users::CHK_TYPE_DROP }}">Drop</option>
                                </select>
                            </div> --}}
                            {{-- <div id="add-otherInformationGroup" class="d-none">
                                <div class="mb-2">&nbsp;</div>
                                <h6>Informasi Lainnya</h6>
                                <div id="add-bankInformationGroup" class="d-none">
                                    <div class="mb-3">
                                        <label for="add-bank" class="form-label">Bank</label>
                                        <select id="add-bank" name="add-bank" class="form-control" style="width:100%;">
                                            <option value="" selected disabled>Choose</option>
                                            @foreach ($banks as $bank)
                                                <option value="{{ $bank->bank_code }}" data-id="{{ $bank->id }}" data-code="{{ $bank->bank_code }}" data-short="{{ $bank->bank_short_name }}" data-name="{{ $bank->bank_name }}">{{ $bank->bank_short_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="add-kcp" class="form-label">KCP</label>
                                        <input type="text" class="form-control form-control-sm" name="add-kcp" id="add-kcp" placeholder="KCP Rempoa">
                                    </div>
                                    <div class="mb-3">
                                        <label for="add-acc_number" class="form-label">Nomor Rekening</label>
                                        <input type="number" class="form-control form-control-sm" name="add-acc_number" id="add-acc_number">
                                    </div>
                                    <div class="mb-3">
                                        <label for="add-acc_name" class="form-label">Pemilik Rekening</label>
                                        <input type="text" class="form-control form-control-sm" name="add-acc_name" id="add-acc_name">
                                    </div>
                                </div>
                            </div> --}}
                            <div class="mb-2">&nbsp;</div>
                            <h6>Utilities</h6>
                            <div class="mb-3">
                                <label for="add-status" class="form-label">Status</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="add-status">
                                    <label class="form-check-label" for="add-status"><span class="text-dark" id="add-txtStatus">Inactive</span></label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="add-status-sms" class="form-label">SMS Notification</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="add-status-sms">
                                    <label class="form-check-label" for="add-status-sms"><span class="text-dark" id="add-txtStatusSms">Inactive</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="add-group_track_vhc" class="row">
                        <div class="col-sm-6">
                            <h6>Trackings</h6>
                            <div class="mb-3">
                                <label for="add-is_tracking" class="form-label">Is Tracking Vehicle ?</label>
                                <select id="add-is_tracking" name="add-is_tracking" class="form-control" style="width:100%;">
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_NO }}">No</option>
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_YES }}">Yes</option>
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_DEFAULT }}" selected>Default</option>
                                </select>
                            </div>
                            <div id="add-group_vehicles" class="mb-3">
                                <label for="add-vehicles" class="form-label">Vehicles you tracking</label>
                                <select id="add-vehicles" name="add-vehicles" class="form-control" style="width:100%;" multiple="multiple">
                                    @foreach ($vehicles as $k => $v)
                                        <option value="{{ $v->id }}">{{ $v->nopol1 . ' ' . $v->nopol2 . ' ' . $v->nopol3 }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" id="btnSubmitNewUser" class="btn btn-sm btn-danger">Submit data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="updtUserModal" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="updtUserModal" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="updtUserModal">Update User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body pb-0">
                    <div class="row">
                        <div class="col-sm-6">
                            <h6>User Infomation</h6>
                            <div class="mb-3">
                                <label for="updt-first_name" class="form-label">Name</label>
                                <input type="text" class="form-control form-control-sm" name="updt-first_name" id="updt-first_name">
                            </div>
                            <div class="mb-3">
                                <label for="updt-phone" class="form-label">Phone</label>
                                <input type="number" class="form-control form-control-sm" name="updt-phone" id="updt-phone" placeholder="without zero">
                            </div>
                            <div class="mb-3">
                                <label for="updt-email" class="form-label">Email</label>
                                <input type="mail" class="form-control form-control-sm" name="updt-email" id="updt-email">
                            </div>
                            <div class="mb-3">
                                <label for="updt-fulladdress" class="form-label">Address</label>
                                <textarea name="updt-fulladdress" id="updt-fulladdress" class="form-control form-control-sm" rows="3"></textarea>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <h6>Company & Roles</h6>
                            <div class="mb-3">
                                <label for="updt-clients" class="form-label">Company</label>
                                <select id="updt-clients" name="updt-clients" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    @foreach ($clients as $client)
                                        <option value="{{ $client->id }}">{{ $client->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="updt-roles" class="form-label">Roles</label>
                                <select id="updt-roles" name="updt-roles" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    @foreach ($roles as $role)
                                        <option value="{{ $role->id }}">{{ $role->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            {{-- <div class="mb-3">
                                <label for="updt-pernu_id" class="form-label">Menu Permission</label>
                                <select id="updt-pernu_id" name="updt-pernu_id" class="form-control" style="width:100%;">
                                    <option value="">Tidak Ada</option>
                                    @foreach ($pernus as $pernu)
                                        <option value="{{ $pernu->id }}">{{ $pernu->name }}</option>
                                    @endforeach
                                </select>
                            </div> --}}
                            {{-- <div id="updt-group-chk_type" class="mb-3 d-none">
                                <label for="updt-chk_type" class="form-label">Checker Type</label>
                                <select id="updt-chk_type" name="updt-chk_type" class="form-control" style="width:100%;">
                                    <option value="">Choose</option>
                                    <option value="{{ \App\Models\Users::CHK_TYPE_PICKUP }}">Pickup</option>
                                    <option value="{{ \App\Models\Users::CHK_TYPE_DROP }}">Drop</option>
                                </select>
                            </div> --}}
                            {{-- <div id="updt-otherInformationGroup" class="d-none">
                                <div class="mb-2">&nbsp;</div>
                                <h6>Informasi Lainnya</h6>
                                <div id="updt-bankInformationGroup" class="d-none">
                                    <div class="mb-3">
                                        <label for="updt-bank" class="form-label">Bank</label>
                                        <select id="updt-bank" name="updt-bank" class="form-control" style="width:100%;">
                                            <option value="" selected disabled>Choose</option>
                                            @foreach ($banks as $bank)
                                                <option value="{{ $bank->bank_code }}" data-id="{{ $bank->id }}" data-code="{{ $bank->bank_code }}" data-short="{{ $bank->bank_short_name }}" data-name="{{ $bank->bank_name }}">{{ $bank->bank_short_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="updt-kcp" class="form-label">KCP</label>
                                        <input type="text" class="form-control form-control-sm" name="updt-kcp" id="updt-kcp" placeholder="KCP Rempoa">
                                    </div>
                                    <div class="mb-3">
                                        <label for="updt-acc_number" class="form-label">Nomor Rekening</label>
                                        <input type="number" class="form-control form-control-sm" name="updt-acc_number" id="updt-acc_number">
                                    </div>
                                    <div class="mb-3">
                                        <label for="updt-acc_name" class="form-label">Pemilik Rekening</label>
                                        <input type="text" class="form-control form-control-sm" name="updt-acc_name" id="updt-acc_name">
                                    </div>
                                </div>
                            </div>
                            <div class="mb-2">&nbsp;</div> --}}
                        </div>
                    </div>
                    <div class="row">
                        <div id="updt-group_track_vhc" class="col-sm-6">
                            <h6>Trackings</h6>
                            <div class="mb-3">
                                <label for="updt-is_tracking" class="form-label">Is Tracking Vehicle ?</label>
                                <select id="updt-is_tracking" name="updt-is_tracking" class="form-control" style="width:100%;">
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_NO }}">No</option>
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_YES }}">Yes</option>
                                    <option value="{{ \App\Models\Users::IS_TRACK_VHC_DEFAULT }}">Default</option>
                                </select>
                            </div>
                            <div id="updt-group_vehicles" class="mb-3">
                                <label for="updt-vehicles" class="form-label">Vehicles you tracking</label>
                                <select id="updt-vehicles" name="updt-vehicles" class="form-control" style="width:100%;" multiple="multiple">
                                    @foreach ($vehicles as $k => $v)
                                        <option value="{{ $v->id }}">{{ $v->nopol1 . ' ' . $v->nopol2 . ' ' . $v->nopol3 }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <h6>Change Password</h6>
                            <div class="mb-3">
                                <label for="updt-is_change_pasw" class="form-label">Update Password ?</label>
                                <select id="updt-is_change_pasw" name="updt-is_change_pasw" class="form-control" style="width:100%;">
                                    <option value="no">No</option>
                                    <option value="yes">Yes</option>
                                </select>
                            </div>
                            <div class="form-row groupPassword d-none">
                                <div class="col">
                                    <div class="mb-3">
                                        <label for="updt-password" class="form-label">Password</label>
                                        <input type="password" class="form-control form-control-sm" name="updt-password" id="updt-password">
                                    </div>
                                </div>
                                <div class="col">
                                    <div class="mb-3">
                                        <label for="updt-conf_password" class="form-label">Password Confirmation</label>
                                        <input type="password" class="form-control form-control-sm" name="updt-conf_password" id="updt-conf_password">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-6">
                            <h6>Utilities</h6>
                            <div class="mb-3">
                                <label for="updt-status" class="form-label">Status</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="updt-status">
                                    <label class="form-check-label" for="updt-status"><span class="text-dark" id="updt-txtStatus">Inactive</span></label>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="updt-status-sms" class="form-label">SMS Notification</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="updt-status-sms">
                                    <label class="form-check-label" for="updt-status-sms"><span class="text-dark" id="updt-txtStatusSMS">Inactive</span></label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    @can('user.delete')
                        <button type="button" id="btnDelUser_updt" class="btn btn-sm btn-warning">Delete ?</button>
                    @endcan
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    @can('user.edit')
                        <button type="button" id="btnSubmitUpdtUser" class="btn btn-sm btn-danger">Update data</button>
                    @endcan
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="delUserModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="delUserModal" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="delUserModal">Delete User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <p class="mb-0">
                            Are you sure want to delete this user
                            <a href="#" class="text-danger">
                                <span id="del-first_name"></span>
                                (<span id="del-phone"></span>)
                            </a>
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitDelUser" type="button" class="btn btn-sm btn-secondary">Yes, delete</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlUserLogs" aria-labelledby="mdlUserLogsLabel" aria-hidden="true">
		<!-- ajax -->
    </div>

@endsection

@section('customjs')
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            user_status: {
                active: "{{ App\Models\Users::STATUS_ACTIVE }}",
                inactive: "{{ App\Models\Users::STATUS_NOT_ACTIVE }}",
            },
            user_roles: {
                checker: "{{ App\Models\Users::ROLE_CHECKER }}",
                vendor: "{{ App\Models\Users::ROLE_VENDOR }}",
            },
            is_tracking: {
                no: "{{ App\Models\Users::IS_TRACK_VHC_NO }}",
                yes: "{{ App\Models\Users::IS_TRACK_VHC_YES }}",
                default: "{{ App\Models\Users::IS_TRACK_VHC_DEFAULT }}",
            },
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                UNew.activate();
                UUpdate.activate();
                UDel.activate();
                Filter.activate();
            },
            event: function() {
                $('#add-status, #add-status-sms, #updt-status, #updt-status-sms').bind('change', function() {
					const labelSpan = $(this).closest('.form-check').find('span');
					labelSpan.html($(this).is(':checked') ? 'Active' : 'Inactive');
                    // if ($(this).is(':checked'))
                    //     $('#add-txtStatus').html('Active')
                    // else
                    //     $('#add-txtStatus').html('Inactive')
                });
                // $('#updt-status').bind('change', function() {
                //     if ($(this).is(':checked'))
                //         $('#updt-txtStatus').html('Active')
                //     else
                //         $('#updt-txtStatus').html('Inactive')
                // });
                // $('#add-roles').on('change', function() {
                //     let role = $('#add-roles').val();
                //     if (role == State.user_roles.checker) {
                //         $('#add-group-chk_type').removeClass('d-none');
                //         $('#add-group_track_vhc').addClass('d-none');

                //         $('#add-otherInformationGroup').addClass('d-none');
                //         $('#add-bankInformationGroup').addClass('d-none');
                //     } else if (role == State.user_roles.vendor) {
                //         $('#add-otherInformationGroup').removeClass('d-none');
                //         $('#add-bankInformationGroup').removeClass('d-none');

                //         $('#add-group-chk_type').addClass('d-none');
                //         $('#add-group_track_vhc').removeClass('d-none');
                //     } else {
                //         $('#add-group-chk_type').addClass('d-none');
                //         $('#add-group_track_vhc').removeClass('d-none');
                //         $('#add-otherInformationGroup').addClass('d-none');
                //         $('#add-bankInformationGroup').addClass('d-none');
                //     }
                // });
                $('#updt-roles').on('change', function() {
                    let role = $('#updt-roles').val();
                    if (role == State.user_roles.checker) {
                        $('#updt-group-chk_type').removeClass('d-none');
                        $('#updt-group_track_vhc').addClass('d-none');

                        $('#updt-otherInformationGroup').addClass('d-none');
                        $('#updt-bankInformationGroup').addClass('d-none');
                    } else if (role == State.user_roles.vendor) {
                        $('#updt-otherInformationGroup').removeClass('d-none');
                        $('#updt-bankInformationGroup').removeClass('d-none');

                        $('#updt-group-chk_type').addClass('d-none');
                        $('#updt-group_track_vhc').removeClass('d-none');
                    } else {
                        $('#updt-group-chk_type').addClass('d-none');
                        $('#updt-group_track_vhc').removeClass('d-none');
                        $('#updt-otherInformationGroup').addClass('d-none');
                        $('#updt-bankInformationGroup').addClass('d-none');
                    }
                });
                $('#updt-is_change_pasw').on('change', function() {
                    let val = $('#updt-is_change_pasw').val();
                    $('#updt-password').val('');
                    $('#updt-conf_password').val('');
                    if (val === 'yes') {
                        $('.groupPassword').removeClass('d-none');
                    } else {
                        $('.groupPassword').addClass('d-none');
                    }
                });

                $('#add-clients').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-roles').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-pernu_id').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-chk_type').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-is_tracking').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-vehicles').select2({
                    dropdownParent: $('#addNewUserModal'),
                });
                $('#add-bank').select2({
                    dropdownParent: $('#addNewUserModal'),
                });

                $('#updt-clients').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-roles').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-pernu_id').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-is_change_pasw').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-chk_type').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-is_tracking').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-vehicles').select2({
                    dropdownParent: $('#updtUserModal'),
                });
                $('#updt-bank').select2({
                    dropdownParent: $('#updtUserModal'),
                });

                $('#add-group_track_vhc').addClass('d-none');
                $('#add-group_vehicles').addClass('d-none');
                $('#updt-group_track_vhc').addClass('d-none');
                $('#updt-group_vehicles').addClass('d-none');
            },
        };

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tUsers').DataTable();
                // if (User.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { User.Table.firstInitDataTable = 1; }
                $('#tUsers').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_users') }}?cptid=" + AppState.current_company,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_users').text(count);
                            }
                            // removeTableSkeletonLoading()
                        },
                    },
                    deferRender: true,
                    columns: [{
                            data: 'DT_RowIndex',
                            className: 'text-end',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'action',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                // <a href="#" class="text-decoration-none me-1 btnViewUser" data-bs-toggle="tooltip"
                                // 	data-bs-placement="bottom" title="View">
                                // 	<span class="icon ion-eye fz-16"></span>
                                // </a>
                                let action = `
                                    <a href="#" class="text-decoration-none me-2 btnEdtUser" data-bs-toggle="tooltip"
                                        data-bs-placement="bottom" title="Edit">
                                        <span class="icon ion-eye fz-16"></span>
                                    </a>
									<a href="#" class="text-decoration-none me-2 btnLogUser" data-bs-toggle="tooltip" data-id="${row.id}"
										data-bs-placement="bottom" title="Logs">
										<span class="icon ion-android-laptop fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelUser"
                                //     data-bs-toggle="tooltip" data-bs-placement="bottom" title="Delete">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'first_name',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-id', rowData.id);
                                $(td).attr('data-name', rowData.name);
                                $(td).attr('data-phone', rowData.phone);
                                $(td).attr('data-phone_code', rowData.phone_code);
                                $(td).attr('data-client_group_name', rowData.client_group_name);
                            },
                        },
                        {
                            data: 'fulladdress',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'phone',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return (
                                    `<a href="tel:670${data}"><i class="text-dark ion-ios-telephone"></i> ${Helper.splitEvery4Char('670'+data)}</a>` +
                                    `<br>` +
                                    `<a href="https://api.whatsapp.com/send/?phone=670${data}&text=Halo&app_absent=0" target="_blank"><i class="text-success ion-social-whatsapp"></i> ${Helper.splitEvery4Char('670'+data)}</a>`
                                );
                            },
                        },
                        {
                            data: 'email',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'crt',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return moment.unix(data).format('DD MMM YYYY HH:mm')
                            },
                        },
						{
							data: 'lastLogin',
							className: 'text-start text-nowrap',
							visible: true,
							orderable: true,
							searchable: true,
							render: function(data, type, row, meta) {
								return data ? moment.unix(data).format('DD MMM YYYY HH:mm') : '-';
							},
						},
                        {
                            data: 'client_group_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'role_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return `<small class="text-muted">${data ?? '-'}</small>`;
                            },
                        },
                        {
                            data: 'status',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.user_status.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                }
                                return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                            },
                        },
                    ],
                });
            },
        };

        const UNew = {
            activate: function() {
                UNew.event();
            },
            event: function() {
                // modal
                $('#btnAddNewUserModal').on('click', function() {
                    $('#addNewUserModal').modal('show');
                });
                $('#addNewUserModal').on('shown.bs.modal', function() {
                    // initiate select2 if there
                });
                $('#btnSubmitNewUser').on('click', function() {
                    let data = UNew.getData();
                    if (data.password !== data.conf_password) {
                        Helper.toast('Warning', 'just now', 'password not same');
                        return false;
                    }
                    UNew.submitData(data);
                });
                $('#add-is_tracking').on('change', function() {
                    let is_tracking = $('#add-is_tracking').val();
                    if (is_tracking == State.is_tracking.yes) {
                        $('#add-group_vehicles').removeClass('d-none');
                    } else {
                        $('#add-group_vehicles').addClass('d-none');
                    }
                });
            },
            getData: function() {
                let data = {};
                data.first_name = $('#add-first_name').val();
                data.fulladdress = $('#add-fulladdress').val();
                data.phone = $('#add-phone').val();
                data.email = $('#add-email').val();

                data.password = $('#add-password').val();
                data.conf_password = $('#add-conf_password').val();

                data.clients = $('#add-clients').val();
                data.roles = $('#add-roles').val();
                data.pernu_id = $('#add-pernu_id').val();
                // data.chk_type = $('#add-chk_type').val();

                let selectedBank = $('#add-bank :selected');
                if (selectedBank && selectedBank.val() != '') {
                    data.bank_id = selectedBank.data('id');
                    data.bank_code = selectedBank.data('code');
                    data.bank_short = selectedBank.data('short');
                    data.bank_name = selectedBank.data('name');
                }
                data.bank_branch_name = $('#add-kcp').val();
                data.bank_acc_number = $('#add-acc_number').val();
                data.bank_acc_name = $('#add-acc_name').val();

                data.is_vdr_bcng = ($('#add_isVdrBcng').prop('checked')) ? 1 : 0;

                if ($('#add-status').prop('checked')) {
                    data.status = State.user_status.active;
                } else {
                    data.status = State.user_status.inactive;
                }

				data.status_sms = ($('#add-status-sms').prop('checked')) ? 1 : 0;

                data.is_tracking = $('#add-is_tracking').val();
                data.vehicles = $('#add-vehicles').val();
                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewUser').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewUser').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_user') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitNewUser').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success add new user');
                            $('#addNewUserModal').modal('hide');
                            DTable.reload();
                            UNew.clearInput();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewUser').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
            clearInput: function() {
                $('#add-chk_type').val('').trigger('change');
            },
        }

        const UUpdate = {
            activate: function() {
                UUpdate.event();
            },
            event: function() {
                // modal
                $('#tUsers').on('click', '.btnEdtUser', async function(e) {
                    let uid = $(e.target).closest('tr').find('td[data-id]').data('id');
                    UUpdate.clearInput();
                    let resp = await UUpdate.reqData({
                        uid
                    });
                    if (resp.type != 'success') {
                        Helper.toast('User Not Found', 'just now', 'please try again');
                        return false;
                    }
                    UUpdate.passDataToView(resp.data);
                });
                $('#tUsers').on('click', '.btnLogUser', async function(e) {
                    // let uid = $(e.target).closest('tr').find('td[data-id]').data('id');
                    // UUpdate.clearInput();
                    // let resp = await UUpdate.reqData({
                    //     uid
                    // });
                    // if (resp.type != 'success') {
                    //     Helper.toast('User Not Found', 'just now', 'please try again');
                    //     return false;
                    // }
                    // UUpdate.passDataToView(resp.data);

					e.preventDefault();
					const id = $(this).data('id');
					$('#mdlUserLogs').empty().load("{{ route('view_user_logs1') }}", `id=${id}`, () => {
						$('#mdlUserLogs').modal('show')
					})

                });
				
                $('#updtUserModal').on('shown.bs.modal', function() {
                    // initiate select2 if there
                });
                $('#btnSubmitUpdtUser').on('click', function() {
                    let data = UUpdate.getData();
                    if (typeof data.password != 'undefined') {
                        if (data.password !== data.conf_password) {
                            Helper.toast('Warning', 'just now', 'password not same');
                            return false;
                        }
                    }
                    UUpdate.submitData(data);
                });
                $('#updt-is_tracking').on('change', function() {
                    let is_tracking = $('#updt-is_tracking').val();
                    if (is_tracking == State.is_tracking.yes) {
                        $('#updt-group_vehicles').removeClass('d-none');
                    } else {
                        $('#updt-group_vehicles').addClass('d-none');
                    }
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_user', '') }}/" + params.uid,
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: params,
                        success: (data, textStatus, jqXHR) => {
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                data: data.data
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
            passDataToView: function(data) {
				console.log("data", data);
				
                $('#updt-first_name').val(data.first_name);
                $('#updt-fulladdress').val(data.fulladdress);
                $('#updt-phone').val(data.phone);
                $('#updt-email').val(data.email);

                $('#updt-clients').val(data.client_group_id).trigger('change');
                // $('#updt-roles').val(data.role).trigger('change');
                $('#updt-roles').val(data.role_id).trigger('change');
                $('#updt-pernu_id').val(data.pernu_id);
                $('#updt-is_change_pasw').val('no').trigger('change');

                // if (data.role == State.user_roles.checker) $('#updt-chk_type').val(data.chk_type).trigger('change');

                if (data.role == State.user_roles.vendor) {
                    $('#updt-bank').val(data.bank_code).trigger('change');
                    $('#updt-kcp').val(data.bank_branch_name);
                    $('#updt-acc_number').val(data.bank_acc_number);
                    $('#updt-acc_name').val(data.bank_acc_name);
                }

                if (data.is_vdr_bcng == 1) {
                    $('#updt_isVdrBcng').prop('checked', true);
                } else {
                    $('#updt_isVdrBcng').prop('checked', false);
                }

                if (data.status == State.user_status.active) {
                    $('#updt-status').prop('checked', true).trigger('change');
                } else {
                    $('#updt-status').prop('checked', false).trigger('change');
                }

                $('#updt-is_tracking').val(data.is_tracking).trigger('change');
                if (data.vhcs) {
                    $('#updt-vehicles').val(data.vhcs.split(',')).trigger('change');
                } else {
                    $('#updt-vehicles').val(null).trigger('change');
                }

                $('#updtUserModal').data('id', data.id);
                $('#updtUserModal').modal('show');

				$('#updt-status-sms').prop('checked', (data.status_sms == 1) ? true : false).trigger('change');
            },
            getData: function() {
                let data = {};
                data.uid = $('#updtUserModal').data('id');
                data.first_name = $('#updt-first_name').val();
                data.fulladdress = $('#updt-fulladdress').val();
                data.phone = $('#updt-phone').val();
                data.email = $('#updt-email').val();

                data.password = $('#updt-password').val();
                data.conf_password = $('#updt-conf_password').val();

                data.clients = $('#updt-clients').val();
                data.roles = $('#updt-roles').val();
                data.pernu_id = $('#updt-pernu_id').val();
                // data.chk_type = $('#updt-chk_type').val();

                let selectedBank = $('#updt-bank :selected');
                if (selectedBank && selectedBank.val() != '') {
                    data.bank_id = selectedBank.data('id');
                    data.bank_code = selectedBank.data('code');
                    data.bank_short = selectedBank.data('short');
                    data.bank_name = selectedBank.data('name');
                }
                data.bank_branch_name = $('#updt-kcp').val();
                data.bank_acc_number = $('#updt-acc_number').val();
                data.bank_acc_name = $('#updt-acc_name').val();

                data.is_vdr_bcng = $('#updt_isVdrBcng').val();

                data.is_vdr_bcng = ($('#updt_isVdrBcng').prop('checked')) ? 1 : 0;

                data.is_tracking = $('#updt-is_tracking').val();
                data.vehicles = $('#updt-vehicles').val();

				data.status_sms = ($('#updt-status-sms').prop('checked')) ? 1 : 0;

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitUpdtUser').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitUpdtUser').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_user', '') }}/" + data.uid,
                        method: 'PUT',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitUpdtUser').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success update user');
                            $('#updtUserModal').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitUpdtUser').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
            clearInput: function() {
                $('#updt-chk_type').val('').trigger('change');
            },
        }

        const UDel = {
            activate: function() {
                UDel.event();
            },
            event: function() {
                // on table
                $('#tUsers').on('click', '.btnDelUser', function(e) {
                    let row = $(e.target).closest('tr');
                    let uid = row.find('td[data-id]').data('id');
                    let fisrt_name = row.find('td[data-fisrt_name]').data('fisrt_name');
                    let phone = row.find('td[data-phone]').data('phone');
                    let phone_code = row.find('td[data-phone_code]').data('phone_code');
                    UDel.passDataToView({
                        uid,
                        fisrt_name,
                        phone,
                        phone_code,
                    });
                    $('#delUserModal').data('id', uid);
                    $('#delUserModal').modal('show');
                });
                $('#btnSubmitDelUser').on('click', function() {
                    let data = {
                        uid: $('#delUserModal').data('id'),
                    };
                    UDel.submitData(data);
                });
                // on modal update
                $('#btnDelUser_updt').on('click', function(e) {
                    let data = UUpdate.getData();
                    UDel.passDataToView({
                        uid: data.uid,
                        fisrt_name: data.first_name,
                        phone: data.phone,
                        phone_code: 62,
                    });
                    $('#delUserModal').data('id', data.uid);
                    $('#delUserModal').modal('show');
                });
            },
            passDataToView: function(data) {
                data.phone = '' + data.phone
                $('#del-fisrt_name').text(data.fisrt_name);
                $('#del-phone').text(`+${data.phone_code} ${Helper.splitEvery4Char(data.phone)}`);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelUser').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelUser').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_user', '') }}/" + data.uid,
                        method: 'DELETE',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                            'x-api-key': Helper.getCookie('_trtk'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitDelUser').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success delete user');
                            $('#delUserModal').modal('hide');
                            $('#updtUserModal').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelUser').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
        }

        const Filter = {
            activate: function() {
                Filter.event();
            },
            event: function() {},
            triggerFilterCompany: function() {
                DTable.reload();
            },
        }

        Wrapper.activate();
    </script>
@endsection
