@extends('app.app')

@section('title')
    Assuransi
@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">Asuransi (<span id="count_insurances">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewInsurance" class="btn btn-sm btn-danger">Buat Asuransi 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="tInsurances" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="">Deskripsi</th>
                                    <th class="text-end">Percent</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="mdlEdtInsurances" aria-labelledby="mdlEdtInsurancesLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog modal-dialog-centered modal-dialog-scrollable modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlEdtInsurancesLabel">Edit Asuransi</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 Premi</h6>
                            </div> --}}
                            <div class="row">
                                {{-- <div class="col-sm-12">
                                    <label for="updt-desc" class="col-form-label">Deskripsi</label>
                                    <textarea name="updt-desc" id="updt-desc" class="form-control"></textarea>
                                </div> --}}
                                <div class="col-sm-12">
                                    <label for="updt-amt_percent" class="col-form-label">Percent dari nilai pertangguhan<span class="text-danger">*</span></label>
                                    <input type="text" name="updt-amt_percent" id="updt-amt_percent" class="form-control">
                                </div>
                                {{-- <div class="col-sm-12">
                                    <label for="updt-amt_flat" class="col-form-label">Percent<span
                                            class="text-danger">*</span></label>
                                    <input type="text" name="updt-amt_flat" id="updt-amt_flat" 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-6 col-md-3">
                                    <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> --}}
                    </form>
                </div>
                <div class="modal-footer">
                    {{-- <button type="button" id="btnDelInsurance_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="btnSubmitEdtInsurances" type="button" class="btn btn-sm btn-danger">Update Data</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customjs')
    <script>
        'use strict';
        const State = {
            storage_lara: "{{ asset('storage') }}/",
            stts_isact: {
                active: "{{ App\Models\StaticInsurances::IS_ACTIVE }}",
                inactive: "{{ App\Models\StaticInsurances::IS_INACTIVE }}",
            },
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                AUpdt.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 DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tInsurances').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tInsurances').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_static_insurances') }}",
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_insurances').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 btnUpdtInsurance">
										<span class="icon ion-edit fz-16"></span>
									</a>
                                    `;
                                // <a href="#" class="text-decoration-none text-danger btnDelInsurance">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'desc',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-id', rowData.id);
                                $(td).attr('data-desc', rowData.desc);
                                $(td).attr('data-amt_percent', rowData.amt_percent);
                            },
                            render: function(data, type, row, meta) {
                                if (!data) return '-';
                                return data;
                            },
                        },
                        {
                            data: 'amt_percent',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                return data + '%';
                            },
                        },
                        // {
                        //     data: 'amt_flat',
                        //     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 AUpdt = {
            activate: function() {
                AUpdt.event();
            },
            event: function() {
                // modal
                $('#tInsurances').on('click', '.btnUpdtInsurance', 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('Insurance Not Found', 'just now', 'please try again');
                        return false;
                    }
                    AUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtInsurances').on('shown.bs.modal', function() {

                });
                // button
                $('#btnSubmitEdtInsurances').on('click', function() {
                    let data = AUpdt.getData();
                    let isValid = AUpdt.checkData(data);
                    if (!isValid) return false;
                    AUpdt.submitData(data);
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_static_insurance', '') }}/" + 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-desc').val(data.desc);

                $('#updt-amt_percent').val(data.amt_percent);
                // $('#updt-amt_flat').val((new Intl.NumberFormat('id-ID').format(data.amt_flat)));

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

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

                data.amt_percent = Number($('#updt-amt_percent').val());
                // data.desc = $('#updt-desc').val();
                data.desc = data.amt_percent + '% dari nilai pertangguhan';
                // data.amt_flat = $('#updt-amt_flat').val().split('.').join('');

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

                return data;
            },
            checkData: function(data, isAlert = true) {
                if (data.amt_percent < 1 || isNaN(data.amt_percent)) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Percent tidak valid');
                    return false;
                }
                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtInsurances').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtInsurances').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_static_insurance', '') }}/" + 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) => {
                            $('#btnSubmitEdtInsurances').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 insurance');
                            $('#mdlEdtInsurances').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtInsurances').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
