@extends('app.app')

@section('title')
    Conf Vehicle Types
@endsection

@section('customcss')
    <style>

    </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">Vehicle Types (<span id="count_trucktypes">0</span>)</p> --}}
                            <p class="card-title text-bold mb-0">Vehicle Types</p>
                        </div>
                        @can('config_truck_type.create')
                            <div class="col text-end">
                                <button id="btnMdlNewTruckType" class="btn btn-sm btn-danger">Add New Vehicle Type</button>
                            </div>
                        @endcan

                        <div class="col-auto text-end ps-0">
                            {{-- <button class="btn btn-sm btn-danger">Upload</button> --}}
                            {{-- <button class="btn btn-sm btn-danger">Download</button> --}}
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="tTruckTypes" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    <th class="w-100">Vehicle Type Name</th>
                                    <th class="text-center">Status</th>
                                    <th class="text-center">Publish</th>
                                </tr>
                            </thead>
                            <tbody>

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

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlNewTruckType" aria-labelledby="mdlNewTruckTypeLabel" 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="mdlNewTruckTypeLabel">Add New Vehicle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Truck Type --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Vehicle Type</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-6">
                                    <label for="add-type_name" class="col-form-label">Type Name:</label>
                                    <input type="text" name="add-type_name" id="add-type_name" class="form-control" placeholder="Please consider use english language">
                                </div>
                            </div>
                        </div>
                        {{-- Weight --}}
                        <div class="mb-3 d-none">
                            <div class="border-bottom">
                                <h6>Weight</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-max_kg" class="col-form-label">Max (KG)</label>
                                    <input type="text" name="add-max_kg" id="add-max_kg" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-max_cbm" class="col-form-label">Max (CBM)</label>
                                    <input type="text" name="add-max_cbm" id="add-max_cbm" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="add-max_koli" class="col-form-label">Max (Koli):</label>
                                    <input type="text" name="add-max_koli" id="add-max_koli" 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="add-status" class="form-label">Status</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 class="col-sm-6 col-md-3">
                                    <label for="add-publish" class="form-label">Publish</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="add-publish">
                                        <label class="form-check-label" for="add-publish"><span class="text-dark" id="add-txtPublish">Unpublish</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="btnSubmitNewTruckType" 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="mdlEdtTruckType" aria-labelledby="mdlEdtTruckTypeLabel" 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="mdlEdtTruckTypeLabel">Edit Vehicle Type</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form>
                        {{-- Truck Type --}}
                        <div class="mb-3">
                            <div class="border-bottom">
                                <h6>Vehicle Type</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-6">
                                    <label for="updt-type_name" class="col-form-label">Type Name:</label>
                                    <input type="text" name="updt-type_name" id="updt-type_name" class="form-control" placeholder="Please consider use english language">
                                </div>
                            </div>
                        </div>
                        {{-- Weight --}}
                        <div class="mb-3 d-none">
                            <div class="border-bottom">
                                <h6>Weight</h6>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-max_kg" class="col-form-label">Max (KG)</label>
                                    <input type="text" name="updt-max_kg" id="updt-max_kg" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-max_cbm" class="col-form-label">Max (CBM)</label>
                                    <input type="text" name="updt-max_cbm" id="updt-max_cbm" class="form-control">
                                </div>
                                <div class="col-sm-6 col-md-3">
                                    <label for="updt-max_koli" class="col-form-label">Max (Koli):</label>
                                    <input type="text" name="updt-max_koli" id="updt-max_koli" 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</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 class="col-sm-6 col-md-3">
                                    <label for="updt-publish" class="form-label">Publish ?</label>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="updt-publish">
                                        <label class="form-check-label" for="updt-publish"><span class="text-dark" id="updt-publishStatus">Unpublish</span></label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    @can('config_truck_type.delete')
                        <button type="button" id="btnDelTruckType_updt" class="btn btn-sm btn-warning">Delete ?</button>
                    @endcan
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    @can('config_truck_type.edit')
                        <button id="btnSubmitEdtTruckType" type="button" class="btn btn-sm btn-danger">Update data</button>
                    @endcan
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelTruckType" aria-labelledby="mdlDelTruckTypeLabel" 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="mdlDelTruckTypeLabel">Delete TruckType</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 vehicle type
                            <a href="#" class="text-danger">
                                <span id="del-type_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="btnSubmitDelTruckType" 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') }}/",
            stts_conf: {
                active: "{{ App\Models\ConfTruckTypes::IS_ACTIVE }}",
                inactive: "{{ App\Models\ConfTruckTypes::IS_INACTIVE }}",
                publish: "{{ App\Models\ConfTruckTypes::IS_PUBLISH }}",
                unpublish: "{{ App\Models\ConfTruckTypes::IS_UNPUBLISH }}",
            },
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                RNew.activate();
                RUpdt.activate();
                RDel.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')
                });

                $('#add-publish').bind('change', function() {
                    if ($(this).is(':checked'))
                        $('#add-txtPublish').html('Publish')
                    else
                        $('#add-txtPublish').html('Unpublish')
                });
                $('#updt-publish').bind('change', function() {
                    if ($(this).is(':checked'))
                        $('#updt-txtPublish').html('Publish')
                    else
                        $('#updt-txtPublish').html('Unpublish')
                });
            },
        };

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tTruckTypes').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tTruckTypes').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_conf_list_truck_types') }}",
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_trucktypes').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 btnUpdtTruckType">
										<span class="icon ion-eye fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelTruckType">
                                //     <span class="icon ion-trash-b fz-16"></span>
                                // </a>
                                return action;
                            }
                        },
                        {
                            data: 'type_name',
                            className: 'text-left text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-ttid', rowData.id);
                                $(td).attr('data-type_name', rowData.type_name);
                            },
                        },
                        {
                            data: 'is_active',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.stts_conf.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                } else {
                                    return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                                }
                            }
                        },
                        {
                            data: 'is_publish',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.stts_conf.publish) {
                                    return '<span class="badge rounded-pill bg-success">Publish</span>';
                                } else {
                                    return '<span class="badge rounded-pill bg-danger">Unpublish</span>';
                                }
                            }
                        },
                    ],
                });
            },
        };

        const RNew = {
            activate: function() {
                RNew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewTruckType').on('click', function() {
                    $('#mdlNewTruckType').modal('show');
                });
                $('#mdlNewTruckType').on('shown.bs.modal', function() {
                    // init select2
                });
                // button
                $('#btnSubmitNewTruckType').on('click', function() {
                    let data = RNew.getData();
                    RNew.submitData(data);
                });
                // input
            },
            getData: function() {
                let data = {};

                data.type_name = $('#add-type_name').val();

                data.max_kg = $('#add-max_kg').val();
                data.max_cbm = $('#add-max_cbm').val();
                data.max_koli = $('#add-max_koli').val();

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

                if ($('#add-publish').prop('checked')) {
                    data.publish = State.stts_conf.publish;
                } else {
                    data.publish = State.stts_conf.unpublish;
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewTruckType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewTruckType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_add_truck_type') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitNewTruckType').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 vehicle type');
                            $('#mdlNewTruckType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewTruckType').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 RUpdt = {
            activate: function() {
                RUpdt.event();
            },
            event: function() {
                // modal
                $('#tTruckTypes').on('click', '.btnUpdtTruckType', async function(e) {
                    let ttid = $(e.target).closest('tr').find('td[data-ttid]').data('ttid');
                    let resp = await RUpdt.reqData({
                        ttid
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Vehicle Type Not Found', 'just now', 'please try again');
                        return false;
                    }
                    RUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtTruckType').on('shown.bs.modal', function() {
                    // init select2
                });
                // button
                $('#btnSubmitEdtTruckType').on('click', function() {
                    let data = RUpdt.getData();
                    RUpdt.submitData(data);
                });
                // input
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_conf_show_truck_type', '') }}/" + params.ttid,
                        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-type_name').val(data.type_name);

                $('#updt-max_kg').val(data.max_kg || '');
                $('#updt-max_cbm').val(data.max_cbm || '');
                $('#updt-max_koli').val(data.max_koli || '');

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

                if (data.is_publish == State.stts_conf.publish) {
                    $('#updt-publish').prop('checked', true).trigger('change');
                } else {
                    $('#updt-publish').prop('checked', false).trigger('change');
                }

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

                data.ttid = $('#mdlEdtTruckType').data('id');
                data.type_name = $('#updt-type_name').val();

                data.max_kg = $('#updt-max_kg').val();
                data.max_cbm = $('#updt-max_cbm').val();
                data.max_koli = $('#updt-max_koli').val();

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

                if ($('#updt-publish').prop('checked')) {
                    data.publish = State.stts_conf.publish;
                } else {
                    data.publish = State.stts_conf.unpublish;
                }

                return data;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtTruckType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtTruckType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_edit_truck_type', '') }}/" + data.ttid,
                        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) => {
                            $('#btnSubmitEdtTruckType').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 trucktype');
                            $('#mdlEdtTruckType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtTruckType').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 RDel = {
            activate: function() {
                RDel.event();
            },
            event: function() {
                // on table
                $('#tTruckTypes').on('click', '.btnDelTruckType', function(e) {
                    let row = $(e.target).closest('tr');
                    let ttid = row.find('td[data-ttid]').data('ttid');
                    let type_name = row.find('td[data-type_name]').data('type_name');
                    RDel.passDataToView({
                        ttid,
                        type_name,
                    });
                    $('#mdlDelTruckType').data('id', ttid);
                    $('#mdlDelTruckType').modal('show');
                });
                $('#btnSubmitDelTruckType').on('click', function() {
                    let data = {
                        ttid: $('#mdlDelTruckType').data('id'),
                    };
                    RDel.submitData(data);
                });
                // on modal update
                $('#btnDelTruckType_updt').on('click', function(e) {
                    let data = RUpdt.getData();
                    RDel.passDataToView({
                        ttid: data.ttid,
                        type_name: data.type_name,
                    });
                    $('#mdlDelTruckType').data('id', data.ttid);
                    $('#mdlDelTruckType').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del-type_name').text(data.type_name);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelTruckType').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelTruckType').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_conf_del_truck_type', '') }}/" + data.ttid,
                        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) => {
                            $('#btnSubmitDelTruckType').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 vehicle type');
                            $('#mdlDelTruckType').modal('hide');
                            $('#mdlEdtTruckType').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelTruckType').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
