@extends('app.app')

@section('title')
    Master Additional Items
@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">Item (<span id="count_a_items">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewItem" class="btn btn-sm btn-danger">Tambah Item Baru</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="tItems" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center"></th>
                                    <th class="">Nama Item</th>
                                    <th class="text-end">Satuan</th>
                                    <th class="text-end">Harga</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="mdlNewItem" aria-labelledby="mdlNewItemLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlNewItemLabel">Tambah Item Baru</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Primary --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Data Item</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <label for="add-name" class="col-form-label">Nama<span class="text-danger">*</span></label>
                                    <input type="text" name="add-name" id="add-name" class="form-control">
                                </div>
                                <div class="col-sm-12">
                                    <label for="add-type" class="col-form-label">Satuan<span class="text-danger">*</span></label>
                                    <select name="add-type" id="add-type" class="form-control" style="width:100%;">
                                        <option value="" selected disabled>Belum dipilih</option>
                                        @foreach ($unitTypes as $type)
                                            <option value="{{ $type->id }}">{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-12">
                                    <label for="add-price" class="col-form-label">Harga Satuan<span class="text-danger">*</span></label>
                                    <input type="text" name="add-price" id="add-price" class="form-control">
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <label for="add-status" class="form-label">Status<span class="text-danger">*</span></label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="add-status">
                                        <label class="form-check-label" for="add-status"><span class="text-dark" id="add-txtStatus">Inactive</span></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @if ($user->role === \App\Models\Users::ROLE_FINANCE)
                            <div>
                                <div class="form-check">
                                    <input class="form-check-input" name="add-isAdmPrice" type="checkbox" value="yes" id="add-isAdmPrice">
                                    <label class="form-check-label text-danger" for="add-isAdmPrice">
                                        Biaya admin ?
                                    </label>
                                </div>
                            </div>
                        @endif
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitNewItem" 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="mdlUpdtItem" aria-labelledby="mdlUpdtItemLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlUpdtItemLabel">Edit Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Primary --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Data Item</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <label for="updt-name" class="col-form-label">Nama<span class="text-danger">*</span></label>
                                    <input type="text" name="updt-name" id="updt-name" class="form-control">
                                </div>
                                <div class="col-sm-12">
                                    <label for="updt-type" class="col-form-label">Satuan<span class="text-danger">*</span></label>
                                    <select name="updt-type" id="updt-type" class="form-control" style="width:100%;">
                                        <option value="" selected disabled>Belum dipilih</option>
                                        @foreach ($unitTypes as $type)
                                            <option value="{{ $type->id }}">{{ $type->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-12">
                                    <label for="updt-price" class="col-form-label">Harga Satuan<span class="text-danger">*</span></label>
                                    <input type="text" name="updt-price" id="updt-price" class="form-control">
                                </div>
                            </div>
                        </div>
                        {{-- Utilites --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Utilities</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <label for="updt-status" class="form-label">Status<span class="text-danger">*</span></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>
                        @if ($user->role === \App\Models\Users::ROLE_FINANCE)
                            <div>
                                <div class="form-check">
                                    <input class="form-check-input" name="updt-isAdmPrice" type="checkbox" value="yes" id="updt-isAdmPrice">
                                    <label class="form-check-label text-danger" for="updt-isAdmPrice">
                                        Biaya admin ?
                                    </label>
                                </div>
                            </div>
                        @endif
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnDelItem_updt" class="btn btn-sm btn-warning">Hapus ?</button>
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitUpdtItems" 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="mdlDelItem" aria-labelledby="mdlDelItemLabel" 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="mdlDelItemLabel">Delete Item</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">
                            Kamu yakin ingin menghapus item
                            <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="btnSubmitDelItem" type="button" class="btn btn-sm btn-secondary">Iya, hapus</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') }}/",
            stts_isact: {
                active: "{{ App\Models\AItems::IS_ACTIVE }}",
                inactive: "{{ App\Models\AItems::IS_INACTIVE }}",
            },
            is_adm_price: {
                no: "{{ App\Models\AItems::IS_ADM_PRICE_NO }}",
                yes: "{{ App\Models\AItems::IS_ADM_PRICE_YES }}",
            },
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                ANew.activate();
                AUpdt.activate();
                ADel.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')
                });
                // fix modal select2
                $('#add-type').select2({
                    dropdownParent: $('#mdlNewItem'),
                });
                $('#updt-type').select2({
                    dropdownParent: $('#mdlUpdtItem'),
                });
            },
        };

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

        const ANew = {
            activate: function() {
                ANew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewItem').on('click', function() {
                    $('#mdlNewItem').modal('show');
                });
                $('#mdlNewItem').on('shown.bs.modal', function() {

                });
                // button
                $('#btnSubmitNewItem').on('click', function() {
                    let data = ANew.getData();
                    ANew.submitData(data);
                });
                // input
                $('#add-price').on('keyup', function() {
                    let price = $('#add-price').val().split('.').join('');
                    $('#add-price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
            },
            getData: function() {
                let data = {};
                data.name = $('#add-name').val();
                data.type = $('#add-type').val();
                data.price = $('#add-price').val().split('.').join('');

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

                if ($('#add-isAdmPrice').prop('checked')) {
                    data.is_adm_price = State.is_adm_price.yes
                } else {
                    data.is_adm_price = State.is_adm_price.no
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_a_items') }}",
                        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) => {
                            $('#btnSubmitNewItem').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 additional item');
                            $('#mdlNewItem').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewItem').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 AUpdt = {
            activate: function() {
                AUpdt.event();
            },
            event: function() {
                // modal
                $('#tItems').on('click', '.btnUpdtItem', async function(e) {
                    let id = $(e.target).closest('tr').find('td[data-id]').data('id');
                    let resp = await AUpdt.reqData({
                        id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item Not Found', 'just now', 'please try again');
                        return false;
                    }
                    AUpdt.passDataToView(resp.data);
                });
                $('#mdlUpdtItem').on('shown.bs.modal', function() {

                });
                // button
                $('#btnSubmitUpdtItems').on('click', function() {
                    let data = AUpdt.getData();
                    AUpdt.submitData(data);
                });
                // input
                $('#updt-price').on('keyup', function() {
                    let price = $('#updt-price').val().split('.').join('');
                    $('#updt-price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_a_items', '') }}/" + params.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');
                $('#updt-price').val(data.price);

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

                if (data.is_adm_price == State.is_adm_price.yes) {
                    $('#updt-isAdmPrice').prop('checked', true).trigger('change');
                } else {
                    $('#updt-isAdmPrice').prop('checked', false).trigger('change');
                }

                $('#mdlUpdtItem').data('id', data.id);
                $('#mdlUpdtItem').modal('show');
            },
            getData: function() {
                let data = {};
                data.id = $('#mdlUpdtItem').data('id');

                data.name = $('#updt-name').val();
                data.type = $('#updt-type').val();
                data.price = $('#updt-price').val().split('.').join('');

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

                if ($('#updt-isAdmPrice').prop('checked')) {
                    data.is_adm_price = State.is_adm_price.yes
                } else {
                    data.is_adm_price = State.is_adm_price.no
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitUpdtItems').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitUpdtItems').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_updt_a_items', '') }}/" + data.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) => {
                            $('#btnSubmitUpdtItems').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 additional item');
                            $('#mdlUpdtItem').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitUpdtItems').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 ADel = {
            activate: function() {
                ADel.event();
            },
            event: function() {
                // on table
                $('#tItems').on('click', '.btnDelItem', 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');
                    let price = row.find('td[data-price]').data('price');
                    ADel.passDataToView({
                        id,
                        name,
                        price,
                    });
                    $('#mdlDelItem').data('id', id);
                    $('#mdlDelItem').modal('show');
                });
                $('#btnSubmitDelItem').on('click', function() {
                    let data = {
                        id: $('#mdlDelItem').data('id'),
                    };
                    ADel.submitData(data);
                });
                // on modal update
                $('#btnDelItem_updt').on('click', function(e) {
                    const {
                        id,
                        name,
                        price
                    } = AUpdt.getData();
                    ADel.passDataToView({
                        id,
                        name,
                        price,
                    });
                    $('#mdlDelItem').data('id', id);
                    $('#mdlDelItem').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del-name').text(data.name);
                $('#del-price').text(data.price);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_a_items', '') }}/" + data.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) => {
                            $('#btnSubmitDelItem').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 additional item');
                            $('#mdlDelItem').modal('hide');
                            $('#mdlUpdtItem').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelItem').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
