@extends('app.app')

@section('title')
    Logbook Master
@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 Master (<span id="count_lgb_keys">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewLgbKey" class="btn btn-sm btn-danger">Tambah Logbook Master</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="tLgbKeys" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Name</th>
                                    <th class="">Inputs</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="mdlNewLgbKey"
        aria-labelledby="mdlNewLgbKeyLabel" 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="mdlNewLgbKeyLabel">Tambah Master 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-4">
                            {{-- <div class="border-bottom">
                                <h6>Logbbok Key</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <label for="add_name" class="col-form-label">Nama Logbook<span class="text-danger">*</span></label>
                                    <input type="text" name="add_name" id="add_name" class="form-control" placeholder="Solar">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <label for="add_type" class="col-form-label">Tipe Logbook<span class="text-danger">*</span></label>
                                    <select name="add_type" id="add_type" class="form-control" style="width:100%;">
                                        {{-- <option value="">Pilih Type</option> --}}
                                        @foreach ($types as $type)
                                            <option value="{{ $type->id }}">{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Keys --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <div class="row">
                                    <div class="col-sm-6 col-md-5">
                                        <h6>Input</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <h6>Satuan</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <h6>Tipe Inputan</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-1 text-start">
                                        <button id="point-add-row" type="button" class="btn btn-sm btn-danger">
                                            <span class="ion-plus"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div id="divAddCheckpoint">
                                <div id="divRowAddCheckpoint${nextIdx}" class="row divRowAddCheckpoint" data-idx="${nextIdx}">
                                    <div class="col-sm-6 col-md-5">
                                        <label for="add_keys[]" class="form-label">Nama Inputan<span class="text-danger">*</span></label>
                                        <input type="text" name="add_keys[]" class="form-control" placeholder="Harga">
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <label for="add_units[]" class="form-label">Satuan<span class="text-danger">*</span></label>
                                        <input type="text" name="add_units[]" class="form-control" placeholder="Rp">
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <label for="add_dtypes[]" class="form-label">Tipe Inputan<span class="text-danger">*</span></label>
                                        <select name="add_dtypes[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                            ${dtypes}
                                        </select>
                                    </div>
                                    <div class="col-sm-6 col-md-1 text-center d-flex align-items-center">
                                        <button type="button" class="btn btn-sm btn-secondary point-minus">
                                            <span class="ion-minus"></span>
                                        </button>
                                    </div>
                                </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="btnSubmitNewLgbKey" 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="mdlEdtLgbKey"
        aria-labelledby="mdlEdtLgbKeyLabel" 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="mdlEdtLgbKeyLabel">Edit Logbook Master</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-4">
                            {{-- <div class="border-bottom">
                                <h6>Logbbok Key</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <label for="updt_name" class="col-form-label">Nama Logbook<span class="text-danger">*</span></label>
                                    <input type="text" name="updt_name" id="updt_name" class="form-control" placeholder="Solar">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <label for="updt_type" class="col-form-label">Tipe Logbook<span class="text-danger">*</span></label>
                                    <select name="updt_type" id="updt_type" class="form-control" style="width:100%;">
                                        {{-- <option value="">Pilih Type</option> --}}
                                        @foreach ($types as $type)
                                            <option value="{{ $type->id }}">{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        {{-- Keys --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <div class="row">
                                    <div class="col-sm-6 col-md-5">
                                        <h6>Input</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <h6>Satuan</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <h6>Tipe Inputan</h6>
                                    </div>
                                    <div class="col-sm-6 col-md-1 text-start">
                                        <button id="point-updt-row" type="button" class="btn btn-sm btn-danger">
                                            <span class="ion-plus"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div id="divUpdtCheckpoint">
                                <div id="divRowUpdtCheckpoint${nextIdx}" class="row divRowUpdtCheckpoint" data-idx="${nextIdx}">
                                    <div class="col-sm-6 col-md-5">
                                        <label for="updt_keys[]" class="form-label">Nama Inputan<span class="text-danger">*</span></label>
                                        <input type="text" name="updt_keys[]" class="form-control" placeholder="Harga">
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <label for="updt_units[]" class="form-label">Satuan<span class="text-danger">*</span></label>
                                        <input type="text" name="updt_units[]" class="form-control" placeholder="Rp">
                                    </div>
                                    <div class="col-sm-6 col-md-3">
                                        <label for="updt_dtypes[]" class="form-label">Tipe Inputan<span class="text-danger">*</span></label>
                                        <select name="updt_dtypes[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                            ${dtypes}
                                        </select>
                                    </div>
                                    <div class="col-sm-6 col-md-1 text-center d-flex align-items-center">
                                        <button type="button" class="btn btn-sm btn-secondary updt-point-minus">
                                            <span class="ion-minus"></span>
                                        </button>
                                    </div>
                                </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" name="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="btnDelLgbKey_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="btnSubmitEdtLgbKey" 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="mdlDelLgbKey"
        aria-labelledby="mdlDelLgbKeyLabel" 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="mdlDelLgbKeyLabel">Delete Logbook Master</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 master
                            <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="btnSubmitDelLgbKey" 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\LogbookKeys::IS_ACTIVE }}",
                inactive: "{{ App\Models\LogbookKeys::IS_INACTIVE }}",
            },
            ls_dtypes: [],
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                PNew.activate();
                PNewInput.activate();
                PUpdt.activate();
                PUpdtInput.activate();
                PDel.activate();
            },
            event: async 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')
                });

                $('#add_type').select2({
                    dropdownParent: $('#mdlNewLgbKey'),
                });

                $('#updt_type').select2({
                    dropdownParent: $('#mdlEdtLgbKey'),
                });

                const dtypes = await Req.list_dtypes({}, false, null);
                if (dtypes.type === 'success') {
                    State.ls_dtypes = dtypes.resp.data;

                    // trigger
                    PNewInput.removeAll();
                    PNewInput.add();
                    PUpdtInput.removeAll();
                    PUpdtInput.add();
                }
            },
        };

        const Req = {
            list_dtypes: function(data, isAlert = false, cb = null) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_list_dtypes') }}?is_active="+State.is_active.active,
                        method: 'GET',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        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() {
                // $('#tLgbKeys').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tLgbKeys').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_lgb_keys') }}?cptid="+AppState.current_company,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_lgb_keys').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, key, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnUpdtLgbKey">
										<span class="icon ion-edit fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelLgbKey">
                                //     <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, key, row, meta) {
                                return data;
                            }
                        },
                        {
                            data: 'keys',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, key, row, meta) {
                                return data;
                            }
                        },
                        {
                            data: 'is_active',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, key, 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
                $('#btnMdlNewLgbKey').on('click', function() {
                    $('#mdlNewLgbKey').modal('show');
                });
                $('#mdlNewLgbKey').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
                $('#btnSubmitNewLgbKey').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();

                for (let iKey in data.add_keys) {
                    data.add_keys[iKey] = data.add_keys[iKey].split(' ').join('_').toLowerCase();
                }

                for (let iKey in data.add_units) {
                    data.add_units[iKey] = data.add_units[iKey].split(' ').join('_');
                }

                for (let iKey in data.add_dtypes) {
                    data.add_dtypes[iKey] = data.add_dtypes[iKey].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' || data.add_name === '') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Nama wajib diisi');
                    return false;
                }

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

                for (let val of data.add_keys) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Nama inputan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Nama inputan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                for (let val of data.add_units) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Satuan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Satuan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                for (let val of data.add_dtypes) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Tipe inputan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Tipe inputan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewLgbKey').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewLgbKey').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_lgb_key') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitNewLgbKey').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 logbook');
                            $('#mdlNewLgbKey').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewLgbKey').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 PNewInput = {
            activate: async function() {
                PNewInput.event();
            },
            event: function () {
                // crud checkpoint
                $('#divAddCheckpoint').on('click', '.point-minus', function(e) {
                    let trgt = $(e.target);
                    if ($('.point-minus').length <= 1) {
                        Helper.toast('Warning', 'just now', 'minimal terdapat 1 inputan');
                        return false;
                    }
                    trgt.closest('.divRowAddCheckpoint').remove();
                });
                $('#point-add-row').on('click', function() {
                    PNewInput.add();
                });
            },
            reTriggerSel2: function () {
                $('select[name="add_dtypes[]"]').select2({
                    dropdownParent: $('#mdlNewLgbKey'),
                });
            },
            add: function () {
                let dtypes = '';

                for (let dtype of State.ls_dtypes) {
                    dtypes += `<option value="${dtype.val}">${dtype.name}</option>`;
                }

                // start from 0
                let nextIdx = $('.point-minus').length;

                let template = `
                <div id="divRowAddCheckpoint${nextIdx}" class="row divRowAddCheckpoint" data-idx="${nextIdx}">
                    <div class="col-sm-6 col-md-5">
                        <label for="add_keys[]" class="form-label">Nama Inputan<span class="text-danger">*</span></label>
                        <input type="text" name="add_keys[]" class="form-control" placeholder="Harga">
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <label for="add_units[]" class="form-label">Satuan<span class="text-danger">*</span></label>
                        <input type="text" name="add_units[]" class="form-control" placeholder="Rp">
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <label for="add_dtypes[]" class="form-label">Tipe Inputan<span class="text-danger">*</span></label>
                        <select name="add_dtypes[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                            ${dtypes}
                        </select>
                    </div>
                    <div class="col-sm-6 col-md-1 text-center d-flex align-items-center">
                        <button type="button" class="btn btn-sm btn-secondary point-minus">
                            <span class="ion-minus"></span>
                        </button>
                    </div>
                </div>
                `;
                $('#divAddCheckpoint').append(template);

                PNewInput.reTriggerSel2();
            },
            removeAll: function () {
                $('#divAddCheckpoint').html('');
            },
        }

        const PUpdt = {
            activate: function() {
                PUpdt.event();
            },
            event: function() {
                // modal
                $('#tLgbKeys').on('click', '.btnUpdtLgbKey', async function(e) {
                    let id = $(e.target).closest('tr').find('td[data-id]').data('id');
                    let resp = await PUpdt.reqData({
                        lgb_key_id: id,
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Logbook Key Not Found', 'just now', 'please try again');
                        return false;
                    }
                    PUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtLgbKey').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
                $('#btnSubmitEdtLgbKey').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_key', '') }}/" + params.lgb_key_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);
                $('#updt_type').val(data.type).trigger('change');

                PUpdtInput.removeAll();
                data.keys = JSON.parse(data.keys);
                data.units = JSON.parse(data.units);
                data.dtypes = JSON.parse(data.dtypes);

                for (let i in data.keys) {
                    PUpdtInput.add();
                    $($('input[name="updt_keys[]"]')[i]).val(data.keys[i]);
                    $($('input[name="updt_units[]"]')[i]).val(data.units[i]);
                    $($('select[name="updt_dtypes[]"]')[i]).val(data.dtypes[i]).trigger('change');
                }
                PUpdtInput.reTriggerSel2();

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

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

                for (let iKey in data.updt_keys) {
                    data.updt_keys[iKey] = data.updt_keys[iKey].split(' ').join('_').toLowerCase();
                }

                for (let iKey in data.updt_units) {
                    data.updt_units[iKey] = data.updt_units[iKey].split(' ').join('_');
                }

                for (let iKey in data.updt_dtypes) {
                    data.updt_dtypes[iKey] = data.updt_dtypes[iKey].split(' ').join('_').toLowerCase();
                }

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

                data.lgb_key_id = $('#mdlEdtLgbKey').data('id');

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (typeof data.updt_name === 'undefined' || data.updt_name === '') {
                    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;
                }

                for (let val of data.updt_keys) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Nama inputan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Nama inputan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                for (let val of data.updt_units) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Satuan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Satuan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                for (let val of data.updt_dtypes) {
                    if (val === '') {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Tipe inputan wajib diisi');
                        return false;
                    }
                    regex = /[!@#\$%\^\&*\)\(+=.-]/g;
                    if (regex.test(val)) {
                        Helper.toast('Warning', 'just now', 'Tipe inputan tidak boleh mengandung symbol');
                        return false;
                    }
                }

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtLgbKey').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtLgbKey').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_lgb_key', '') }}/" + data.lgb_key_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) => {
                            $('#btnSubmitEdtLgbKey').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 logbook');
                            $('#mdlEdtLgbKey').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtLgbKey').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 PUpdtInput = {
            activate: async function() {
                PUpdtInput.event();
            },
            event: function () {
                // crud checkpoint
                $('#divUpdtCheckpoint').on('click', '.updt-point-minus', function(e) {
                    let trgt = $(e.target);
                    if ($('.updt-point-minus').length <= 1) {
                        Helper.toast('Warning', 'just now', 'minimal terdapat 1 inputan');
                        return false;
                    }
                    trgt.closest('.divRowUpdtCheckpoint').remove();
                });
                $('#point-updt-row').on('click', function() {
                    PUpdtInput.add();
                });
            },
            reTriggerSel2: function () {
                $('select[name="updt_dtypes[]"]').select2({
                    dropdownParent: $('#mdlEdtLgbKey'),
                });
            },
            add: function () {
                let dtypes = '';

                for (let dtype of State.ls_dtypes) {
                    dtypes += `<option value="${dtype.val}">${dtype.name}</option>`;
                }

                // start from 0
                let nextIdx = $('.updt-point-minus').length;

                let template = `
                <div id="divRowUpdtCheckpoint${nextIdx}" class="row divRowUpdtCheckpoint" data-idx="${nextIdx}">
                    <div class="col-sm-6 col-md-5">
                        <label for="updt_keys[]" class="form-label">Nama Inputan<span class="text-danger">*</span></label>
                        <input type="text" name="updt_keys[]" class="form-control" placeholder="Harga">
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <label for="updt_units[]" class="form-label">Satuan<span class="text-danger">*</span></label>
                        <input type="text" name="updt_units[]" class="form-control" placeholder="Rp">
                    </div>
                    <div class="col-sm-6 col-md-3">
                        <label for="updt_dtypes[]" class="form-label">Tipe Inputan<span class="text-danger">*</span></label>
                        <select name="updt_dtypes[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                            ${dtypes}
                        </select>
                    </div>
                    <div class="col-sm-6 col-md-1 text-center d-flex align-items-center">
                        <button type="button" class="btn btn-sm btn-secondary updt-point-minus">
                            <span class="ion-minus"></span>
                        </button>
                    </div>
                </div>
                `;
                $('#divUpdtCheckpoint').append(template);

                PUpdtInput.reTriggerSel2();
            },
            removeAll: function () {
                $('#divUpdtCheckpoint').html('');
            },
        }

        const PDel = {
            activate: function() {
                PDel.event();
            },
            event: function() {
                // on table
                $('#tLgbKeys').on('click', '.btnDelLgbKey', 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_key_id: id,
                        name,
                    });
                    $('#mdlDelLgbKey').data('id', id);
                    $('#mdlDelLgbKey').modal('show');
                });
                $('#btnSubmitDelLgbKey').on('click', function() {
                    let data = {
                        lgb_key_id: $('#mdlDelLgbKey').data('id'),
                    };
                    PDel.submitData(data);
                });
                // on modal update
                $('#btnDelLgbKey_updt').on('click', function (e) {
                    let data = PUpdt.getData();
                    PDel.passDataToView({
                        lgb_key_id: data.lgb_key_id,
                        // code: '',
                    });
                    $('#mdlDelLgbKey').data('id', data.lgb_key_id);
                    $('#mdlDelLgbKey').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del_name').text(data.name);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelLgbKey').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelLgbKey').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_lgb_key', '') }}/" + data.lgb_key_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) => {
                            $('#btnSubmitDelLgbKey').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 key');
                            $('#mdlDelLgbKey').modal('hide');
                            $('#mdlEdtLgbKey').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelLgbKey').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
