@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">Roles (<span id="count_users">0</span>)</p>
                                </div>
                                @can('role.create')
                                    <div class="col text-end">
                                        <a href="#" class="btn btn-sm btn-danger" id="btnAddNewUserModal">Add New Role</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 col-8">Name</th>
                                            <th class="text-nowrap col-2">Created At</th>
                                            <th class="text-nowrap col-2">Updated At</th>
                                        </tr>
                                    </thead>
                                </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 Role</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">
                        <h6>Role 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-name" id="add-name">
                        </div>
                    </div>
                    <div>
                        <h6>Permissions</h6>
                        @foreach ($permission as $module => $perms)
                            <div class="mb-3 row">
                                <label for="add-first_name" class="form-label text-capitalize col-3">
                                    {{ 
										$module == 'transaction' ? 'job' : 
											($module == 'client' ? 'company' : 
											($module == 'config_truck_type' ? 'Config Vehicle Type' : 
											($module == 'config_master_device' ? 'Config Master Devices' : 
											($module == 'config_logs_gps' ? 'Config Logs GPS' :
											($module == 'config_distribution_category' ? 'Config Distribution Category' :
											($module == 'config_pool' ? 'Config Pool' :
											($module == 'report_vehicle_trip' ? 'Report Vehicle Trip' :
											($module == 'report_abnormality' ? 'Report Abnormality' :
											($module == 'user_logs' ? 'Config User Activity' : $module
											)))))))))
									}}
                                </label>
                                <div class="col-9">
                                    <div class="d-flex flex-wrap align-items-center gap-2">
                                        @foreach ($perms as $perm)
                                            @php
                                                $id = 'perm-' . str_replace('.', '-', $perm->name);
                                            @endphp
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="checkbox" name="add-permissions[]" value="{{ $perm->id }}" id="{{ $id }}">
                                                <label class="form-check-label ms-1" for="{{ $id }}">{{ Str::after($perm->name, '.') }}</label>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>

                            </div>
                        @endforeach
                    </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 Role</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">
                        <h6>Role 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="updt-name" id="updt-name">
                        </div>
                    </div>
                    <div>
                        <h6>Permissions</h6>
                        @foreach ($permission as $module => $perms)
                            <div class="mb-3 row">
                                <label for="add-first_name" class="form-label text-capitalize col-3">
                                    {{ 
										$module == 'transaction' ? 'job' : 
											($module == 'client' ? 'company' : 
											($module == 'config_truck_type' ? 'Config Vehicle Type' : 
											($module == 'config_master_device' ? 'Config Master Devices' : 
											($module == 'config_logs_gps' ? 'Config Logs GPS' :
											($module == 'config_distribution_category' ? 'Config Distribution Category' :
											($module == 'config_pool' ? 'Config Pool' :
											($module == 'report_vehicle_trip' ? 'Report Vehicle Trip' :
											($module == 'report_abnormality' ? 'Report Abnormality' :
											($module == 'user_logs' ? 'Config User Activity' : $module
											)))))))))
									}}
                                </label>
                                <div class="col-9">
                                    <div class="d-flex flex-wrap align-items-center gap-2">
                                        @foreach ($perms as $perm)
                                            @php
                                                $id = 'perm-' . str_replace('.', '-', $perm->name);
                                            @endphp
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="checkbox" name="updt-permissions[]" value="{{ $perm->id }}" id="{{ $id }}">
                                                <label class="form-check-label ms-1" for="{{ $id }}">{{ Str::after($perm->name, '.') }}</label>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>

                            </div>
                        @endforeach
                    </div>
                </div>
                <div class="modal-footer">
                    @can('role.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('role.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 Role</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 role
                            <a href="#" class="text-danger">
                                <span id="del-name"></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>
@endsection

@section('customjs')
    <script>
        'use strict';

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                UNew.activate();
                UUpdate.activate();
                UDel.activate();
                Filter.activate();
            },
            event: function() {},
        };

        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_roles') }}?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) {
                                let action = `
                                    <a href="#" class="text-decoration-none me-1 btnEdtUser" data-bs-toggle="tooltip"
                                        data-bs-placement="bottom" title="Edit">
                                        <span class="icon ion-eye fz-16"></span>
                                    </a>
								`;
                                return action;
                            }
                        },
                        {
                            data: '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);
                            },
                        },
                        {
                            data: 'created_at',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return moment(data, 'YYYY-MM-DD HH:mm:ss').format('DD MMM YYYY HH:mm')
                            },
                        },
                        {
                            data: 'updated_at',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return moment(data, 'YYYY-MM-DD HH:mm:ss').format('DD MMM YYYY HH:mm')
                            },
                        },
                    ],
                });
            },
        };

        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();
                    UNew.submitData(data);
                });
            },
            getData: function() {
                let data = {};
                data.name = $('input[name=add-name]').val();
                data.permissions = $('input[name="add-permissions[]"]:checked')
                    .map(function() {
                        return $(this).val();
                    })
                    .get();
                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_role') }}",
                        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 role');
                            $('#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('Role Not Found', 'just now', 'please try again');
                        return false;
                    }
                    UUpdate.passDataToView(resp.data);
                });
                $('#updtUserModal').on('shown.bs.modal', function() {
                    // initiate select2 if there
                });
                $('#btnSubmitUpdtUser').on('click', function() {
                    let data = UUpdate.getData();
                    UUpdate.submitData(data);
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_role', '') }}/" + 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) {
                $('input[name=updt-name').val(data.name);
                $('input[name="updt-permissions[]"]').each(function() {
                    $(this).prop('checked', false);
                    let val = parseInt($(this).val());
                    if (data.permissions.includes(val)) {
                        $(this).prop('checked', true);
                    }
                });

                $('#updtUserModal').data('id', data.id);
                $('#updtUserModal').modal('show');
            },
            getData: function() {
                let data = {};
                data.uid = $('#updtUserModal').data('id')
                data.name = $('input[name=updt-name]').val();
                data.permissions = $('input[name="updt-permissions[]"]:checked')
                    .map(function() {
                        return $(this).val();
                    })
                    .get();
                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_role', '') }}/" + 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 role');
                            $('#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 name = row.find('td[data-name]').data('name');
                    UDel.passDataToView({
                        uid,
                    });
                    $('#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,
                        name: data.name,
                    });
                    $('#delUserModal').data('id', data.uid);
                    $('#delUserModal').modal('show');
                });
            },
            passDataToView: function(data) {
                data.phone = '' + data.phone
                $('#del-name').text(data.fisrt_name);
            },
            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_role', '') }}/" + 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 role');
                            $('#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
