@extends('app.app')

@section('title')
    Tipe Logbook
@endsection

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

    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="card">
                <div class="card-header">
                    <div class="row d-flex align-items-center">
                        <div class="col-3">
                            <p class="card-title text-bold mb-0">Logbook Type (<span id="count_lgb_types">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewLgbType" class="btn btn-sm btn-danger">Tambah Logbook Type</button>
                        </div>
                        <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="tLgbTypes" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Type</th>
                                    <th class="text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNewLgbType"
        aria-labelledby="mdlNewLgbTypeLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlNewLgbTypeLabel">Tambah Tipe Logbook</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formAdd">
                        <div class="mb-3">
                            {{-- <div class="border-bottom">
                                <h6>Logbbok Type</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <label for="add_name" class="col-form-label">Type<span class="text-danger">*</span></label>
                                    <input type="text" name="add_name" id="add_name" class="form-control" placeholder="BBM">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-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" name="add_status">
                                        <label class="form-check-label" for="add_status"><span class="text-dark" id="add-txtStatus">Inactive</span></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitNewLgbType" type="button" class="btn btn-sm btn-danger">Submit data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlEdtLgbType"
        aria-labelledby="mdlEdtLgbTypeLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlEdtLgbTypeLabel">Edit Logbook Type</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formUpdt">
                        <div class="mb-3">
                            {{-- <div class="border-bottom">
                                <h6>Uang Saku</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <label for="updt_name" class="col-form-label">Type<span class="text-danger">*</span></label>
                                    <input type="text" name="updt_name" id="updt_name" class="form-control" placeholder="FREE_E-TOL02">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-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>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnDelLgbType_updt" class="btn btn-sm btn-warning">Delete ?</button>
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitEdtLgbType" type="button" class="btn btn-sm btn-danger">Update data</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelLgbType"
        aria-labelledby="mdlDelLgbTypeLabel" 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="mdlDelLgbTypeLabel">Delete Logbook Type</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 logbook type
                            <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="btnSubmitDelLgbType" type="button" class="btn btn-sm btn-secondary">Yes, delete</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            is_active: {
                active: "{{ App\Models\LogbookTypes::IS_ACTIVE }}",
                inactive: "{{ App\Models\LogbookTypes::IS_INACTIVE }}",
            },
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                PNew.activate();
                PUpdt.activate();
                PDel.activate();
            },
            event: function() {
                $('#add_status').bind('change', function() {
                    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')
                });
            },
        };

        const Req = {
            list_client_zone: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_list_client_zones') }}",
                        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: (resp, textStatus, jqXHR) => {
                            if (cb) cb(resp);
                            if (resp.meta.type != 'success') {
                                resolve({
                                    type: 'fail',
                                    msg: resp.meta.message,
                                });
                                if (isAlert) Helper.toast('Warning', 'just now', resp.meta
                                    .message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: resp,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (cb) cb(jqXHR.responseJSON);
                            if (jqXHR.status >= 500) {
                                if (isAlert) Helper.toast('Error', 'just now',
                                    'please try again');
                            } else {
                                if (isAlert) Helper.toast('Error', 'just now', jqXHR
                                    .responseJSON.meta.message);
                            }
                            resolve({
                                type: 'error',
                                msg: jqXHR.responseJSON.meta.message,
                            });
                        }
                    })
                })
            },
            list_checkpoints: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_list_checkpoints') }}",
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (resp, textStatus, jqXHR) => {
                            if (cb) cb(resp);
                            if (resp.meta.type != 'success') {
                                resolve({
                                    type: 'fail',
                                    msg: resp.meta.message,
                                });
                                if (isAlert) Helper.toast('Warning', 'just now', resp.meta
                                    .message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: resp,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            if (cb) cb(jqXHR.responseJSON);
                            if (jqXHR.status >= 500) {
                                if (isAlert) Helper.toast('Error', 'just now',
                                    'please try again');
                            } else {
                                if (isAlert) Helper.toast('Error', 'just now', jqXHR
                                    .responseJSON.meta.message);
                            }
                            resolve({
                                type: 'error',
                                msg: jqXHR.responseJSON.meta.message,
                            });
                        }
                    })
                })
            },
        }

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tLgbTypes').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tLgbTypes').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_lgb_types') }}?cptid="+AppState.current_company,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_lgb_types').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,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-id', rowData.id);
                                // $(td).attr('data-code', rowData.code);
                                $(td).attr('data-name', rowData.name);
                            },
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnUpdtLgbType">
										<span class="icon ion-edit fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelLgbType">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        // {
                        //     data: 'code',
                        //     className: 'text-end text-nowrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        // },
                        {
                            data: 'name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data;
                            }
                        },
                        {
                            data: 'is_active',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.is_active.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                } else {
                                    return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                                }
                            }
                        },
                    ],
                });
            },
        };

        const PNew = {
            activate: function() {
                PNew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewLgbType').on('click', function() {
                    $('#mdlNewLgbType').modal('show');
                });
                $('#mdlNewLgbType').on('shown.bs.modal', function() {
                    
                });
                // input
                $('#add_name').on('keyup', function() {
                    let val = $('#add_name').val();
                    let regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Tidak boleh mengandung symbol');
                        return false;
                    }
                });
                // button
                $('#btnSubmitNewLgbType').on('click', function() {
                    let data = PNew.getData();
                    let isValid = PNew.checkData(data, true);
                    if (!isValid) return false;
                    PNew.submitData(data);
                });
            },
            getData: function() {
                let data = Helper.objectifyForm($('#formAdd').serializeArray());

                data.add_name = data.add_name.split(' ').join('_').toLowerCase();

                if ($('#add_status').prop('checked')) {
                    data.status = State.is_active.active;
                } else {
                    data.status = State.is_active.inactive;
                }

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (typeof data.add_name === 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Type wajib diisi');
                    return false;
                }

                let regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                if (regex.test(data.add_name)) {
                    Helper.toast('Warning', 'just now', 'Tidak boleh mengandung symbol');
                    return false;
                }

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewLgbType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewLgbType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_lgb_type') }}",
                        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) => {
                            $('#btnSubmitNewLgbType').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 menambahkan uang saku');
                            $('#mdlNewLgbType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewLgbType').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 PUpdt = {
            activate: function() {
                PUpdt.event();
            },
            event: function() {
                // modal
                $('#tLgbTypes').on('click', '.btnUpdtLgbType', async function(e) {
                    let id = $(e.target).closest('tr').find('td[data-id]').data('id');
                    let resp = await PUpdt.reqData({
                        lgb_type_id: id,
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Logbook Type Not Found', 'just now', 'please try again');
                        return false;
                    }
                    PUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtLgbType').on('shown.bs.modal', function() {
                    
                });
                // input
                $('#updt_name').on('keyup', function() {
                    let val = $('#updt_name').val();
                    let regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Tidak boleh mengandung symbol');
                        return false;
                    }
                });
                // button
                $('#btnSubmitEdtLgbType').on('click', function() {
                    let data = PUpdt.getData();
                    let isValid = PUpdt.checkData(data, true);
                    if (!isValid) return false;
                    PUpdt.submitData(data);
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_lgb_type', '') }}/" + params.lgb_type_id,
                        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: async function(data) {
                $('#updt_name').val(data.name);

                if (data.is_active == State.is_active.active) {
                    $('#updt_status').prop('checked', true);
                } else {
                    $('#updt_status').prop('checked', false);
                }

                $('#mdlEdtLgbType').data('id', data.id);
                $('#mdlEdtLgbType').modal('show');
            },
            getData: function() {
                let data = Helper.objectifyForm($('#formUpdt').serializeArray());
                
                data.updt_name = data.updt_name.split(' ').join('_').toLowerCase();

                if ($('#updt_status').prop('checked')) {
                    data.status = State.is_active.active;
                } else {
                    data.status = State.is_active.inactive;
                }

                data.lgb_type_id = $('#mdlEdtLgbType').data('id');

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (typeof data.updt_name === 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Nama wajib diisi');
                    return false;
                }

                let regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                if (regex.test(data.updt_name)) {
                    Helper.toast('Warning', 'just now', 'Tidak boleh mengandung symbol');
                    return false;
                }

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtLgbType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtLgbType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_lgb_type', '') }}/" + data.lgb_type_id,
                        method: 'PUT',
                        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) => {
                            $('#btnSubmitEdtLgbType').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 pocket');
                            $('#mdlEdtLgbType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtLgbType').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 PDel = {
            activate: function() {
                PDel.event();
            },
            event: function() {
                // on table
                $('#tLgbTypes').on('click', '.btnDelLgbType', function(e) {
                    let row = $(e.target).closest('tr');
                    let id = row.find('td[data-id]').data('id');
                    let name = row.find('td[data-name]').data('name');
                    PDel.passDataToView({
                        lgb_type_id: id,
                        name,
                    });
                    $('#mdlDelLgbType').data('id', id);
                    $('#mdlDelLgbType').modal('show');
                });
                $('#btnSubmitDelLgbType').on('click', function() {
                    let data = {
                        lgb_type_id: $('#mdlDelLgbType').data('id'),
                    };
                    PDel.submitData(data);
                });
                // on modal update
                $('#btnDelLgbType_updt').on('click', function (e) {
                    let data = PUpdt.getData();
                    PDel.passDataToView({
                        lgb_type_id: data.lgb_type_id,
                        // code: '',
                    });
                    $('#mdlDelLgbType').data('id', data.lgb_type_id);
                    $('#mdlDelLgbType').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del_name').text(data.name);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelLgbType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelLgbType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_lgb_type', '') }}/" + data.lgb_type_id,
                        method: 'DELETE',
                        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) => {
                            $('#btnSubmitDelLgbType').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 logbook type');
                            $('#mdlDelLgbType').modal('hide');
                            $('#mdlEdtLgbType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelLgbType').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'
                            });
                        }
                    })
                })
            },
        }

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