@extends('app.app')

@section('title')
    Publish Pocket & Duration
@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">Uang Saku (<span id="count_pocket">0</span>)</p>
                        </div>
                        <div class="col text-end">
                            <button id="btnMdlNewPocket" class="btn btn-sm btn-danger">Tambah Uang Saku</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="tPocket" class="table table-hover dataTable">
                            <thead>
                                <tr class="">
                                    <th class="">#</th>
                                    <th class="text-center">Action</th>
                                    {{-- <th class="text-end">Code</th> --}}
                                    <th class="">Nama</th>
                                    <th class="">Pickup</th>
                                    {{-- <th class="">Drop</th> --}}
                                    <th class="">Type</th>
                                    {{-- <th class="">Flow</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="mdlNewPocket"
        aria-labelledby="mdlNewPocketLabel" 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="mdlNewPocketLabel">Tambah Uang Saku</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formAdd">
                        <div class="mb-3">
                            {{-- <div class="border-bottom">
                                <h6>Uang Saku</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <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" placeholder="FREE_E-TOL02">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <label for="add_type" class="col-form-label">Type<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 class="row">
                                <div class="col-sm-6 col-md-4">
                                    <div class="row">
                                        <div class="col-12 mb-1">
                                            <label for="add_pck" class="col-form-label">Pickup<span class="text-danger">*</span></label>
                                            <select name="add_pck" id="add_pck"
                                                class="form-control" style="width:100%;">
                                                <option value="">Lokasi Pickup</option>
                                                {{-- @foreach ($pickups as $pck)
                                                    <option value="{{ $pck->id }}" data-name="{{ $pck->name }}" data-fulladdress="{{ $pck->fulladdress }}">{{ $pck->name }}</option>
                                                @endforeach --}}
                                            </select>
                                            <p id="add_pck_location" class="mb-0">&nbsp;</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="row">
                                        <div class="col-12 mb-1">
                                            <label for="add_drop" class="col-form-label">Drop<span class="text-danger">*</span></label>
                                            <select name="add_drop" id="add_drop" class="form-control" style="width:100%;">
                                                <option value="">Lokasi Drop</option>
                                                {{-- @foreach ($drops as $drop)
                                                    <option value="{{ $drop->id }}" data-name="{{ $drop->name }}" data-fulladdress="{{ $drop->fulladdress }}">{{ $drop->name }}</option>
                                                @endforeach --}}
                                            </select>
                                            <p id="add_drop_location" class="mb-0">&nbsp;</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md-4 groupAddPrice">
                                    <label for="add_price" class="col-form-label">Harga (Rp)<span class="text-danger">*</span></label>
                                    <input type="text" name="add_price" id="add_price" class="form-control" value="0">
                                </div>
                            </div>
                        </div>
                        {{-- Checkpoint --}}
                        <div class="mb-3 groupAddCheckpoint">
                            <div class="border-bottom">
                                <div class="row">
                                    <div class="col-11">
                                        <h6>Checkpoints</h6>
                                    </div>
                                    <div class="col-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-6">
                                        <div class="row">
                                            <div class="col-12 mb-1">
                                                <label for="add_start_checkpoints[]" class="col-form-label">Titik Lokasi<span class="text-danger">*</span></label>
                                                <select name="add_start_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                                    <option value="">Pilih Checkpoint</option>
                                                    ${pck_checkpoints}
                                                </select>
                                                <p class="add_pck_location_checkpoints mb-0">&nbsp;</p>
                                            </div>
                                        </div>
                                    </div>
                                    {{-- <div class="col-sm-6 col-md-4">
                                        <div class="row">
                                            <div class="col-12 mb-1">
                                                <label for="add_end_checkpoints[]" class="col-form-label">Titik Akhir<span class="text-danger">*</span></label>
                                                <select name="add_end_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                                    <option value="">Pilih Checkpoint</option>
                                                    ${drop_checkpoints}
                                                </select>
                                                <p class="add_drop_location_checkpoints mb-0">&nbsp;</p>
                                            </div>
                                        </div>
                                    </div> --}}
                                    <div class="col-sm-6 col-md-3">
                                        <label for="add_price_checkpoints[]" class="col-form-label">Harga (Rp)<span class="text-danger">*</span></label>
                                        <input type="text" name="add_price_checkpoints[]" class="form-control" value="0">
                                    </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="btnSubmitNewPocket" 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="mdlEdtPocket"
        aria-labelledby="mdlEdtPocketLabel" 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="mdlEdtPocketLabel">Edit Pocket</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formUpdt">
                        <div class="mb-3">
                            {{-- <div class="border-bottom">
                                <h6>Uang Saku</h6>
                            </div> --}}
                            <div class="row">
                                <div class="col-sm-6 col-md-4">
                                    <label for="updt_name" class="col-form-label">Nama<span class="text-danger">*</span></label>
                                    <input type="text" name="updt_name" id="updt_name" class="form-control" placeholder="FREE_E-TOL02">
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <label for="updt_type" class="col-form-label">Type<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 class="row">
                                <div class="col-sm-6 col-md-4">
                                    <div class="row">
                                        <div class="col-12 mb-1">
                                            <label for="updt_pck" class="col-form-label">Pickup<span class="text-danger">*</span></label>
                                            <select name="updt_pck" id="updt_pck"
                                                class="form-control" style="width:100%;">
                                                <option value="">Lokasi Pickup</option>
                                                {{-- @foreach ($pickups as $pck)
                                                    <option value="{{ $pck->id }}" data-name="{{ $pck->name }}" data-fulladdress="{{ $pck->fulladdress }}">{{ $pck->name }}</option>
                                                @endforeach --}}
                                            </select>
                                            <p id="updt_pck_location" class="mb-0">&nbsp;</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md-4">
                                    <div class="row">
                                        <div class="col-12 mb-1">
                                            <label for="updt_drop" class="col-form-label">Drop<span class="text-danger">*</span></label>
                                            <select name="updt_drop" id="updt_drop" class="form-control" style="width:100%;">
                                                <option value="">Lokasi Drop</option>
                                                {{-- @foreach ($drops as $drop)
                                                    <option value="{{ $drop->id }}" data-name="{{ $drop->name }}" data-fulladdress="{{ $drop->fulladdress }}">{{ $drop->name }}</option>
                                                @endforeach --}}
                                            </select>
                                            <p id="updt_drop_location" class="mb-0">&nbsp;</p>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-6 col-md-3 groupUpdtPrice">
                                    <label for="updt_price" class="col-form-label">Harga (Rp)<span class="text-danger">*</span></label>
                                    <input type="text" name="updt_price" id="updt_price" class="form-control" value="0">
                                </div>
                            </div>
                        </div>
                        {{-- Checkpoint --}}
                        <div class="mb-3 groupUpdtCheckpoint">
                            <div class="border-bottom">
                                <div class="row">
                                    <div class="col-11">
                                        <h6>Checkpoints</h6>
                                    </div>
                                    <div class="col-1 text-start">
                                        <button id="updt-point-add-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-6">
                                        <div class="row">
                                            <div class="col-12 mb-1">
                                                <label for="updt_start_checkpoints[]" class="col-form-label">Titik Lokasi<span class="text-danger">*</span></label>
                                                <select name="updt_start_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                                    <option value="">Pilih Checkpoint</option>
                                                    ${pck_checkpoints}
                                                </select>
                                                <p class="updt_pck_location_checkpoints mb-0">&nbsp;</p>
                                            </div>
                                        </div>
                                    </div>
                                    {{-- <div class="col-sm-6 col-md-4">
                                        <div class="row">
                                            <div class="col-12 mb-1">
                                                <label for="updt_end_checkpoints[]" class="col-form-label">Titik Akhir<span class="text-danger">*</span></label>
                                                <select name="updt_end_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                                    <option value="">Pilih Checkpoint</option>
                                                    ${drop_checkpoints}
                                                </select>
                                                <p class="updt_drop_location_checkpoints mb-0">&nbsp;</p>
                                            </div>
                                        </div>
                                    </div> --}}
                                    <div class="col-sm-6 col-md-5">
                                        <label for="updt_price_checkpoints[]" class="col-form-label">Harga (Rp)<span class="text-danger">*</span></label>
                                        <input type="text" name="updt_price_checkpoints[]" class="form-control" value="0">
                                    </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">
                                        <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="btnDelPocket_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="btnSubmitEdtPocket" 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="mdlDelPocket"
        aria-labelledby="mdlDelPocketLabel" 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="mdlDelPocketLabel">Delete Pocket</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 pocket
                            <a href="#" class="text-danger">
                                <span id="del-pck_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="btnSubmitDelPocket" 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\PocketMoney::IS_ACTIVE }}",
                inactive: "{{ App\Models\PocketMoney::IS_INACTIVE }}",
            },
            pocket_type: {
                bundle: "{{ App\Models\PocketMoney::TYPE_BUNDLE }}",
                bundle_text: "{{ App\Models\PocketMoney::TYPE_BUNDLE_TEXT }}",
                checkpoints: "{{ App\Models\PocketMoney::TYPE_CHECKPOINTS }}",
                checkpoints_text: "{{ App\Models\PocketMoney::TYPE_CHECKPOINTS_TEXT }}",
            },
            pocket_flow: {
                departure: "{{ App\Models\PocketMoney::FLOW_DEPARTURE }}",
                departure_text: "{{ App\Models\PocketMoney::FLOW_DEPARTURE_TEXT }}",
                arrival: "{{ App\Models\PocketMoney::FLOW_ARRIVAL }}",
                arrival_text: "{{ App\Models\PocketMoney::FLOW_ARRIVAL_TEXT }}",
                hybrid: "{{ App\Models\PocketMoney::FLOW_HYBRID }}",
                hybrid_text: "{{ App\Models\PocketMoney::FLOW_HYBRID_TEXT }}",
            },
            workflow_type: {
                pickup: "{{ App\Models\Zone::ZONE_WORKFLOW_PICKUP }}",
                drop: "{{ App\Models\Zone::ZONE_WORKFLOW_DEST }}",
            },
            l_pickups: [],
            l_drops: [],
            pck_checkpoints: [],
            drop_checkpoints: [],
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                DTable.activate();
                PNew.activate();
                PNewCheckpoint.activate();
                PUpdt.activate();
                PUpdtCheckpoint.activate();
                PDel.activate();
                Filter.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_pck').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
                $('#add_drop').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
                $('#add_type').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });

                $('#updt_pck').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
                $('#updt_drop').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
                $('#updt_type').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
            },
        };

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

        const Filter = {
            activate: function() {
                Filter.event();
                Filter.zones();
            },
            event: function() {
            },
            triggerFilterCompany: function() {
                DTable.reload();
                Filter.zones();
            },
            zones: async function() {
                State.l_pickups = [];
                State.l_drops = [];
                State.pck_checkpoints = [];
                State.drop_checkpoints = [];
                PNew.reDataZone();
                PUpdt.reDataZone();

                let cptid = (AppState.current_company == 0) ? undefined : AppState.current_company;
                const respPickups = await Req.list_client_zone({cptid, workflow_type: State.workflow_type.pickup}, false, null);
                if (respPickups.type !== 'success') {
                    Helper.toast('Warning', 'just now', 'Client belum mempunyai zona pickup');
                    return false;
                }
                State.l_pickups = respPickups.resp.data;
                const respDrops = await Req.list_client_zone({cptid, workflow_type: State.workflow_type.drop}, false, null);
                if (respDrops.type !== 'success') {
                    Helper.toast('Warning', 'just now', 'Client belum mempunyai zona drop');
                    return false;
                }
                State.l_drops = respDrops.resp.data;
                PNew.reDataZone();
                PUpdt.reDataZone();

                const pckCheckpoints = await Req.list_checkpoints({}, true, null);
                if (pckCheckpoints.type === 'success') {
                    State.pck_checkpoints = pckCheckpoints.resp.data;
                    State.drop_checkpoints = pckCheckpoints.resp.data;
                }
                // const dropCheckpoints = await Req.list_checkpoints({}, true, null);
                // if (dropCheckpoints.type === 'success') {
                //     State.drop_checkpoints = dropCheckpoints.resp.data;
                // }
            },
        }

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tPocket').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                $('#tPocket').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_list_pockets') }}?cptid="+AppState.current_company,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            let count = jqXHR.responseJSON.count;
                            if (typeof count != 'undefined') {
                                $('#count_pocket').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-pck_name', rowData.pck_name);
                                $(td).attr('data-pck_fulladdress', rowData.pck_fulladdress);
                                // $(td).attr('data-drop_name', rowData.drp_name);
                                // $(td).attr('data-drop_fulladdress', rowData.drop_fulladdress);
                            },
                            render: function(data, type, row, meta) {
                                let action = `
									<a href="#" class="text-decoration-none me-1 btnUpdtPocket">
										<span class="icon ion-edit fz-16"></span>
									</a>
								`;
                                // <a href="#" class="text-decoration-none text-danger btnDelPocket">
                                //     <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-wrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
						{
                            data: 'pck_name',
                            className: 'text-start text-wrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data) {
                                    return data + '<br>' + row.pck_fulladdress;
                                }
                                return '-';
                            }
                        },
                        // {
                        //     data: 'drop_name',
                        //     className: 'text-start text-wrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        //     render: function(data, type, row, meta) {
                        //         if (data) {
                        //             return data + '<br>' + row.drop_fulladdress;
                        //         }
                        //         return '-';
                        //     }
                        // },
                        {
                            data: 'type',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.pocket_type.bundle) {
                                    return State.pocket_type.bundle_text;
                                } else if (data == State.pocket_type.checkpoints) {
                                    return State.pocket_type.checkpoints_text;
                                } else {
                                    return '-';
                                }
                            }
                        },
                        // {
                        //     data: 'flow',
                        //     className: 'text-start text-nowrap',
                        //     visible: true,
                        //     orderable: true,
                        //     searchable: true,
                        //     render: function(data, type, row, meta) {
                        //         if (data == State.pocket_flow.departure) {
                        //             return State.pocket_flow.departure_text;
                        //         } else if (data == State.pocket_flow.arrival) {
                        //             return State.pocket_flow.arrival_text;
                        //         } else if (data == State.pocket_flow.hybrid) {
                        //             return State.pocket_flow.hybrid_text;
                        //         } else {
                        //             return '-';
                        //         }
                        //     }
                        // },
                        {
                            data: 'is_active',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (data == State.is_active.active) {
                                    return '<span class="badge rounded-pill bg-success">Active</span>';
                                } else {
                                    return '<span class="badge rounded-pill bg-danger">Inactive</span>';
                                }
                            }
                        },
                    ],
                });
            },
        };

        const PNew = {
            activate: function() {
                PNew.event();
            },
            event: function() {
                // modal
                $('#btnMdlNewPocket').on('click', function() {
                    $('#mdlNewPocket').modal('show');
                });
                $('#mdlNewPocket').on('shown.bs.modal', function() {
                    
                });
                // button
                $('#btnSubmitNewPocket').on('click', function() {
                    let data = PNew.getData();
                    let isValid = PNew.checkData(data, true);
                    if (!isValid) return false;
                    PNew.submitData(data);
                });
                // select
                $('#add_type').on('change', function() {
                    let type = $('#add_type').val();
                    if (type == State.pocket_type.bundle) {
                        PNewCheckpoint.removeAll();

                        $('.groupAddPrice').removeClass('d-none');
                        $('.groupAddCheckpoint').addClass('d-none');
                    } else if (type == State.pocket_type.checkpoints) {
                        PNewCheckpoint.removeAll();
                        PNewCheckpoint.add();
                        PNewCheckpoint.reTriggerSel2();

                        $('.groupAddPrice').addClass('d-none');
                        $('.groupAddCheckpoint').removeClass('d-none');
                    } else {
                        PNewCheckpoint.removeAll();

                        $('.groupAddPrice').addClass('d-none');
                        $('.groupAddCheckpoint').addClass('d-none');
                    }
                    $('#add_price').val('0');
                });
                $('#add_pck').on('change', function() {
                    let pck = $('#add_pck :selected');
                    if (pck && pck != '') {
                        $('#add_pck_location').text(pck.data('fulladdress'));
                    } else {
                        $('#add_pck_location').text('');
                    }
                });
                $('#add_drop').on('change', function() {
                    let drop = $('#add_drop :selected');
                    if (drop && drop != '') {
                        $('#add_drop_location').text(drop.data('fulladdress'));
                    } else {
                        $('#add_drop_location').text('');
                    }
                });
                $('#divAddCheckpoint').on('change', 'select[name="add_start_checkpoints[]"]', function (e) {
                    let trgt = $(e.target);
                    let idx = trgt.data('idx');
                    if (trgt && trgt.val() != '') {
                        $(`#divRowAddCheckpoint${idx}`).find('.add_pck_location_checkpoints').text(trgt.children(':selected').data('fulladdress'));
                    } else {
                        $(`#divRowAddCheckpoint${idx}`).find('.add_pck_location_checkpoints').text('');
                    }
                });
                $('#divAddCheckpoint').on('change', 'select[name="add_end_checkpoints[]"]', function (e) {
                    let trgt = $(e.target);
                    let idx = trgt.data('idx');
                    if (trgt && trgt.val() != '') {
                        $(`#divRowAddCheckpoint${idx}`).find('.add_drop_location_checkpoints').text(trgt.children(':selected').data('fulladdress'));
                    } else {
                        $(`#divRowAddCheckpoint${idx}`).find('.add_drop_location_checkpoints').text('');
                    }
                });
                // input
                $('#add_price').on('keyup', function() {
                    let price = Number($('#add_price').val().split('.').join('').split(',').join('.'));
                    $('#add_price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                $('#divAddCheckpoint').on('keyup', 'input[name="add_price_checkpoints[]"]', function(e) {
                    let trgt = $(e.target);
                    let price = Number(trgt.val().split('.').join('').split(',').join('.'));
                    trgt.val((new Intl.NumberFormat('id-ID')).format(price));
                });
                // trigger select
                $('#add_type').val(State.pocket_type.bundle).trigger('change');
            },
            reDataZone: function() {
                $('#add_pck').html('<option value="">Lokasi Pickup</option>');
                for (let pck of State.l_pickups) {
                    $('#add_pck').append(`<option value="${pck.id}">${pck.name}</option>`);
                }
                $('#add_pck').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
                $('#add_drop').html('<option value="">Lokasi Drop</option>');
                for (let drop of State.l_drops) {
                    $('#add_drop').append(`<option value="${drop.id}">${drop.name}</option>`);
                }
                $('#add_drop').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
            },
            getData: function() {
                let data = Helper.objectifyForm($('#formAdd').serializeArray());
                data.add_price = Number(data.add_price.split('.').join('').split(',').join('.'));

                if (typeof data.add_price_checkpoints !== 'undefined') {
                    for (let i in data.add_price_checkpoints) {
                        data.add_price_checkpoints[i] = Number(data.add_price_checkpoints[i].split('.').join('').split(',').join('.'));
                    }
                }

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

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

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitNewPocket').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitNewPocket').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_add_pocket') }}",
                        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) => {
                            $('#btnSubmitNewPocket').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success menambahkan uang saku');
                            $('#mdlNewPocket').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitNewPocket').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 PNewCheckpoint = {
            activate: async function() {
                PNewCheckpoint.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 checkpoint');
                        return false;
                    }
                    trgt.closest('.divRowAddCheckpoint').remove();
                });
                $('#point-add-row').on('click', function() {
                    PNewCheckpoint.add();
                });
            },
            reTriggerSel2: function () {
                $('select[name="add_start_checkpoints[]"]').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
                $('select[name="add_end_checkpoints[]"]').select2({
                    dropdownParent: $('#mdlNewPocket'),
                });
            },
            add: function () {
                let pck_checkpoints = '', drop_checkpoints = '';

                for (let pck of State.pck_checkpoints) {
                    pck_checkpoints += `<option value="${pck.id}" data-name="${pck.name}" data-fulladdress="${pck.fulladdress}">${pck.name}</option>`;
                }

                // for (let drop of State.drop_checkpoints) {
                //     drop_checkpoints += `<option value="${drop.id}" data-name="${drop.name}" data-fulladdress="${drop.fulladdress}">${drop.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-6">
                        <div class="row">
                            <div class="col-12 mb-1">
                                <label for="add_start_checkpoints[]" class="col-form-label">Titik Lokasi<span class="text-danger">*</span></label>
                                <select name="add_start_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                    <option value="">Pilih Checkpoint</option>
                                    ${pck_checkpoints}
                                </select>
                                <p class="add_pck_location_checkpoints mb-0">&nbsp;</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-5">
                        <label for="add_price_checkpoints[]" class="col-form-label">Harga</label>
                        <input type="text" name="add_price_checkpoints[]" class="form-control" value="0">
                    </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);

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

        const PUpdt = {
            activate: function() {
                PUpdt.event();
            },
            event: function() {
                // modal
                $('#tPocket').on('click', '.btnUpdtPocket', async function(e) {
                    let id = $(e.target).closest('tr').find('td[data-id]').data('id');
                    let resp = await PUpdt.reqData({
                        pocket_id: id,
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Pocket Not Found', 'just now', 'please try again');
                        return false;
                    }
                    PUpdt.passDataToView(resp.data);
                });
                $('#mdlEdtPocket').on('shown.bs.modal', function() {
                    
                });
                // button
                $('#btnSubmitEdtPocket').on('click', function() {
                    let data = PUpdt.getData();
                    let isValid = PUpdt.checkData(data, true);
                    if (!isValid) return false;
                    PUpdt.submitData(data);
                });
                // select
                $('#updt_type').on('change', function() {
                    let type = $('#updt_type').val();
                    if (type == State.pocket_type.bundle) {
                        PUpdtCheckpoint.removeAll();

                        $('.groupUpdtPrice').removeClass('d-none');
                        $('.groupUpdtCheckpoint').addClass('d-none');
                    } else if (type == State.pocket_type.checkpoints) {
                        PUpdtCheckpoint.removeAll();
                        PUpdtCheckpoint.add();
                        PUpdtCheckpoint.reTriggerSel2();

                        $('.groupUpdtPrice').addClass('d-none');
                        $('.groupUpdtCheckpoint').removeClass('d-none');
                    } else {
                        PUpdtCheckpoint.removeAll();

                        $('.groupUpdtPrice').addClass('d-none');
                        $('.groupUpdtCheckpoint').addClass('d-none');
                    }
                    $('#updt_price').val('0');
                });
                $('#updt_pck').on('change', function() {
                    let pck = $('#updt_pck :selected');
                    if (pck && pck != '') {
                        $('#updt_pck_location').text(pck.data('fulladdress'));
                    } else {
                        $('#updt_pck_location').text('');
                    }
                });
                $('#updt_drop').on('change', function() {
                    let drop = $('#updt_drop :selected');
                    if (drop && drop != '') {
                        $('#updt_drop_location').text(drop.data('fulladdress'));
                    } else {
                        $('#updt_drop_location').text('');
                    }
                });
                $('#divUpdtCheckpoint').on('change', 'select[name="updt_start_checkpoints[]"]', function (e) {
                    let trgt = $(e.target);
                    let idx = trgt.data('idx');
                    if (trgt && trgt.val() != '') {
                        $(`#divRowUpdtCheckpoint${idx}`).find('.updt_pck_location_checkpoints').text(trgt.children(':selected').data('fulladdress'));
                    } else {
                        $(`#divRowUpdtCheckpoint${idx}`).find('.updt_pck_location_checkpoints').text('');
                    }
                });
                $('#divUpdtCheckpoint').on('change', 'select[name="updt_end_checkpoints[]"]', function (e) {
                    let trgt = $(e.target);
                    let idx = trgt.data('idx');
                    if (trgt && trgt.val() != '') {
                        $(`#divRowUpdtCheckpoint${idx}`).find('.updt_drop_location_checkpoints').text(trgt.children(':selected').data('fulladdress'));
                    } else {
                        $(`#divRowUpdtCheckpoint${idx}`).find('.updt_drop_location_checkpoints').text('');
                    }
                });
                // input
                $('#updt_price').on('keyup', function() {
                    let price = Number($('#updt_price').val().split('.').join('').split(',').join('.'));
                    $('#updt_price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                $('#divUpdtCheckpoint').on('keyup', 'input[name="updt_price_checkpoints[]"]', function(e) {
                    let trgt = $(e.target);
                    let price = Number(trgt.val().split('.').join('').split(',').join('.'));
                    trgt.val((new Intl.NumberFormat('id-ID')).format(price));
                });
            },
            reDataZone: function() {
                $('#updt_pck').html('<option value="">Lokasi Pickup</option>');
                for (let pck of State.l_pickups) {
                    $('#updt_pck').append(`<option value="${pck.id}">${pck.name}</option>`);
                }
                $('#updt_pck').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
                $('#updt_drop').html('<option value="">Lokasi Drop</option>');
                for (let drop of State.l_drops) {
                    $('#updt_drop').append(`<option value="${drop.id}">${drop.name}</option>`);
                }
                $('#updt_drop').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
            },
            reqData: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_show_pocket', '') }}/" + params.pocket_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_pck').val(data.pck_id).trigger('change');
                // $('#updt_pck_location').val(data.pck_fulladdress).trigger('change');
                $('#updt_drop').val(data.drop_id).trigger('change');
                // $('#updt_drop_location').val(data.drop_fulladdress).trigger('change');

                if (data.type == State.pocket_type.bundle) {
                    $('#updt_price').val(data.checkpoints[0].total).trigger('keyup');
                } else {
                    $('#updt_price').val(0);
                }

                if (data.type == State.pocket_type.checkpoints) {
                    for (let i in data.checkpoints) {
                        if (i != 0) {
                            PUpdtCheckpoint.add();
                            PUpdtCheckpoint.reTriggerSel2();
                        }
                        $($('select[name="updt_start_checkpoints[]"]')[i]).val(data.checkpoints[i].pck_id).trigger('change');
                        $($('input[name="updt_price_checkpoints[]"]')[i]).val(data.checkpoints[i].total).trigger('keyup');
                    }
                }

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

                $('#mdlEdtPocket').data('id', data.id);
                $('#mdlEdtPocket').modal('show');
            },
            getData: function() {
                let data = Helper.objectifyForm($('#formUpdt').serializeArray());
                data.updt_price = Number(data.updt_price.split('.').join('').split(',').join('.'));

                if (typeof data.updt_price_checkpoints !== 'undefined') {
                    for (let i in data.updt_price_checkpoints) {
                        data.updt_price_checkpoints[i] = Number(data.updt_price_checkpoints[i].split('.').join('').split(',').join('.'));
                    }
                }

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

                data.pocket_id = $('#mdlEdtPocket').data('id');

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

                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitEdtPocket').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitEdtPocket').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_edit_pocket', '') }}/" + data.pocket_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) => {
                            $('#btnSubmitEdtPocket').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'success update pocket');
                            $('#mdlEdtPocket').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitEdtPocket').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 PUpdtCheckpoint = {
            activate: async function() {
                PUpdtCheckpoint.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 checkpoint');
                        return false;
                    }
                    trgt.closest('.divRowUpdtCheckpoint').remove();
                });
                $('#updt-point-add-row').on('click', function() {
                    PUpdtCheckpoint.add();
                });
            },
            reTriggerSel2: function () {
                $('select[name="updt_start_checkpoints[]"]').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
                $('select[name="updt_end_checkpoints[]"]').select2({
                    dropdownParent: $('#mdlEdtPocket'),
                });
            },
            add: function () {
                let pck_checkpoints = '', drop_checkpoints = '';

                for (let pck of State.pck_checkpoints) {
                    pck_checkpoints += `<option value="${pck.id}" data-name="${pck.name}" data-fulladdress="${pck.fulladdress}">${pck.name}</option>`;
                }

                // for (let drop of State.drop_checkpoints) {
                //     drop_checkpoints += `<option value="${drop.id}" data-name="${drop.name}" data-fulladdress="${drop.fulladdress}">${drop.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-6">
                        <div class="row">
                            <div class="col-12 mb-1">
                                <label for="updt_start_checkpoints[]" class="col-form-label">Titik Lokasi<span class="text-danger">*</span></label>
                                <select name="updt_start_checkpoints[]" class="form-control" style="width:100%;" data-idx="${nextIdx}">
                                    <option value="">Pilih Checkpoint</option>
                                    ${pck_checkpoints}
                                </select>
                                <p class="updt_pck_location_checkpoints mb-0">&nbsp;</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-md-5">
                        <label for="updt_price_checkpoints[]" class="col-form-label">Harga</label>
                        <input type="text" name="updt_price_checkpoints[]" class="form-control" value="0">
                    </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);

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

        const PDel = {
            activate: function() {
                PDel.event();
            },
            event: function() {
                // on table
                $('#tPocket').on('click', '.btnDelPocket', function(e) {
                    let row = $(e.target).closest('tr');
                    let id = row.find('td[data-id]').data('id');
                    let pck_name = row.find('td[data-pck_name]').data('pck_name');
                    let pck_fulladdress = row.find('td[data-pck_fulladdress]').data('pck_fulladdress');
                    // let drop_name = row.find('td[data-drop_name]').data('drop_name');
                    // let drop_fulladdress = row.find('td[data-drop_fulladdress]').data('drop_fulladdress');
                    PDel.passDataToView({
                        pocket_id: id,
                        pck_name,
                        pck_fulladdress,
                        // drop_name,
                        // drop_fulladdress,
                    });
                    $('#mdlDelPocket').data('id', id);
                    $('#mdlDelPocket').modal('show');
                });
                $('#btnSubmitDelPocket').on('click', function() {
                    let data = {
                        pocket_id: $('#mdlDelPocket').data('id'),
                    };
                    PDel.submitData(data);
                });
                // on modal update
                $('#btnDelPocket_updt').on('click', function (e) {
                    let data = PUpdt.getData();
                    PDel.passDataToView({
                        pocket_id: data.pocket_id,
                        // code: '',
                    });
                    $('#mdlDelPocket').data('id', data.pocket_id);
                    $('#mdlDelPocket').modal('show');
                });
            },
            passDataToView: function(data) {
                $('#del-pck_name').text(data.pck_name);
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelPocket').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelPocket').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_del_pocket', '') }}/" + data.pocket_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) => {
                            $('#btnSubmitDelPocket').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 pocket');
                            $('#mdlDelPocket').modal('hide');
                            $('#mdlEdtPocket').modal('hide');
                            DTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelPocket').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
