@extends('app.app')
@section('title')
    Finance - Payment
@endsection

@section('customcss')
    <style>
        .tepiBottom {
            border-bottom: 1.5px groove #000;
            padding-bottom: 15px;
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                <div class="col-sm-4" id="">
                    @foreach ($orders as $iOrd => $order)
                        <div class="card">
                            <div class="card-header">
                                <div class="row d-flex align-items-center">
                                    <div class="col">
                                        <p class="card-title text-bold mb-0">Detail Pesanan (#{{ $order->ord_code }})</p>
                                        <p class="mb-0" style="margin-top: 0.25rem;">
                                            @if ($order->crt_type_order === \App\Models\Orders::CRT_TYPE_ORDER_ADMIN_SPECIAL)
                                                <span class="badge bg-warning text-dark">Pesanan Khusus</span>
                                            @endif
                                        </p>
                                    </div>
                                    <div class="col text-end">
                                        <button class="btn btn-secondary btn-sm" onclick="location.href='{{ route('view_keuangan_payment') }}'">Kembali</button>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body pb-0">
                                <div class="row d-flex">
                                    <div class="col-5 mb-3">
                                        <div class="row">
                                            <div class="col-sm-12 mb-3">
                                                <p class="text-danger text-bold mb-0">Penjemputan dan Pengantaran</p>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Tanggal Penjemputan</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        <p class="mb-0"><span id="view{{ $iOrd }}-pickup_date_at">22 Apr
                                                                2022</span></p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Waktu Penjemputan</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        <p class="mb-0"><span id="view{{ $iOrd }}-pickup_time_at">19.20</span>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-2"></div>
                                    <div class="col-sm-5 mb-3">
                                        <div class="row">
                                            <div class="col-sm-12 col-12 mb-3">
                                                <p class="text-danger text-bold mb-0">Layanan Yang Dipilih</p>
                                            </div>
                                            <div class="col-sm-12 col-6 mb-3">
                                                <label for="" class="form-label">Durasi Pengantaran & Harga Vendor</label>
                                                <div class="card bg-light border mb-0 w-100">
                                                    <div class="card-body d-flex justify-content-between">
                                                        <p class="mb-0">{{ $order->lead_time }} Hari</p>
                                                        <p class="mb-0">
                                                            Rp{{ number_format($order->buy_price, 0, ',', '.') }}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12 col-6 mb-3">
                                                <label for="" class="form-label">Tipe Kendaraan</label>
                                                <div class="card bg-light border mb-0 w-100">
                                                    <div class="card-body d-flex justify-content-between">
                                                        {{-- <p class="mb-0">{{ $order->prefer_truck_type_name }}</p> --}}
                                                        <p class="mb-0">{{ $order->vhc_type_name }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row mb-3 d-flex align-items-center">
                                    <div class="col-5 mb-3">
                                        <label for="" class="form-label">Lokasi Penjemputan</label>
                                        <div class="card bg-light border mb-0">
                                            <div class="card-body">
                                                {{-- <p class="text-bold mb-2">Gudang Pluit SiCepat (Jakarta)</p> --}}
                                                <p class="text-bold mb-2">{{ $order->pck_name }}</p>
                                                {{-- <p class="mb-0">Jl. Pluit Karang Karya 2 No.33, RT.7/RW.16, Pejagalan, Kec. Penjaringan, Kota Jkt Utara, Daerah Khusus Ibukota Jakarta 14440</p> --}}
                                                <p class="mb-0">{{ $order->pck_addr }}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-2 text-center">
                                        <label for="" class="form-label mb-0 mt-0">&nbsp;</label>
                                        {{-- <p class="mb-0">to</p> --}}
                                        <span class="ion-arrow-right-c text-danger" style="font-size: 15px"></span>
                                    </div>
                                    <div class="col-5 mb-3">
                                        <label for="" class="form-label">Lokasi Pengantaran</label>
                                        <div class="card bg-light border mb-0">
                                            <div class="card-body">
                                                {{-- <p class="text-bold mb-2">Kantor Pusat SiCepat (yogyakarta)</p> --}}
                                                <p class="text-bold mb-2">{{ $order->drop_name }}</p>
                                                {{-- <p class="mb-0">Jl. Prof. Herman Yohanes No.989, Terban, Gondokusuman, Kota Yogyakarta, Daerah Istimewa Yogyakarta 55223, Indonesia</p> --}}
                                                <p class="mb-0">{{ $order->drop_addr }}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                @foreach ($order->adtPoints as $i => $p)
                                    <div class="row d-flex align-items-center">
                                        <div class="col-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Infomasi Penjemputan dan Pengantaran Lainnya ({{ $i + 2 }})</p>
                                        </div>
                                        <div class="col-5 mb-3">
                                            <div class="row">
                                                <div class="col-12 mb-3">
                                                    <label for="" class="form-label">Tanggal Penjemputan</label>
                                                    <div class="card bg-light border mb-0">
                                                        <div class="card-body">
                                                            <p class="mb-0"><span id="view{{ $iOrd }}-pickup_date_at{{ $i + 1 }}"></span></p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <label for="" class="form-label">Waktu Penjemputan</label>
                                                    <div class="card bg-light border mb-0">
                                                        <div class="card-body">
                                                            <p class="mb-0"><span id="view{{ $iOrd }}-pickup_time_at{{ $i + 1 }}"></span></p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row mb-3 d-flex align-items-center">
                                        <div class="col-5 mb-3">
                                            <label for="" class="form-label">Lokasi Penjemputan</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="text-bold mb-2">{{ $p->pck_name }}</p>
                                                    <p class="mb-0">{{ $p->pck_addr }}</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-2 text-center">
                                            <label for="" class="form-label mb-0 mt-0">&nbsp;</label>
                                            {{-- <p class="mb-0">to</p> --}}
                                            <span class="ion-arrow-right-c text-danger" style="font-size: 15px"></span>
                                        </div>
                                        <div class="col-5 mb-3">
                                            <label for="" class="form-label">Lokasi Pengantaran</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="text-bold mb-2">{{ $p->drop_name }}</p>
                                                    <p class="mb-0">{{ $p->drop_addr }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                                <div class="row">
                                    <div class="col-sm-5">
                                        <div class="row d-flex align-items-center mb-3">
                                            <div class="col-12 mb-3">
                                                <p class="text-danger text-bold mb-0">Infomasi Vendor</p>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Nama Vendor</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        {{-- <p class="mb-0">CV Karya Expedisi Bangsa</p> --}}
                                                        @if ($order->vdr_name)
                                                            <p class="mb-0">{{ $order->vdr_name }}</p>
                                                        @else
                                                            <p class="mb-0 text-primary">belum ditugaskan</p>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Kendaraan</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        @if ($order->vhc_nopol1)
                                                            <p class="mb-0">
                                                                {{ $order->vhc_nopol1 . ' ' . $order->vhc_nopol2 . ' ' . $order->vhc_nopol3 }}
                                                            </p>
                                                        @else
                                                            <p class="mb-0 text-primary">belum ditugaskan</p>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Nama Pengemudi 1</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        @if ($order->drv_name)
                                                            <p class="mb-0"> {{ $order->drv_name }} </p>
                                                            <p class="mb-0">
                                                                <a href="tel:0{{ $order->drv_phone_val }}">
                                                                    <i class="text-dark ion-ios-telephone"></i>&nbsp;
                                                                    {{ implode(' ', str_split('0' . $order->drv_phone_val, 4)) }}
                                                                </a>
                                                            </p>
                                                            <p class="mb-0">
                                                                <a href="https://api.whatsapp.com/send/?phone=62{{ $order->drv_phone_val }}&text=Halo&app_absent=0" class="" target="_blank"><i class="text-success ion-social-whatsapp"></i>
                                                                    {{ implode(' ', str_split('0' . $order->drv_phone_val, 4)) }}</a>
                                                            </p>
                                                        @else
                                                            <p class="mb-0 text-primary">belum ditugaskan</p>
                                                        @endif
                                                    </div>
                                                </div>
                                                @if ($order->drv_name2)
                                                    <label for="" class="form-label">Nama Pengemudi 2</label>
                                                    <div class="card bg-light border mb-0">
                                                        <div class="card-body">
                                                            @if ($order->drv_name2)
                                                                <p class="mb-0"> {{ $order->drv_name2 }} </p>
                                                                <p class="mb-0">
                                                                    <a href="tel:0{{ $order->drv_phone2_val }}">
                                                                        <i class="text-dark ion-ios-telephone"></i>&nbsp;
                                                                        {{ implode(' ', str_split('0' . $order->drv_phone2_val, 4)) }}
                                                                    </a>
                                                                </p>
                                                                <p class="mb-0">
                                                                    <a href="https://api.whatsapp.com/send/?phone=62{{ $order->drv_phone2_val }}&text=Halo&app_absent=0" class="" target="_blank"><i class="text-success ion-social-whatsapp"></i>
                                                                        {{ implode(' ', str_split('0' . $order->drv_phone2_val, 4)) }}</a>
                                                                </p>
                                                            @else
                                                                <p class="mb-0 text-primary">belum ditugaskan</p>
                                                            @endif
                                                        </div>
                                                    </div>
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
                <div class="col-sm-8">
                    {{-- old view pembayaran --}}
                    {{-- <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Pembayaran</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-body pb-0">
                            <div class="row">
                                <div class="col-sm-5">
                                    <div class="row d-flex align-items-center mb-3">
                                        <div class="col-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Infomasi Bank</p>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Akun Bank</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0">Bank Central Asia (BCA)</p>
                                                    <p class="mb-0">5270860721</p>
                                                    <p class="mb-0">A/N. Karya Expedisi Bangsa CV</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-2">&nbsp;</div>
                                <div class="col-sm-5">
                                    <div class="row d-flex align-items-center mb-3">
                                        <div class="col-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Catatan</p>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Catatan Finance</label>
                                            <textarea name="" id="" cols="30" rows="4" class="form-control radius"></textarea>
                                            <button class="btn btn-sm btn-primary mt-3">Save</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12 mb-3">
                                    <p class="text-danger text-bold mb-0">Pembayaran</p>
                                </div>
                                <div class="col-sm-5">
                                    <div class="row d-flex align-items-center mb-3">
                                        <div id="term1Wrapper">
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Pembayaran Termin I</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        <p class="mb-0">Rp721.000</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12 mb-3">
                                                <label for="" class="form-label">Tenggang Waktu Pembayaran</label>
                                                <div class="card bg-light border mb-0">
                                                    <div class="card-body">
                                                        <div class="d-flex align-items-center justify-content-between">
                                                            <p class="mb-0">22 Apr 2022 17:18</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-12">
                                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#mdlTerm1">Bayar</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-5 offset-sm-2">
                                    <div class="row d-flex align-items-center mb-3">
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Pembayaran Termin II</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0">Rp309.000</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Tenggang Waktu Pembayaran</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <div class="d-flex align-items-center justify-content-between">
                                                        <p class="mb-0 text-danger">Menunggu pengantaran selesai.</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div> --}}
                    {{-- berkas driver --}}
                    @if (count($drvs_ups) > 0)
                        <div class="accordion mb-3">
                            <div class="accordion-item border-0 radius-8">
                                <h2 class="accordion-header" id="panelsStayOpen-headingFive">
                                    <button class="accordion-button radius-8 collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseFive" aria-expanded="false" aria-controls="panelsStayOpen-collapseFive">
                                        Berkas Driver
                                    </button>
                                </h2>
                                <div id="panelsStayOpen-collapseFive" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingFive">
                                    <div class="accordion-body pb-0">
                                        <div class="row">
                                            @php
                                                $afterTravelDoc = 0;
                                            @endphp
                                            @foreach ($drvs_ups as $i => $drvUp)
                                                @if ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_ARRIVED_PICKUP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Sampai dilokasi Pickup</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_PROCESS_PICKUP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Mulai Memuat Barang</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_FINISH_PICKUP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Selesai Memuat</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_TRAVEL_DOCUMENT)
                                                    @php
                                                        $afterTravelDoc = 1;
                                                    @endphp
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Dokumen Perjalanan</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_OTW_DROP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Saat diperjalanan</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_ARRIVED_DROP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Tiba dilokasi Bongkar</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_PROCESS_DROP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Proses Bongkar</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_FINISH_DROP)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Selesai Bongkar</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_HANDOVER_DOCUMENT)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Serah Terima</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @elseif ($drvUp->stts === \App\Models\OrdersDriversUploads::STTS_UP_ACCIDENT)
                                                    <div class="col-12 mb-3 tepiBottom">
                                                        <div class="d-flex justify-content-between">
                                                            <div><label for="" class="form-label fw-bold">Foto Mengalami Trouble / Kecelakaan</label></div>
                                                            <div><label for="" class="form-label fw-bold foto-crt" data-crt="{{ $drvUp->crt }}"></label></div>
                                                        </div>
                                                        <div class="card bg-light border mb-0">
                                                            <div class="card-body p-0">
                                                                <img src="{{ isset($drvUp->img) ? \App\Helper::changeIpToDomain($drvUp->img) : 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDVPuMlKfGrFErmCt6hCuECLbbhekJF-GCtAJvPIZpHX5upTT-hABFlp8qZY8rkgaZ0DE&usqp=CAU' }}" alt="" class="img-fluid img-report">
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endif
                                                @if ($order->is_aprv_pck === \App\Models\OrdersPckDrop::IS_APRV_YES && $afterTravelDoc === 1)
                                                    <div class="col-auto mb-3 fw-bold">
                                                        {{-- <p class="mb-0 text-success">Disetujui {{ strftime('%d-%m-%Y %H:%M:%S', $order->aprv_pck_at).' WIB' }}</p> --}}
                                                        <p class="mb-0 text-success">Disetujui <span id="aprvPckAt"></span></p>
                                                        <p class="mb-0 text-dark">Oleh {{ $order->aprv_pck_by_name }}</p>
                                                    </div>
                                                @endif
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif
                    {{-- additional items --}}
                    <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Pembayaran</p>
                                </div>
                                <div class="col-auto text-end ps-0">
                                    {{-- <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#mdlAddItem">Tambah Item</button> --}}
                                    <button id="btnMdlNewAdtItem" class="btn btn-sm btn-primary">Tambah Item</button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive mb-3">
                                <table class="table table-striped" id="tblAdditional">
                                    <thead>
                                        <tr class="">
                                            <th class="text-center">#</th>
                                            <th class="text-center"></th>
                                            <th class="w-50">Deskripsi</th>
                                            <th class="text-center">Jumlah</th>
                                            <th class="text-center">Tenggat Waktu</th>
                                            <th class="text-nowrap">Bayarkan ke</th>
                                            <th class="">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="">
                                            <td class="text-center small">1</td>
                                            <td class="text-center" id="tblColAction">
                                                <a href="javascript:void(0)" class="btn btn-primary btn-sm text-nowrap small w-100" data-bs-toggle="modal" data-bs-target="#mdlpayAdd">Bayar</a>
                                            </td>
                                            <td class="small">Biaya inap kendaraan</td>
                                            <td class="text-nowrap small text-end">Rp350.000</td>
                                            <td class="text-nowrap small">23 Apr 2022 06:00</td>
                                            <td class="">
                                                <p class="mb-0 text-nowrap small">Bank Central Asia (BCA)</p>
                                                <p class="mb-0 text-nowrap small">5270860721</p>
                                                <p class="mb-0 text-nowrap small">A/N. Karya Expedisi Bangsa CV</p>
                                            </td>
                                            <td class="text-nowrap" id="tblColStatus">
                                                <p class="text-danger mb-0 text-nowrap small">Belum Bayar</p>
                                            </td>
                                        </tr>
                                        <tr class="">
                                            <td class="text-center small">2</td>
                                            <td class="text-center small">
                                                <a href="javascript:void(0)" class="text-nowrap text-success" data-bs-toggle="modal" data-bs-target="#mdlViewAdd">Lihat Bukti</a>
                                            </td>
                                            <td class="small">Biaya pengemudi tambahan</td>
                                            <td class="text-nowrap small text-end">Rp530.000</td>
                                            <td class="text-nowrap small">23 Apr 2022 04:00</td>
                                            <td class="">
                                                <p class="mb-0 text-nowrap small">Bank Central Asia (BCA)</p>
                                                <p class="mb-0 text-nowrap small">5270860721</p>
                                                <p class="mb-0 text-nowrap small">A/N. Karya Expedisi Bangsa CV</p>
                                            </td>
                                            <td class="text-nowrap">
                                                <p class="mb-0 text-success text-nowrap small">Lunas</p>
                                                <p class="mb-0 text-nowrap small text-muted">23 Apr 2022 06:00</p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="row d-flex align-items-center mb-3">
                                <div class="col-12">
                                    <p class="card-title text-bold mb-0">Arsip Pembayaran</p>
                                </div>
                            </div>
                            <div class="row d-flex align-items-center mb-3">
                                <div class="col-12">
                                    <div class="table-responsive mb-3">
                                        <table class="table table-striped" id="tblAdditionalArchv">
                                            <thead>
                                                <tr class="">
                                                    <th class="text-center">#</th>
                                                    <th class="text-center"></th>
                                                    <th class="w-50">Deskripsi</th>
                                                    <th class="text-center">Jumlah</th>
                                                    <th class="text-center">Tenggat Waktu</th>
                                                    <th class="text-nowrap">Bayarkan ke</th>
                                                    <th class="">Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr class="">
                                                    <td class="text-center small">1</td>
                                                    <td class="text-center" id="tblColAction">
                                                        <a href="javascript:void(0)" class="btn btn-primary btn-sm text-nowrap small w-100" data-bs-toggle="modal" data-bs-target="#mdlpayAdd">Bayar</a>
                                                    </td>
                                                    <td class="small">Biaya inap kendaraan</td>
                                                    <td class="text-nowrap small text-end">Rp350.000</td>
                                                    <td class="text-nowrap small">23 Apr 2022 06:00</td>
                                                    <td class="">
                                                        <p class="mb-0 text-nowrap small">Bank Central Asia (BCA)</p>
                                                        <p class="mb-0 text-nowrap small">5270860721</p>
                                                        <p class="mb-0 text-nowrap small">A/N. Karya Expedisi Bangsa CV</p>
                                                    </td>
                                                    <td class="text-nowrap" id="tblColStatus">
                                                        <p class="text-danger mb-0 text-nowrap small">Belum Bayar</p>
                                                    </td>
                                                </tr>
                                                <tr class="">
                                                    <td class="text-center small">2</td>
                                                    <td class="text-center small">
                                                        <a href="javascript:void(0)" class="text-nowrap text-success" data-bs-toggle="modal" data-bs-target="#mdlViewAdd">Lihat Bukti</a>
                                                    </td>
                                                    <td class="small">Biaya pengemudi tambahan</td>
                                                    <td class="text-nowrap small text-end">Rp530.000</td>
                                                    <td class="text-nowrap small">23 Apr 2022 04:00</td>
                                                    <td class="">
                                                        <p class="mb-0 text-nowrap small">Bank Central Asia (BCA)</p>
                                                        <p class="mb-0 text-nowrap small">5270860721</p>
                                                        <p class="mb-0 text-nowrap small">A/N. Karya Expedisi Bangsa CV</p>
                                                    </td>
                                                    <td class="text-nowrap">
                                                        <p class="mb-0 text-success text-nowrap small">Lunas</p>
                                                        <p class="mb-0 text-nowrap small text-muted">23 Apr 2022 06:00</p>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            @if ($orders[0]->stts_merge === \App\Models\Orders::STTS_MERGE_RESULT)
                                <div class="row d-flex align-items-center mb-3">
                                    <div class="col">
                                        <p class="text-danger text-bold mb-0">Catatan Merge</p>
                                        <p class="text-muted mb-0">Di merge pada <span id="view-merge_at"></span></p>
                                        <p class="text-muted mb-0">{{ $orders[0]->merge_note }}</p>
                                    </div>
                                </div>
                            @endif
                            <div class="row d-flex align-items-center mb-3">
                                @foreach ($orders as $iOrd => $order)
                                    <div class="col">
                                        {{-- <label for="fnnc-note{{ $iOrd }}" class="form-label">Catatan Finance</label> --}}
                                        <p class="text-danger text-bold mb-0">Catatan Finance #{{ $order->ord_code }}</p>
                                        <textarea name="fnnc-note{{ $iOrd }}" id="fnnc-note{{ $iOrd }}" data-ord_id="{{ $order->ord_id }}" cols="30" rows="2" class="form-control radius">{{ $order->fnnc_note }}</textarea>
                                        <button id="btnSaveFnncNote{{ $iOrd }}" class="btn btn-sm btn-primary mt-3">Save</button>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Modal Term 1 --}}
    <div class="modal" id="mdlTerm1" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlTerm1Label" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlTerm1Label"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="" class="form-label">Unggah Bukti Pembayaran</label>
                        <input class="form-control" type="file" id="">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSaveTerm1">Save</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="mdlpayAdd" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlpayAddLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlpayAddLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="up_paid_ref_no">Nomor Referensi <span class="text-danger">*</span></label>
                        <input type="number" id="up_paid_ref_no" name="up_paid_ref_no" class="form-control">
                        <small>Bisa didapatkan dari vendor, bisa berupa no invoice atau lainnya terkait nomor pembayaran</small>
                    </div>
                    <div class="mb-3">
                        <label for="up_paid_proof" class="col-form-label">Unggah Bukti Pembayaran <span class="text-danger">*</span></label>
                        <br>
                        <img id="inpt-up_paid_proof-img" class="img-fluid d-none" src="#" alt="inpt-up_paid_proof-img">
                        <div id="inpt-group_up_paid_proof_spinner" class="d-none">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                        <div>
                            <span id="inpt-up_paid_proof-status" class="d-none"></span>
                            <span id="inpt-up_paid_proof-filesize" class="d-none"></span>
                        </div>
                        <div id="inpt-group_rotate_up_paid_proof" class="pt-2 d-flex justify-content-start d-none">
                            <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                            <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                        </div>
                        <input type="file" id="inpt-up_paid_proof-file" class="form-control form-control-sm">
                        <input type="text" id="inpt-up_paid_proof-base64" class="form-control" hidden>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnPayAdd">Save</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="mdlViewAdd" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlViewAddLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlViewAddLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="groupViewPaidRefNo" class="row mb-3">
                        <div class="col-12">
                            <label><strong>Nomor Referensi</strong></label>
                            <p id="view-paid_ref_no" class="mb-0"></p>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-12">
                            <label><strong id="txtProofOrSubmsn">Bukti Pembayaran</strong></label>
                            <br>
                            {{-- <img id="imgViewProofImg" src="https://i.pinimg.com/736x/a5/0e/5e/a50e5e839949d2f19271d83c12bd0abc.jpg" class="img-fluid" alt="" /> --}}
                            <embed id="imgViewProofImg" src="https://i.pinimg.com/736x/a5/0e/5e/a50e5e839949d2f19271d83c12bd0abc.jpg" style="width:100%;height:100%;" />
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    {{-- ./Modal Term 1 --}}

    {{-- Modal Item --}}
    <div class="modal" id="mdlAddItem" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlAddItemLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlAddItemLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="addSlcTrxCode" class="mb-3 {{ count($orders) > 1 ? '' : 'd-none' }}">
                        <label for="slcTrxCode" class="form-label w-100">Masukkan ke transaksi <span class="text-danger">*</span></label>
                        <select name="slcTrxCode" id="slcTrxCode" class="select2 form-control" style="width: 100% !important">
                            @foreach ($orders as $order)
                                <option value="{{ $order->ord_code }}" data-ord_id="{{ $order->ord_id }}" data-ord_code="{{ $order->ord_code }}">{{ $order->ord_code }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div id="addSlcItemWrapper" class="mb-3">
                        <label for="slcItem" class="form-label w-100">Pilih Item <span class="text-danger">*</span></label>
                        <select name="slcItem" id="slcItem" class="select2 form-control" style="width: 100% !important">
                            <option value="" selected disabled>Belum ada item yang dipilih</option>
                            @foreach ($items as $item)
                                <option value="{{ $item->id }}" data-name="{{ $item->name }}" data-type="{{ $item->type }}" data-price="{{ $item->price }}" data-is_adm_price="{{ $item->is_adm_price }}">{{ $item->name }}</option>
                            @endforeach
                            <option value="new"><span class="text-danger">Tambah item baru</span></option>
                        </select>
                        <small id="slcItemPrice"></small>
                    </div>
                    <div id="addNewItemWrapper" class="d-none">
                        <div class="mb-3">
                            <label for="add-item_name" class="form-label">Nama Item <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_name" id="add-item_name" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label for="add-item_type" class="form-label">Satuan <span class="text-danger">*</span></label>
                            <select name="add-item_type" id="add-item_type" class="select2 form-control" style="width: 100% !important">
                                <option value="" selected disabled>Belum ada satuan yang dipilih</option>
                                @foreach ($unitTypes as $type)
                                    <option value="{{ $type->id }}">{{ $type->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label for="add-item_price" class="form-label">Harga Satuan <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_price" id="add-item_price" class="form-control">
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" name="add-item_isAdmPrice" type="checkbox" value="yes" id="add-item_isAdmPrice">
                                <label class="form-check-label text-danger" for="add-item_isAdmPrice">
                                    Biaya admin bank ?
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="add-item_tax_type" class="form-label">Perpajakan <span class="text-danger">*</span></label>
                        <select name="add-item_tax_type" id="add-item_tax_type" class="select2 form-control" style="width: 100% !important">
                            {{-- <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_WITHOUT }}">Tanpa Pajak</option> --}}
                            <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE }}">Belum Termasuk Pajak</option>
                            <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE }}">Sudah Termasuk Pajak</option>
                        </select>
                    </div>
                    <div class="row mb-3 groupPpn d-none">
                        <div class="col">
                            <label for="add-item_tax_ppn_percent" class="form-label">Percent PPN % <span class="text-danger">*</span></label>
                            <input type="number" name="add-item_tax_ppn_percent" id="add-item_tax_ppn_percent" class="form-control" readonly>
                        </div>
                        <div class="col">
                            <label for="add-item_tax_ppn_flat" class="form-label">Harga PPN (Rp) <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_tax_ppn_flat" id="add-item_tax_ppn_flat" class="form-control" readonly>
                        </div>
                    </div>
                    <div class="row mb-3 groupTax d-none">
                        <div class="col">
                            <label for="add-item_tax_pph_percent" class="form-label">Percent PPH % <span class="text-danger">*</span></label>
                            <input type="number" name="add-item_tax_pph_percent" id="add-item_tax_pph_percent" class="form-control" readonly>
                        </div>
                        <div class="col">
                            <label for="add-item_tax_pph_flat" class="form-label">Harga PPH (Rp) <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_tax_pph_flat" id="add-item_tax_pph_flat" class="form-control" readonly>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="add-item_tax_total_flat" class="form-label">Harga Setelah Kalkulasi Pajak (Rp) <span class="text-danger">*</span></label>
                        <input type="text" name="add-item_tax_total_flat" id="add-item_tax_total_flat" class="form-control" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="add-item_qty" class="form-label">Jumlah Item <span class="text-danger">*</span></label>
                        <input type="number" name="add-item_qty" id="add-item_qty" class="form-control">
                    </div>
                    <div id="groupFillDdln" class="d-none">
                        <div class="mb-3">
                            <label for="ddln_pay_date" class="form-label">Tenggat Tanggal Pembayaran <span class="text-danger">*</span></label>
                            <input type="date" name="ddln_pay_date" id="ddln_pay_date" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label for="add-ddln_pay_time" class="form-label text-nowrap">Tenggat Waktu Pembayaran <span class="text-danger">*</span></label>
                            <div class="row">
                                <div class="col-sm-6 col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                    <select name="ddln_pay_time_hour" id="ddln_pay_time_hour" class="form-control">
                                        <option value="" selected disabled hidden>--</option>
                                        @for ($i = 0; $i < 24; $i++)
                                            <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                        @endfor
                                    </select>
                                </div>
                                <div class="col-sm-6 col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                    <select name="ddln_pay_time_minute" id="ddln_pay_time_minute" class="form-control">
                                        <option value="" selected disabled hidden>--</option>
                                        @for ($i = 0; $i < 60; $i++)
                                            <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                        @endfor
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="groupSubmissionProof">
                        <div class="mb-3">
                            <label for="submission_proof" class="col-form-label">Unggah Bukti Pengajuan <span class="text-danger">*</span></label>
                            <br>
                            <img id="inpt-submission_proof-img" class="img-fluid d-none" src="#" alt="inpt-submission_proof-img">
                            <div id="inpt-group_submission_proof_spinner" class="d-none">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                            </div>
                            <div>
                                <span id="inpt-submission_proof-status" class="d-none"></span>
                                <span id="inpt-submission_proof-filesize" class="d-none"></span>
                            </div>
                            <div id="inpt-group_rotate_submission_proof" class="pt-2 d-flex justify-content-start d-none">
                                <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                            </div>
                            <input type="file" id="inpt-submission_proof-file" class="form-control form-control-sm">
                            <input type="text" id="inpt-submission_proof-base64" class="form-control" hidden>
                        </div>
                    </div>
                    <div id="groupPayPurpose" class="mb-3">
                        <label for="slcPayPurpose" class="form-label">Tujuan Pembayaran</label>
                        <select name="slcPayPurpose" id="slcPayPurpose" class="select2 form-control" style="width: 100% !important">
                            <option value="none" disabled>Tidak ada</option>
                            <option value="fill" selected>Isi data penerima</option>
                        </select>
                    </div>
                    <div id="fillReceiverWrapper">
                        <div class="mb-3">
                            <label for="bank" class="form-label">Bank <span class="text-danger">*</span></label>
                            <select id="bank" name="bank" class="form-control select2" style="width:100%;">
                                <option value="" selected disabled>Pilih</option>
                                @foreach ($banks as $bank)
                                    <option value="{{ $bank->bank_code }}" data-id="{{ $bank->id }}" data-code="{{ $bank->bank_code }}" data-short="{{ $bank->bank_short_name }}" data-name="{{ $bank->bank_name }}">{{ $bank->bank_short_name . ' (' . $bank->bank_code . ')' }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="bank_acc_number" class="form-label">Nomor Rekening <span class="text-danger">*</span></label>
                            <input type="number" class="form-control form-control-sm" name="bank_acc_number" id="bank_acc_number">
                        </div>
                        <div class="mb-3">
                            <label for="bank_acc_name" class="form-label">Pemilik Rekening <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-sm" name="bank_acc_name" id="bank_acc_name">
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-group">
                            <label for="is_paid" class="form-label">Status Pembayaran</label>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="is_paid">
                                <label class="form-check-label" for="is_paid"><span class="text-dark" id="txtIsPaid">Belum dibayar</span></label>
                            </div>
                        </div>
                        <div id="groupIsPaid" class="form-group d-none">
                            <div class="mb-3">
                                <label for="inpt-paid_proof_ref_no">Nomor Referensi <span class="text-danger">*</span></label>
                                <input type="number" id="inpt-paid_proof_ref_no" name="inpt-paid_proof_ref_no" class="form-control">
                                <small>Bisa didapatkan dari vendor, bisa berupa no invoice atau lainnya terkait nomor pembayaran</small>
                            </div>
                            <div class="mb-3">
                                <label for="is_paid_proof" class="col-form-label">Unggah Bukti Pembayaran <span class="text-danger">*</span></label>
                                <br>
                                <img id="inpt-is_paid_proof-img" class="img-fluid d-none" src="#" alt="inpt-is_paid_proof-img">
                                <div id="inpt-group_is_paid_proof_spinner" class="d-none">
                                    <div class="spinner-border" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </div>
                                <div>
                                    <span id="inpt-is_paid_proof-status" class="d-none"></span>
                                    <span id="inpt-is_paid_proof-filesize" class="d-none"></span>
                                </div>
                                <div id="inpt-group_rotate_is_paid_proof" class="pt-2 d-flex justify-content-start d-none">
                                    <button type="button" class="btnRotateLeft btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-left"></i></button>
                                    <button type="button" class="btnRotateRight btn btn-sm btn-outline-primary ml-1" style="padding:0.25rem 0.5rem;border-radius:0.25rem;"><i class="icon ion-arrow-return-right"></i></button>
                                </div>
                                <input type="file" id="inpt-is_paid_proof-file" class="form-control form-control-sm">
                                <input type="text" id="inpt-is_paid_proof-base64" class="form-control" hidden>
                            </div>
                            {{-- <div class="mb-3">
                                <label for="is_paid_date" class="form-label">Tanggal Dibayar <span class="text-danger">*</span></label>
                                <input type="date" name="is_paid_date" id="is_paid_date" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label for="is_paid_time" class="form-label text-nowrap">Waktu Dibayar <span class="text-danger">*</span></label>
                                <div class="row">
                                    <div class="col-sm-6 col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                        <select name="is_paid_time_hour" id="is_paid_time_hour" class="form-control">
                                            <option value="" selected disabled hidden>--</option>
                                            @for ($i = 0; $i < 24; $i++)
                                            <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                            @endfor
                                        </select>
                                    </div>
                                    <div class="col-sm-6 col-md-4 col-lg-3" style="padding:0 0 0 0.75rem;">
                                        <select name="is_paid_time_minute" id="is_paid_time_minute" class="form-control">
                                            <option value="" selected disabled hidden>--</option>
                                            @for ($i = 0; $i < 60; $i++)
                                            <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                                            @endfor
                                        </select>
                                    </div>
                                </div>
                            </div> --}}
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" name="invcToClient" type="checkbox" value="yes" id="invcToClient">
                            <label class="form-check-label text-danger" for="invcToClient">
                                Ditagihkan ke client ?
                            </label>
                        </div>
                    </div>
                    <div id="groupPriceToClient" class="d-none">
                        <div class="mb-3">
                            <label for="add-invc_item_price" class="form-label">Harga Satuan yang Ditagihkan <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-sm" name="add-invc_item_price" id="add-invc_item_price">
                        </div>
                        <div class="mb-3 d-none">
                            <label for="add-item_bill_tax_type" class="form-label">Perpajakan <span class="text-danger">*</span></label>
                            <select name="add-item_bill_tax_type" id="add-item_bill_tax_type" class="select2 form-control" style="width: 100% !important">
                                {{-- <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_WITHOUT }}">Tanpa Pajak</option> --}}
                                <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE }}">Belum Termasuk Pajak</option>
                                <option value="{{ App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE }}">Sudah Termasuk Pajak</option>
                            </select>
                        </div>
                        <div class="row mb-3 groupTaxBill d-none">
                            <div class="col">
                                <label for="add-item_bill_tax_ppn_percent" class="form-label">Percent PPN % <span class="text-danger">*</span></label>
                                <input type="number" name="add-item_bill_tax_ppn_percent" id="add-item_bill_tax_ppn_percent" class="form-control" readonly>
                            </div>
                            <div class="col">
                                <label for="add-item_bill_tax_ppn_flat" class="form-label">Harga PPN (Rp) <span class="text-danger">*</span></label>
                                <input type="text" name="add-item_bill_tax_ppn_flat" id="add-item_bill_tax_ppn_flat" class="form-control" readonly>
                            </div>
                        </div>
                        <div class="row mb-3 groupTaxBill d-none">
                            <div class="col">
                                <label for="add-item_bill_tax_pph_percent" class="form-label">Percent PPH % <span class="text-danger">*</span></label>
                                <input type="number" name="add-item_bill_tax_pph_percent" id="add-item_bill_tax_pph_percent" class="form-control" readonly>
                            </div>
                            <div class="col">
                                <label for="add-item_bill_tax_pph_flat" class="form-label">Harga PPH (Rp) <span class="text-danger">*</span></label>
                                <input type="text" name="add-item_bill_tax_pph_flat" id="add-item_bill_tax_pph_flat" class="form-control" readonly>
                            </div>
                        </div>
                        <div class="mb-3 d-none">
                            <label for="add-item_bill_tax_total_flat" class="form-label">Harga Setelah Kalkulasi Pajak (Rp) <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_bill_tax_total_flat" id="add-item_bill_tax_total_flat" class="form-control" readonly>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="btnDelItem_updt" class="btn btn-sm btn-warning">Hapus ?</button>
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSubmitAddItem">Save</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlDelItem" aria-labelledby="mdlDelItemLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlDelItemLabel">Hapus Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <p class="mb-0">
                            Apakah kamu yakin menghapus item ini
                            <a href="#" class="text-danger">
                                <span id="del-name"></span>
                            </a> ?
                        </p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitDelItem" type="button" class="btn btn-sm btn-secondary">Ya, hapus</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlRjctItem" aria-labelledby="mdlRjctItemLabel" 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="mdlRjctItemLabel">Tolak Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center">
                        <div class="row">
                            <div class="col-12">
                                <p class="mb-2">
                                    Apakah kamu yakin menolak item ini
                                    <a href="#" class="text-danger">
                                        <span id="reject-name"></span>
                                    </a> ?
                                </p>
                                <p class="mb-0">
                                    Diajukan oleh
                                    <a href="#" class="text-danger">
                                        <span id="reject-crt_name"></span>
                                    </a>
                                </p>
                                <p class="mb-0">
                                    Pada tanggal
                                    <a href="#" class="text-danger">
                                        <span id="reject-crt_at"></span>
                                    </a>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitRejectItem" type="button" class="btn btn-sm btn-secondary">Ya, tolak</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" id="mdlMrgItem" aria-labelledby="mdlMrgItemLabel" 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="mdlMrgItemLabel">Merge Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-center flex-column">
                        <div class="row mb-3">
                            <div class="col-12">
                                <p class="mb-2">
                                    Apakah kamu yakin melakukan merge pada item ini
                                    <a href="#" class="text-danger">
                                        <span id="mrg-name"></span>
                                    </a> ?
                                </p>
                                <p class="mb-0">
                                    Status pembayaran
                                <div id="mrg-stts_pay"></div>
                                </p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="mb-3">
                                    <label for="mrg-sel_trx_code" class="form-label">Merge ke transaksi <span class="text-danger">*</span></label>
                                    <select name="mrg-sel_trx_code" id="mrg-sel_trx_code" class="select2 form-control" style="width: 100% !important">
                                        <option value="" selected disabled>Belum ada transaksi yang dipilih</option>
                                        @foreach ($availOrdToMerge as $row)
                                            <option value="{{ $row->code }}" data-id="{{ $row->id }}" data-code="{{ $row->code }}">{{ $row->code }}</option>
                                        @endforeach
                                    </select>
                                    <small><span class="text-danger">Proses merge</span> adalah dimana item pada pembayaran ini akan dimunculkan pada transaksi tersebut.
                                        Namun <span class="text-danger">setelah proses merge</span> jika ada perubahan pada salah satu item, tidak akan mempengaruhi item lainnya.
                                        Melainkan <span class="text-danger">menjadi item yang independen</span> dengan catatan code dari item sebelumnya</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-bs-dismiss="modal">Close</button>
                    <button id="btnSubmitMergeItem" type="button" class="btn btn-sm btn-warning">Ya, merge</button>
                </div>
            </div>
        </div>
    </div>
    {{-- ./Modal Item --}}
@endsection

@section('customcss')
@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
    <script>
        // $('#tblAdditional').DataTable({
        //     "columnDefs": [{
        //         "targets": 1,
        //         "orderable": false
        //     }]
        // });
        $('#btnSaveTerm1').on('click', function() {
            let a = `
                <div class="col-sm-12 mb-3">
                    <div class="d-flex align-items-center justify-content-between">
                        <label for="" class="form-label">Pembayaran Termin I</label>
                        <label for="" class="form-label text-success"><span class="ion-checkmark-circled me-2"></span>Lunas</label>
                    </div>
                    <div class="card bg-light border mb-0">
                        <div class="card-body">
                            <img src="https://i.pinimg.com/736x/a5/0e/5e/a50e5e839949d2f19271d83c12bd0abc.jpg" class="img-fluid mb-3" alt="" />
                            <p class="mb-0">Dibayar pada 22 Apr 2022 17:18</p>
                        </div>
                    </div>
                </div>
            `
            $('#term1Wrapper').html(a)
            $('#mdlTerm1').modal('hide');
        })

        // $('#btnPayAdd').on('click', function() {
        //     let a = `
    //         <a href="javascript:void(0)" class="text-nowrap text-success" data-bs-toggle="modal" data-bs-target="#mdlViewAdd">Lihat Bukti</a>
    //     `
        //     let b = `
    //         <p class="mb-0 text-success text-nowrap small">Lunas</p>
    //         <p class="mb-0 text-nowrap small text-muted">23 Apr 2022 06:00</p>
    //     `
        //     $('#tblColAction').html(a)
        //     $('#tblColStatus').html(b)
        //     $('#mdlpayAdd').modal('hide');
        // })
    </script>
    <script>
        'use strict'

        const State = {
            // orders: JSON.parse('{!! json_encode($bladeViewOrders) !!}'),
            orders: {!! json_encode($bladeViewOrders) !!},
            merge_at: "{{ $orders[0]->merge_at }}",
            is_paid: {
                not: "{{ App\Models\OrdersAItems::IS_PAID_NO }}",
                paid: "{{ App\Models\OrdersAItems::IS_PAID_YES }}",
            },
            ddln_pay_type: {
                time: "{{ App\Models\OrdersAItems::DDLN_PAY_TYPE_TIME }}",
                ord_finish: "{{ App\Models\OrdersAItems::DDLN_PAY_TYPE_ORD_FINISH }}",
            },
            invc_to_client: {
                not: "{{ App\Models\OrdersAItems::INVC_TO_CLIENT_NO }}",
                yes: "{{ App\Models\OrdersAItems::INVC_TO_CLIENT_YES }}",
            },
            calc_to_vdr: {
                not: "{{ App\Models\OrdersAItems::CALC_TO_VDR_NO }}",
                yes: "{{ App\Models\OrdersAItems::CALC_TO_VDR_YES }}",
            },
            is_adm_price: {
                no: "{{ App\Models\AItems::IS_ADM_PRICE_NO }}",
                yes: "{{ App\Models\AItems::IS_ADM_PRICE_YES }}",
            },
            crt_type: {
                system: "{{ App\Models\OrdersAItems::CRT_TYPE_SYSTEM }}",
                admin: "{{ App\Models\OrdersAItems::CRT_TYPE_ADMIN }}",
                finance: "{{ App\Models\OrdersAItems::CRT_TYPE_FINANCE }}",
            },
            flow_type: {
                payment: "{{ App\Models\OrdersAItems::FLOW_TYPE_PAYMENT }}",
                billing: "{{ App\Models\OrdersAItems::FLOW_TYPE_BILLING }}",
                hybrid: "{{ App\Models\OrdersAItems::FLOW_TYPE_HYBRID }}",
            },
            cash_type: {
                out: "{{ App\Models\OrdersAItems::TYPE_CASH_OUT }}",
                in: "{{ App\Models\OrdersAItems::TYPE_CASH_IN }}",
                hybrid: "{{ App\Models\OrdersAItems::TYPE_CASH_HYBRID }}",
            },
            a_item_type: {
                main: "{{ App\Models\OrdersAItems::A_TYPE_PRIMARY }}",
                second: "{{ App\Models\OrdersAItems::A_TYPE_SECONDARY }}",
            },
            is_aprv: {
                no: "{{ App\Models\OrdersAItems::IS_APRV_NO }}",
                yes: "{{ App\Models\OrdersAItems::IS_APRV_YES }}",
            },
            is_merge: {
                no: "{{ App\Models\OrdersAItems::IS_MERGE_NO }}",
                yes: "{{ App\Models\OrdersAItems::IS_MERGE_YES }}",
            },
            tax_type: {
                without: "{{ App\Models\OrdersAItems::AMT_TAX_TYPE_WITHOUT }}",
                include: "{{ App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE }}",
                exclude: "{{ App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE }}",
                ppn_percent: "{{ App\Models\OrdersAItems::PPN_PERCENT }}",
                ppn_percent_include: Number("{{ App\Models\OrdersAItems::PPN_PERCENT_INCLUDE }}"),
                pph_percent: "{{ App\Models\OrdersAItems::PPH_PERCENT }}",
            },
            vdr_pkp: {
                is_pkp: "{{ $orders[0]->is_vdr_pkp }}",
                non_pkp: "{{ \App\Models\OrdersClients::IS_NON_PKP }}",
                pkp: "{{ \App\Models\OrdersClients::IS_PKP_YES }}",
            },
            ord_pck_drop: {
                is_aprv_no: "{{ App\Models\OrdersPckDrop::IS_APRV_NO }}",
                is_aprv_yes: "{{ App\Models\OrdersPckDrop::IS_APRV_YES }}",
            },
            aprv_pck_at: "{{ $order->aprv_pck_at }}",
            delay_type_number: 1000,
            storage_lara: "{{ asset('storage') }}/",
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                OrdView.activate();
                ATable.activate();
                OrdAItem.activate();
                FileUploadSingle.activate('submission_proof');
                FileUploadSingle.activate('is_paid_proof');
                OrdPaidItem.activate();
                FileUploadSingle.activate('up_paid_proof');
                OrdNoteFnnc.activate();
                ArcvTable.activate();
            },
            event: function() {
                const {
                    orders
                } = State;
                for (const iOrd in orders) {
                    $(`#view${iOrd}-pickup_at`).text(moment.unix(orders[iOrd].set_pck_at).format('DD MMM YYYY HH:mm:ss'));
                    $(`#view${iOrd}-pickup_date_at`).text(moment.unix(orders[iOrd].set_pck_at).format('DD MMM YYYY'));
                    $(`#view${iOrd}-pickup_time_at`).text(moment.unix(orders[iOrd].set_pck_at).format('HH:mm:ss'));
                }
                if (State.merge_at != 0) {
                    $('#view-merge_at').text(moment.unix(State.merge_at).format('DD MMM YYYY HH:mm:ss'))
                }

                $('#btnMdlNewAdtItem').on('click', function() {
                    $('#inpt-is_paid_proof-base64').val('');
                    $('#inpt-is_paid_proof-file').val('');
                    $('#inpt-group_rotate_is_paid_proof').addClass('d-none');
                    $('#inpt-is_paid_proof-img').addClass('d-none');

                    $('#inpt-submission_proof-base64').val('');
                    $('#inpt-submission_proof-file').val('');
                    $('#inpt-group_rotate_submission_proof').addClass('d-none');
                    $('#inpt-submission_proof-img').addClass('d-none');

                    OrdAItem.toggleSlcItem('show');
                    OrdAItem.toggleInvcToClient('undisabled');
                    OrdAItem.toggleDelItem('hide');

                    $('#mdlAddItem').modal('show');
                });

                $('#mrg-sel_trx_code').select2({
                    dropdownParent: $('#mdlMrgItem'),
                });

                if (State.aprv_pck_at != 0) $('#aprvPckAt').text(moment.unix(State.aprv_pck_at).format('DD MMM YYYY HH:mm'));
                for (let fotoCrt of $('.foto-crt')) {
                    fotoCrt = $(fotoCrt);
                    fotoCrt.text(moment.unix(fotoCrt.data('crt')).format('DD MMM YYYY HH:mm'));
                }
            },
        };

        const OrdView = {
            activate: function() {
                OrdView.event();
                OrdView.initDateAdtPoints();
            },
            event: function() {},
            reqShowAItem: function(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: "{{ route('api_finance_show_a_item', '') }}/" + params.ord_a_item_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'
                            });
                        }
                    })
                });
            },
            viewProofPayment: function(data) {
                if (data.img_proof_payment) {
                    let proof = JSON.parse(data.img_proof_payment);
                    if (proof.length > 0) {
                        OrdView.viewAs(proof[0]);
                        $('#imgViewProofImg').attr('src', State.storage_lara + proof[0]);
                    }
                }
                $('#txtProofOrSubmsn').text('Bukti pembayaran');
                $('#groupViewPaidRefNo').removeClass('d-none');
                $('#view-paid_ref_no').text(data.paid_ref_no);
                $('#mdlViewAdd').data('ord_a_item_id', data.ord_a_item_id);
                $('#mdlViewAdd').modal('show');
            },
            viewProofSubmission: function(data) {
                if (data.img_proof_submission) {
                    let proof = JSON.parse(data.img_proof_submission);
                    if (proof.length > 0) {
                        OrdView.viewAs(proof[0]);
                        $('#imgViewProofImg').attr('src', State.storage_lara + proof[0]);
                    }
                }
                $('#txtProofOrSubmsn').text('Bukti pengajuan');
                $('#groupViewPaidRefNo').addClass('d-none');
                $('#mdlViewAdd').data('ord_a_item_id', data.ord_a_item_id);
                $('#mdlViewAdd').modal('show');
            },
            viewAs: function(urlFile = '') {
                $('#imgViewProofImg').removeClass('img-fluid');
                $('#imgViewProofImg').css('width', '100%');
                $('#imgViewProofImg').css('height', '100%');
                if (urlFile.indexOf('jpeg') > -1 || urlFile.indexOf('png') > -1 || urlFile.indexOf('jpg') > -1) {
                    $('#imgViewProofImg').addClass('img-fluid');
                } else if (urlFile.indexOf('pdf') > -1) {
                    $('#imgViewProofImg').css('height', '50vh');
                }
            },
            initDateAdtPoints: function() {
                const {
                    orders
                } = State;
                for (let iOrd in orders) {
                    iOrd = Number(iOrd);
                    for (let iAdtPoint in orders[iOrd].adtPoints) {
                        iAdtPoint = Number(iAdtPoint);
                        $(`#view${iOrd}-pickup_date_at${iAdtPoint+1}`).text(moment.unix(orders[iOrd].adtPoints[iAdtPoint].set_pck_at).format('DD MMM YYYY'));
                        $(`#view${iOrd}-pickup_time_at${iAdtPoint+1}`).text(moment.unix(orders[iOrd].adtPoints[iAdtPoint].set_pck_at).format('HH:mm:ss'));
                    }
                }
            },
        };

        const OrdPaidItem = {
            activate: function() {
                OrdPaidItem.event();
            },
            event: function() {
                $(document).on('click', '.upPaidProof', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }

                    $('#up_paid_ref_no').val('');
                    $('#inpt-up_paid_proof-base64').val('');
                    $('#inpt-up_paid_proof-file').val('');
                    $('#inpt-group_rotate_up_paid_proof').addClass('d-none');
                    $('#inpt-up_paid_proof-img').addClass('d-none');
                    OrdPaidItem.passDataToView(resp.data);
                });
                $('#btnPayAdd').on('click', async function(e) {
                    e.preventDefault();
                    let ids = $('#mdlpayAdd').data('ord_a_item_id').split(',');
                    let lastPaid = null;
                    for (let id of ids) {
                        let data = OrdPaidItem.getData({
                            ord_a_item_id: Number(id)
                        });
                        let isValid = OrdPaidItem.checkData(data, true);
                        if (!isValid) return false;
                        lastPaid = await OrdPaidItem.submitData(data);
                    }
                    if (lastPaid?.type === 'success') {
                        Helper.toast('Success', 'just now', 'pembayaran sukses');
                        $('#mdlpayAdd').modal('hide');
                        ATable.reload();
                    }
                });
            },
            getData: function(props) {
                const data = {
                    ord_a_item_id: props.ord_a_item_id,
                };

                // data.ord_a_item_id = $('#mdlpayAdd').data('ord_a_item_id');
                // data.group_merge_code = $('#mdlpayAdd').data('group_merge_code');

                data.up_paid_ref_no = $('#up_paid_ref_no').val();

                data.up_paid_proof_base64 = [];
                let up_paid_proof_base64 = $('#inpt-up_paid_proof-base64').val();
                if (up_paid_proof_base64.indexOf('data:') > -1) {
                    // data.up_paid_proof_base64.push(up_paid_proof_base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''));
                    // data.up_paid_proof_base64.push(up_paid_proof_base64.replace(/^data:(image|application)\/(png|jpg|jpeg|pdf);base64,/, ''));
                    data.up_paid_proof_base64.push(up_paid_proof_base64);
                }

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.up_paid_ref_no.length < 1) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Nomor referensi wajib diisi');
                    return false;
                }
                if (data.up_paid_proof_base64.length < 1) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Bukti pembayaran wajib diisi');
                    return false;
                }
                return true;
            },
            passDataToView: function(data) {
                $('#mdlpayAdd').data('ord_a_item_id', '' + data.ord_a_item_id);
                $('#mdlpayAdd').data('group_merge_code', data.group_merge_code);
                if (data?.childs) {
                    for (let iChild in data.childs) {
                        let ord_a_item_id = $('#mdlpayAdd').data('ord_a_item_id');
                        $('#mdlpayAdd').data('ord_a_item_id', ord_a_item_id + ',' + data.childs[iChild].ord_a_item_id);
                    }
                }
                $('#mdlpayAdd').modal('show');
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnPayAdd').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnPayAdd').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_pay_a_items', '') }}/" + data.ord_a_item_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) => {
                            $('#btnPayAdd').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnPayAdd').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'
                            });
                        }
                    })
                })
            },
        }

        /**
         * Event Toggle
         * Jika new item => show input add item
         * Jika new item is adm price => hide tenggat pembayaran, bukti pengajuan, tujuan pembayaran
         * Jika select existing item => clear input add item
         * Jika existing item is adm price => hide tenggat pembayaran, bukti pengajuan, tujuan pembayaran
         * Jika is adm price (dari manapun) yes => tujuan pembayaran none
         * Jika tujuan pembayaran fill => show input penerima
         * Jika tujuan pembayaran none => hide and clear input penerima
         * Jika status pembayaran belum bayar => hide unggah bukti pembayaran
         * Jika status pembayaran lunas => show unggah bukti pembayaran
         */
        const OrdAItem = {
            activate: function() {
                OrdAItem.event();
            },
            event: function() {
                // init select2
                $('#slcTrxCode').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#slcItem').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_type').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_tax_type').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_bill_tax_type').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#slcPayPurpose').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#bank').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                // event select
                $('#slcItem').on('change', function() {
                    let slc = $('#slcItem option:selected');
                    if (slc.val() === 'new') {
                        $('#addNewItemWrapper').removeClass('d-none');
                        OrdAItem.toggleAddItemIsAdmPrice('unchecked');
                        OrdAItem.toggleGroupPayPurpose('show');
                        $('#slcItemPrice').text('');
                    } else {
                        $('#addNewItemWrapper').addClass('d-none');
                        OrdAItem.clearInputAddNewItem();
                        if (slc.data('is_adm_price') == State.is_adm_price.yes) {
                            OrdAItem.toggleGroupFillDdln('hide');
                            OrdAItem.toggleGroupPayPurpose('hide');
                            OrdAItem.toggleGroupSubmissionProof('hide');
                        } else {
                            OrdAItem.toggleGroupFillDdln('show');
                            OrdAItem.toggleGroupPayPurpose('show');
                            OrdAItem.toggleGroupSubmissionProof('show');
                        }
                        $('#slcItemPrice').text('Harga: Rp' + (new Intl.NumberFormat('id-ID')).format(slc.data('price')));
                    }
                });
                $('#slcPayPurpose').on('change', function() {
                    let slc = $('#slcPayPurpose option:selected');
                    if (slc.val() === 'fill') {
                        $('#fillReceiverWrapper').removeClass('d-none');
                    } else {
                        $('#fillReceiverWrapper').addClass('d-none');
                        OrdAItem.clearInputBank();
                    }
                });
                // event switch
                $('#is_paid').bind('change', function() {
                    if ($(this).is(':checked')) {
                        $('#groupIsPaid').removeClass('d-none');
                        $('#txtIsPaid').html('Lunas');
                    } else {
                        $('#groupIsPaid').addClass('d-none');
                        $('#txtIsPaid').html('Belum dibayar');
                        OrdAItem.clearInputIsPaid();
                    }
                });
                // event checklist
                $('#add-item_isAdmPrice').on('change', function() {
                    $('#invcToClient').prop('checked', false).trigger('change');
                    if ($('#add-item_isAdmPrice').prop('checked')) {
                        OrdAItem.toggleGroupPayPurpose('hide');
                        OrdAItem.toggleGroupSubmissionProof('hide');
                        OrdAItem.toggleGroupFillDdln('hide');
                    } else {
                        OrdAItem.toggleGroupPayPurpose('show');
                        OrdAItem.toggleGroupSubmissionProof('show');
                        OrdAItem.toggleGroupFillDdln('show');
                    }
                });
                $('#invcToClient').on('change', function() {
                    $('#add-invc_item_price').val('');
                    if ($('#invcToClient').prop('checked')) {
                        $('#groupPriceToClient').removeClass('d-none');
                    } else {
                        $('#groupPriceToClient').addClass('d-none');
                    }
                });
                // input
                $('#add-item_price').on('keyup', function() {
                    let price = $('#add-item_price').val().split('.').join('');
                    $('#add-item_price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                $('#add-invc_item_price').on('keyup', function() {
                    let price = $('#add-invc_item_price').val().split('.').join('');
                    $('#add-invc_item_price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                // min date is today
                let TimeISOString = moment().toISOString().split('T');
                let time = TimeISOString[1].split('.')[0].split(':');
                // $('#ddln_pay_date').attr('min', TimeISOString[0]); // bypass_date
                TimeISOString = moment().toISOString().split('T');
                time = TimeISOString[1].split('.')[0].split(':');
                // $('#is_paid_date').attr('min', TimeISOString[0]); // bypass_date
                // submit
                $('#btnSubmitAddItem').on('click', function(e) {
                    e.preventDefault();
                    let data = OrdAItem.getData();
                    let isValid = OrdAItem.checkData(data, true);
                    if (!isValid) return false;
                    OrdAItem.submitData(data);
                });
                $('#btnSubmitDelItem').on('click', function(e) {
                    e.preventDefault();
                    let data = {};
                    data.is_del = 2;
                    data.ord_a_item_id = $('#mdlDelItem').data('ord_a_item_id');
                    OrdAItem.submitDelData(data);
                });
                $('#btnSubmitRejectItem').on('click', function(e) {
                    e.preventDefault();
                    let data = {};
                    data.is_rjct = 2;
                    data.ord_a_item_id = $('#mdlRjctItem').data('ord_a_item_id');
                    OrdAItem.submitRejectData(data);
                });
                $('#btnSubmitMergeItem').on('click', function(e) {
                    e.preventDefault();
                    let data = {};
                    data.ord_a_item_id = $('#mdlMrgItem').data('ord_a_item_id');
                    const selTrx = $('#mrg-sel_trx_code :selected');
                    data.mrg_to_ord_id = selTrx.data('id');
                    data.mrg_to_ord_code = selTrx.data('code');
                    if (typeof data.mrg_to_ord_code === 'undefined' || data.mrg_to_ord_code == '') {
                        Helper.toast('Warning', 'just now', 'transaksi belum dipilih');
                        return false;
                    }
                    OrdAItem.submitMergeData(data);
                });
                OrdAItem.eventTax();
            },
            eventTax: function() {
                // vendor
                $('#add-item_tax_type').on('change', function() {
                    const val = $('#add-item_tax_type').val();
                    if (val == State.tax_type.include) {
                        $('.groupTax').removeClass('d-none');
                        if (State.vdr_pkp.is_pkp == State.vdr_pkp.pkp) {
                            $('#add-item_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        } else {
                            $('#add-item_tax_ppn_percent').val(0);
                        }
                        $('#add-item_tax_pph_percent').val(State.tax_type.pph_percent);
                    } else if (val == State.tax_type.exclude) {
                        $('.groupTax').removeClass('d-none');
                        if (State.vdr_pkp.is_pkp == State.vdr_pkp.pkp) {
                            $('#add-item_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        } else {
                            $('#add-item_tax_ppn_percent').val(0);
                        }
                        $('#add-item_tax_pph_percent').val(State.tax_type.pph_percent);
                    } else { // without
                        $('.groupTax').addClass('d-none');
                        $('#add-item_tax_ppn_percent').val('');
                        $('#add-item_tax_pph_percent').val('');
                    }

                    let calcTax = OrdAItem.calcTax('vendor');
                    $('#add-item_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                    $('#add-item_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                    $('#add-item_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));

                    if (State.vdr_pkp.is_pkp == State.vdr_pkp.pkp) {
                        $('.groupPpn').removeClass('d-none');
                    } else {
                        $('.groupPpn').addClass('d-none');
                    }
                });
                $('#add-item_tax_type').trigger('change');
                let ppnPercentTimeout = null;
                $('#add-item_tax_ppn_percent').on('keyup', function() {
                    clearTimeout(ppnPercentTimeout);
                    ppnPercentTimeout = setTimeout(() => {
                        let ppn_percent = $('#add-item_tax_ppn_percent').val();
                        // $('#add-item_tax_ppn_percent').val(ppn_percent.replaceAll(/,/ig, '.')); // gaperlu udah dihanle kalo format numeric
                        let calcTax = OrdAItem.calcTax('vendor');
                        $('#add-item_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });
                let pphPercentTimeout = null;
                $('#add-item_tax_pph_percent').on('keyup', function() {
                    clearTimeout(pphPercentTimeout);
                    pphPercentTimeout = setTimeout(() => {
                        let pph_percent = $('#add-item_tax_pph_percent').val();
                        // $('#add-item_tax_pph_percent').val(pph_percent.replaceAll(/,/ig, '.')); // gaperlu udah dihanle kalo format numeric
                        let calcTax = OrdAItem.calcTax('vendor');
                        $('#add-item_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });
                $('#slcItem').on('change', function() {
                    // $('#add-item_tax_pph_percent').val(pph_percent.replaceAll(/,/ig, '.')); // gaperlu udah dihanle kalo format numeric
                    let calcTax = OrdAItem.calcTax('vendor');
                    $('#add-item_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                    $('#add-item_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                    $('#add-item_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                });
                let newItemTimeout = null;
                $('#add-item_price').on('keyup', function() {
                    clearTimeout(newItemTimeout);
                    newItemTimeout = setTimeout(() => {
                        let calcTax = OrdAItem.calcTax('vendor');
                        $('#add-item_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });

                // client
                $('#add-item_bill_tax_type').on('change', function() {
                    const val = $('#add-item_bill_tax_type').val();
                    if (val == State.tax_type.include) {
                        $('.groupTaxBill').removeClass('d-none');
                        $('#add-item_bill_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        $('#add-item_bill_tax_pph_percent').val(State.tax_type.pph_percent);
                    } else if (val == State.tax_type.exclude) {
                        $('.groupTaxBill').removeClass('d-none');
                        $('#add-item_bill_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        $('#add-item_bill_tax_pph_percent').val(State.tax_type.pph_percent);
                    } else { // without
                        $('.groupTaxBill').addClass('d-none');
                        $('#add-item_bill_tax_ppn_percent').val('');
                        $('#add-item_bill_tax_pph_percent').val('');
                    }

                    let calcTax = OrdAItem.calcTax('client');
                    $('#add-item_bill_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                    $('#add-item_bill_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                    $('#add-item_bill_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                });
                let ppnPercentTimeoutBill = null;
                $('#add-item_bill_tax_ppn_percent').on('keyup', function() {
                    clearTimeout(ppnPercentTimeoutBill);
                    ppnPercentTimeoutBill = setTimeout(() => {
                        let ppn_percent = $('#add-item_bill_tax_ppn_percent').val();
                        // $('#add-item_bill_tax_ppn_percent').val(ppn_percent.replaceAll(/,/ig, '.')); // gaperlu udah dihanle kalo format numeric
                        let calcTax = OrdAItem.calcTax('client');
                        $('#add-item_bill_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_bill_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_bill_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });
                let pphPercentTimeoutBill = null;
                $('#add-item_bill_tax_pph_percent').on('keyup', function() {
                    clearTimeout(pphPercentTimeoutBill);
                    pphPercentTimeoutBill = setTimeout(() => {
                        let pph_percent = $('#add-item_bill_tax_pph_percent').val();
                        // $('#add-item_bill_tax_pph_percent').val(pph_percent.replaceAll(/,/ig, '.')); // gaperlu udah dihanle kalo format numeric
                        let calcTax = OrdAItem.calcTax('client');
                        $('#add-item_bill_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_bill_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_bill_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });
                let newItemTimeoutBill = null;
                $('#add-invc_item_price').on('keyup', function() {
                    clearTimeout(newItemTimeoutBill);
                    newItemTimeoutBill = setTimeout(() => {
                        let calcTax = OrdAItem.calcTax('client');
                        $('#add-item_bill_tax_ppn_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.ppn_flat));
                        $('#add-item_bill_tax_pph_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.pph_flat));
                        $('#add-item_bill_tax_total_flat').val((new Intl.NumberFormat('id-ID')).format(calcTax.total_tax));
                    }, State.delay_type_number);
                });
            },
            calcTax: function(type = 'vendor') {
                let calc = {};

                if (type === 'vendor') {
                    calc = {
                        tax_type: Number($('#add-item_tax_type').val()),
                        ppn_percent: Number($('#add-item_tax_ppn_percent').val()),
                        pph_percent: Number($('#add-item_tax_pph_percent').val()),
                        qty: Number($('#add-item_qty').val()),
                        vdr_pkp: State.vdr_pkp.is_pkp,
                    };
                    let slcType = $('#slcItem option:selected');
                    if (slcType.val() === 'new') {
                        calc.price = Number($('#add-item_price').val().split('.').join(''));
                    } else if (slcType.val() === '') {} else {
                        calc.price = Number(slcType.data('price'));
                    }

                    if (calc.vdr_pkp == State.vdr_pkp.pkp) {
                        if (calc.tax_type == State.tax_type.include) {
                            const before_ppn = calc.price / State.tax_type.ppn_percent_include;
                            const ppn = before_ppn * calc.ppn_percent / 100;
                            calc.ppn_flat = ppn;
                            const pph = -1 * (before_ppn * calc.pph_percent / 100);
                            calc.pph_flat = pph;
                            calc.total_tax = before_ppn + ppn + pph;
                        } else if (calc.tax_type == State.tax_type.exclude) {
                            const ppn = calc.price * calc.ppn_percent / 100;
                            calc.ppn_flat = ppn;
                            const pph = -1 * (calc.price * calc.pph_percent / 100);
                            calc.pph_flat = pph;
                            calc.total_tax = calc.price + ppn + pph;
                        }
                    } else {
                        if (calc.tax_type == State.tax_type.include) {
                            const ppn = 0;
                            calc.ppn_flat = ppn;
                            const pph = -1 * (calc.price * calc.pph_percent / 100);
                            calc.pph_flat = pph;
                            calc.total_tax = calc.price + ppn + pph;
                        } else if (calc.tax_type == State.tax_type.exclude) {
                            const ppn = 0;
                            calc.ppn_flat = ppn;
                            const pph = -1 * (calc.price * calc.pph_percent / 100);
                            calc.pph_flat = pph;
                            calc.total_tax = calc.price + ppn + pph;
                        }
                    }
                    if (calc.tax_type == State.tax_type.without) {
                        calc.ppn_flat = 0;
                        calc.pph_flat = 0;
                        calc.total_tax = calc.price;
                    }
                } else if (type === 'client') {
                    calc = {
                        tax_type: Number($('#add-item_bill_tax_type').val()),
                        ppn_percent: Number($('#add-item_bill_tax_ppn_percent').val()),
                        pph_percent: Number($('#add-item_bill_tax_pph_percent').val()),
                        qty: Number($('#add-item_qty').val()),
                        price: Number($('#add-invc_item_price').val().split('.').join('')),
                    };
                    if (calc.tax_type == State.tax_type.include) {
                        calc.ppn_flat = calc.price - (calc.price / State.tax_type.PPN_PERCENT_INCLUDE);
                        const before_ppn = calc.price - calc.ppn_flat;
                        calc.pph_flat = before_ppn * calc.pph_percent / 100;
                        const before_ppn_pph = calc.price - calc.ppn_flat - calc.pph_flat;
                        calc.total_tax = before_ppn_pph;
                    } else if (calc.tax_type == State.tax_type.exclude) {
                        calc.ppn_flat = calc.price * calc.ppn_percent / 100;
                        const after_ppn = calc.price + calc.ppn_flat;
                        calc.pph_flat = after_ppn * calc.pph_percent / 100;
                        calc.total_tax = calc.price + calc.ppn_flat + calc.pph_flat;
                    } else { // without
                        calc.ppn_flat = 0;
                        calc.pph_flat = 0;
                        calc.total_tax = calc.price;
                    }
                }

                calc.ppn_flat = Math.round(calc.ppn_flat);
                calc.pph_flat = Math.round(calc.pph_flat);
                calc.total_tax = Math.round(calc.total_tax);

                return calc;
            },
            getData: function() {
                const data = {};

                let slcType = $('#slcItem option:selected');
                if (slcType.val() === 'new') {
                    data.a_id = '00';
                    data.a_name = $('#add-item_name').val();
                    data.a_type = $('#add-item_type').val();
                    data.a_price = $('#add-item_price').val().split('.').join('');
                    if ($('#add-item_isAdmPrice').prop('checked')) {
                        data.is_adm_price = State.is_adm_price.yes
                    } else {
                        data.is_adm_price = State.is_adm_price.no
                    }
                } else if (slcType.val() === '') {} else {
                    data.a_id = slcType.val(); // id
                    data.a_name = slcType.data('name');
                    data.a_type = slcType.data('type');
                    data.a_price = slcType.data('price');
                    data.is_adm_price = slcType.data('is_adm_price');
                }
                let calcTaxVendor = OrdAItem.calcTax('vendor');
                data.a_price_tax_type = calcTaxVendor.tax_type;
                data.a_price_tax_ppn_percent = calcTaxVendor.ppn_percent;
                data.a_price_tax_ppn_flat = calcTaxVendor.ppn_flat;
                data.a_price_tax_pph_percent = calcTaxVendor.pph_percent;
                data.a_price_tax_pph_flat = calcTaxVendor.pph_flat;
                data.a_price_total_tax = calcTaxVendor.total_tax;
                data.a_qty = $('#add-item_qty').val();

                if (data.is_adm_price != State.is_adm_price.yes) {
                    data.ddln_pay_date = $('#ddln_pay_date').val().trim();
                    data.ddln_pay_time_hour = $('#ddln_pay_time_hour').val()?.trim();
                    data.ddln_pay_time_minute = $('#ddln_pay_time_minute').val()?.trim();
                    data.ddln_pay_time = `${data.ddln_pay_time_hour}:${data.ddln_pay_time_minute}`;
                    data.ddln_pay_at = moment(data.ddln_pay_date + ' ' + data.ddln_pay_time).unix();

                    data.submission_proof_base64 = [];
                    let submission_proof_base64 = $('#inpt-submission_proof-base64').val();
                    if (submission_proof_base64.indexOf('data:') > -1) {
                        // data.submission_proof_base64.push(submission_proof_base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''));
                        // data.submission_proof_base64.push(submission_proof_base64.replace(/^data:(image|application)\/(png|jpg|jpeg|pdf);base64,/, ''));
                        data.submission_proof_base64.push(submission_proof_base64);
                    }
                }

                data.slc_pay_purpose = $('#slcPayPurpose').val();
                if (data.slc_pay_purpose === 'fill') {
                    let selectedBank = $('#bank :selected');
                    if (selectedBank && selectedBank.val() != '') {
                        data.bank_id = selectedBank.data('id');
                        data.bank_code = selectedBank.data('code');
                        data.bank_short = selectedBank.data('short');
                        data.bank_name = selectedBank.data('name');
                    }
                    data.bank_acc_number = $('#bank_acc_number').val();
                    data.bank_acc_name = $('#bank_acc_name').val();
                }

                let is_paid = $('#is_paid').prop('checked');
                data.is_paid = State.is_paid.not;
                if (is_paid) {
                    data.is_paid = State.is_paid.paid;
                    data.paid_proof_ref_no = $('#inpt-paid_proof_ref_no').val();
                    data.is_paid_proof_base64 = [];
                    let is_paid_proof_base64 = $('#inpt-is_paid_proof-base64').val();
                    if (is_paid_proof_base64.indexOf('data:') > -1) {
                        // data.is_paid_proof_base64.push(is_paid_proof_base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''));
                        // data.is_paid_proof_base64.push(is_paid_proof_base64.replace(/^data:(image|application)\/(png|jpg|jpeg|pdf);base64,/, ''));
                        data.is_paid_proof_base64.push(is_paid_proof_base64);
                    }
                    // data.is_paid_date = $('#is_paid_date').val().trim();
                    // data.is_paid_time_hour = $('#is_paid_time_hour').val()?.trim();
                    // data.is_paid_time_minute = $('#is_paid_time_minute').val()?.trim();
                    // data.is_paid_time = `${data.is_paid_time_hour}:${data.is_paid_time_minute}`;
                    // data.is_paid_at = moment(data.is_paid_date + ' ' + data.is_paid_time).unix();
                }

                let is_invc_to_client = $('#invcToClient').prop('checked');
                data.is_invc_to_client = State.invc_to_client.not;
                data.flow_type = State.flow_type.payment;
                data.cash_type = State.cash_type.out;
                if (is_invc_to_client) {
                    data.is_invc_to_client = State.invc_to_client.yes;
                    data.cash_type = State.cash_type.hybrid;
                    data.flow_type = State.flow_type.hybrid;
                    data.a_invc_price = $('#add-invc_item_price').val().split('.').join('');
                    data.a_invc_price_tax_type = State.tax_type.without;
                    // let calcTaxClient = OrdAItem.calcTax('client');
                    // data.a_invc_price_tax_type = calcTaxClient.tax_type;
                    // data.a_invc_price_tax_ppn_percent = calcTaxClient.ppn_percent;
                    // data.a_invc_price_tax_ppn_flat = calcTaxClient.ppn_flat;
                    // data.a_invc_price_tax_pph_percent = calcTaxClient.pph_percent;
                    // data.a_invc_price_tax_pph_flat = calcTaxClient.pph_flat;
                    // data.a_invc_price_total_tax = calcTaxClient.total_tax;
                }

                data.ord_id = $('#slcTrxCode :selected').data('ord_id');
                data.ddln_pay_type = State.ddln_pay_type.time;
                data.is_calc_to_vdr = State.calc_to_vdr.yes;
                data.crt_type = State.crt_type.finance;

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (typeof data.a_id == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item wajib diisi');
                    return false;
                }
                if (data.a_name == '' || data.a_name == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item nama wajib diisi');
                    return false;
                }
                if (data.a_type == '' || data.a_type == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item satuan wajib diisi');
                    return false;
                }
                if (data.a_price == '' || data.a_price == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item harga wajib diisi');
                    return false;
                }
                if (typeof data.a_qty == 'undefined' || Number(data.a_qty) < 1) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Jumlah wajib diisi');
                    return false;
                }
                if (data.is_adm_price != State.is_adm_price.yes) {
                    if (data.ddln_pay_at < 1 || isNaN(data.ddln_pay_at)) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Tenggat pembayaran tidak valid');
                        return false;
                    }
                    // start bypass_date
                    // if (data.ddln_pay_at < moment().unix()) {
                    //     if (isAlert) Helper.toast('Warning', 'just now', 'Tenggat pembayaran tidak bisa kurang dari saat ini');
                    //     return false;
                    // }
                    // end bypass_date
                    // if (data.ddln_pay_at < moment().add(5, 'minutes').unix()) {
                    //     if (isAlert) Helper.toast('Warning', 'just now', 'Minimal tenggat pembayaran 5 menit dari sekarang');
                    //     return false;
                    // }
                    if (data.submission_proof_base64.length < 1) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Bukti pengajuan wajib diisi');
                        return false;
                    }
                    if (data.slc_pay_purpose === 'fill') {
                        if (!data.bank_id) {
                            if (isAlert) Helper.toast('Warning', 'just now', 'Bank wajib dipilih');
                            return false;
                        }
                        if (data.bank_acc_number == '') {
                            if (isAlert) Helper.toast('Warning', 'just now', 'Nomor rekening wajib diisi');
                            return false;
                        }
                        if (data.bank_acc_name == '') {
                            if (isAlert) Helper.toast('Warning', 'just now', 'Pemilik rekening wajib diisi');
                            return false;
                        }
                    }
                }
                if (data.is_invc_to_client == State.invc_to_client.yes) {
                    if (data.a_invc_price < 0) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Harga yang ditagihkan ke client wajib diisi');
                        return false;
                    }
                }
                if (data.is_paid === State.is_paid.paid) {
                    if (data.paid_proof_ref_no.length < 2) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Nomor referensi wajib diisi');
                        return false;
                    }
                    if (data.is_paid_proof_base64.length < 1) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Bukti pembayaran wajib diisi');
                        return false;
                    }
                }
                return true;
            },
            submitData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitAddItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitAddItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_add_a_items') }}",
                        method: 'POST',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitAddItem').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 item');
                            $('#mdlAddItem').modal('hide');
                            // ATable.reload();
                            window.location.href = window.location.href;
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitAddItem').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'
                            });
                        }
                    })
                })
            },
            clearInputIsPaid: function() {
                $('#is_paid_proof').val('');
                $('#is_paid_date').val('');
                $('#is_paid_time_hour').val('').trigger('change');
                $('#is_paid_time_minute').val('').trigger('change');
            },
            toggleGroupPayPurpose: function(toggle = 'show') {
                if (toggle === 'show') {
                    $('#groupPayPurpose').removeClass('d-none');
                } else {
                    $('#groupPayPurpose').addClass('d-none');
                    $('#slcPayPurpose').val('none').trigger('change');
                }
            },
            toggleGroupSubmissionProof: function(toggle = 'show') {
                if (toggle === 'show') {
                    $('#groupSubmissionProof').removeClass('d-none');
                } else {
                    $('#groupSubmissionProof').addClass('d-none');
                }
            },
            clearInputBank: function() {
                $('#bank').val('').trigger('change');
                $('#bank_acc_name').val('');
                $('#bank_acc_number').val('');
            },
            clearAllInput: function() {
                $('#slcItem').val('').trigger('change');
                OrdAItem.clearInputBank();
                $('#add-item_name').val('');
                $('#add-item_type').val('').trigger('change');
                $('#add-item_price').val('');
                $('#add-item_qty').val('');
                $('#ddln_pay_date').val('');
                $('#ddln_pay_time_hour').val('');
                $('#ddln_pay_time_minute').val('');
                $('#inpt-submission_proof-base64').val('');
                $('#inpt-submission_proof-file').val('');
                $('#inpt-group_rotate_submission_proof').addClass('d-none');
                $('#inpt-submission_proof-img').addClass('d-none');
                $('#invcToClient').prop('checked', false).trigger('change');
                $('#add-invc_item_price').val('');
            },
            toggleAddItemIsAdmPrice: function(toggle = 'checked') {
                if (toggle === 'checked') {
                    $('#add-item_isAdmPrice').prop('checked', true).trigger('change');
                } else {
                    $('#add-item_isAdmPrice').prop('checked', false).trigger('change');
                }
            },
            clearInputAddNewItem: function() {
                $('#add-item_name').val('');
                $('#add-item_type').val('').trigger('change');
                $('#add-item_price').val('');
                $('#add-item_qty').val('');
                OrdAItem.toggleAddItemIsAdmPrice('unchecked');
            },
            toggleGroupFillDdln: function(toggle = 'show') {
                if (toggle === 'show') {
                    $('#groupFillDdln').removeClass('d-none');
                } else {
                    $('#groupFillDdln').addClass('d-none');
                }
            },
            toggleSlcItem: function(toggle = 'show') {
                if (toggle === 'show') {
                    $('#addSlcItemWrapper').removeAttr('disabed');
                    $('#addSlcItemWrapper').removeClass('d-none');
                } else {
                    $('#addSlcItemWrapper').attr('disabed', true);
                    $('#addSlcItemWrapper').addClass('d-none');
                }
            },
            toggleInvcToClient: function(toggle = 'disabled') {
                if (toggle === 'disabled') {
                    $('#invcToClient').attr('disabled', true);
                    $('#add-invc_item_price').attr('disabled', true);
                } else {
                    $('#invcToClient').removeAttr('disabled');
                    $('#add-invc_item_price').removeAttr('disabled');
                }
            },
            toggleDelItem: function(toggle = 'show') {
                if (toggle === 'show') {
                    $('#btnDelItem_updt').removeClass('d-none');
                } else {
                    $('#btnDelItem_updt').addClass('d-none');
                }
            },
            submitDelData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitDelItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitDelItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_del_a_items', '') }}/" + data.ord_a_item_id,
                        method: 'DELETE',
                        crossDomain: true,
                        processData: true,
                        headers: {
                            'x-api-key': Helper.getCookie('_trtk'),
                            'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
                        },
                        data: data,
                        success: (data, textStatus, jqXHR) => {
                            $('#btnSubmitDelItem').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            Helper.toast('Success', 'just now', 'sukses hapus item');
                            $('#mdlDelItem').modal('hide');
                            $('#mdlAddItem').modal('hide');
                            ATable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitDelItem').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'Please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                })
            },
            submitRejectData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitRejectItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitRejectItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_rjct_a_items', '') }}/" + data.ord_a_item_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) => {
                            $('#btnSubmitRejectItem').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', 'sukses tolak item');
                            $('#mdlDelItem').modal('hide');
                            $('#mdlAddItem').modal('hide');
                            $('#mdlRjctItem').modal('hide');
                            ATable.reload();
                            ArcvTable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitRejectItem').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'
                            });
                        }
                    })
                })
            },
            submitMergeData: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitMergeItem').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitMergeItem').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_merger_a_items', '') }}/" + data.ord_a_item_id,
                        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) => {
                            $('#btnSubmitMergeItem').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', 'sukses merge item');
                            $('#mdlMrgItem').modal('hide');
                            ATable.reload();
                            $('#mrg-sel_trx_code').val('').trigger('change');
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitMergeItem').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 ATable = {
            activate: function() {
                ATable.reload();
                ATable.event();
            },
            event: function() {
                $(document).on('click', '.viewPaidProof', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }
                    OrdView.viewProofPayment(resp.data);
                });

                $(document).on('click', '.viewSubmissionProof', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }
                    OrdView.viewProofSubmission(resp.data);
                });

                $(document).on('click', '.btnDelItem', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }
                    $('#del-name').text(resp.data.desc);
                    $('#mdlDelItem').data('ord_a_item_id', resp.data.ord_a_item_id);
                    $('#mdlDelItem').modal('show');
                });

                $(document).on('click', '.btnRejectItem', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }
                    $('#reject-name').text(resp.data.desc);
                    $('#reject-crt_name').text(resp.data.ucrt_name);
                    $('#reject-crt_at').text(moment.unix(resp.data.crt).format('DD MMM YYYY HH:mm:ss'));
                    $('#mdlRjctItem').data('ord_a_item_id', resp.data.ord_a_item_id);
                    $('#mdlRjctItem').modal('show');
                });
                $(document).on('click', '.btnMergeItem', async function(e) {
                    let ord_a_item_id = $(e.target).closest('tr').find('td[data-ord_a_item_id]').data('ord_a_item_id');
                    let resp = await OrdView.reqShowAItem({
                        ord_a_item_id
                    });
                    if (resp.type != 'success') {
                        Helper.toast('Item tidak ditemukan', 'just now', 'please try again');
                        return false;
                    }
                    $('#mrg-name').text(resp.data.desc);
                    if (resp.data.is_paid == State.is_paid.paid) {
                        $('#mrg-stts_pay').html(`
                            <p class="mb-0 text-success text-nowrap small">Lunas</p>
                            <p class="mb-0 text-nowrap small text-muted">${moment.unix(resp.data.paid_at).format('DD MMM YYYY HH:mm')}</p>
                        `);
                    } else {
                        $('#mrg-stts_pay').html(`
                            <p class="mb-0 text-danger text-nowrap small">Belum Bayar</p>
                        `);
                    }
                    $('#mdlMrgItem').data('ord_a_item_id', resp.data.ord_a_item_id);
                    $('#mdlMrgItem').modal('show');
                });
            },
            reload: function() {
                // $('#tblAdditional').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                let ord_ids = '';
                const {
                    orders
                } = State;
                for (let iOrd in orders) {
                    ord_ids += `${orders[iOrd].ord_id},`;
                }
                if (ord_ids.slice(-1) === ',') {
                    ord_ids = ord_ids.slice(0, -1);
                }
                $('#tblAdditional').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_finance_list_adt_items_payments') }}?ord_id=" + ord_ids + "&is_aprv=" + State.is_aprv.yes,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            // const data = jqXHR.responseJSON;
                            // 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 = '';
                                if (State.is_paid.paid == row.is_paid) {
                                    action += `
                                        <a href="javascript:void(0)" class="text-nowrap text-success viewPaidProof">Lihat Bukti<br>Pembayaran</a>
                                    `;
                                } else {
                                    if (State.ddln_pay_type.ord_finish == row.ddln_pay_type) {
                                        if (row.drop_chk_at != 0) {
                                            action += `
                                                <a href="javascript:void(0)" class="btn btn-primary btn-sm text-nowrap small w-100 upPaidProof">Bayar</a>
                                            `;
                                            let img_proof_submission = null;
                                            try {
                                                img_proof_submission = JSON.parse(row.img_proof_submission);
                                            } catch (e) {}
                                            if (row.img_proof_submission) {
                                                if (img_proof_submission.length > 0) {
                                                    action += `
                                                        <a href="javascript:void(0)" class="text-nowrap text-danger viewSubmissionProof">Lihat Bukti<br>Pengajuan</a>
                                                    `;
                                                }
                                            }
                                        } else {
                                            // action += '<p class="mb-0 text-danger small">Menunggu pengantaran selesai</p>';
                                            if (row?.previous_termin?.length === 1) {
                                                if (row.previous_termin[0].is_paid == State.is_paid.paid) {
                                                    action += '<a href="javascript:void(0)" class="btn btn-primary btn-sm text-nowrap small w-100 upPaidProof">Bayar</a>';
                                                } else {
                                                    action += '-';
                                                }
                                            } else {
                                                action += '-';
                                            }
                                        }
                                    } else {
                                        action += `
                                            <a href="javascript:void(0)" class="btn btn-primary btn-sm text-nowrap small w-100 upPaidProof">Bayar</a>
                                        `;
                                        let img_proof_submission = null;
                                        try {
                                            img_proof_submission = JSON.parse(row.img_proof_submission);
                                        } catch (e) {}
                                        if (row.img_proof_submission) {
                                            if (img_proof_submission.length > 0) {
                                                action += `
                                                    <a href="javascript:void(0)" class="text-nowrap text-danger viewSubmissionProof">Lihat Bukti<br>Pengajuan</a>
                                                `;
                                            }
                                        }
                                    }
                                    if (State.a_item_type.main != row.a_item_type) {
                                        if (State.is_paid.paid != row.is_bill_paid) {
                                            if (State.crt_type.admin == row.a_item_crt_type) {
                                                action += `
                                                    <br><br>
                                                    <a href="javascript:void(0)" class="btn btn-secondary btn-sm text-nowrap small w-100 btnRejectItem">Tolak</a>
                                                `;
                                            } else if (State.crt_type.finance == row.a_item_crt_type) {
                                                action += `
                                                    <br><br>
                                                    <a href="javascript:void(0)" class="btn btn-secondary btn-sm text-nowrap small w-100 btnDelItem">Hapus</a>
                                                `;
                                            }
                                        }
                                    }
                                }
                                // if (State.a_item_type.second == row.a_item_type) {
                                //     if (row.is_merge_to == State.is_merge.yes || row.is_merge_from == State.is_merge.yes) {} else {
                                //         action += `
                            //             <br>
                            //             <a href="javascript:void(0)" class="btn btn-warning btn-sm text-nowrap small mt-2 w-100 btnMergeItem">Merge</a>
                            //         `;
                                //     }
                                // }
                                return action;
                            }
                        },
                        {
                            data: 'desc',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-ord_a_item_id', rowData.ord_a_item_id);
                                $(td).attr('data-ord_id', rowData.ord_id);
                                $(td).attr('data-ord_code', rowData.ord_code);
                                $(td).attr('data-v_termin_id', rowData.v_termin_id);
                                $(td).attr('data-group_merge_code', rowData.group_merge_code);
                            },
                            render: function(data, type, row, meta) {
                                let text = data;
                                // if (row.is_merge_to == State.is_merge.yes) {
                                //     text += '<div class="mb-2"></div><small class="mt-2">Telah di merge pada<br>' + moment.unix(row.merge_to_at).format('DD MMM YYYY HH:mm:ss') + '<br>Ke trx <span class="text-danger">' + row.merge_to_ord_code + '</span></small>';
                                // } else if (row.is_merge_from == State.is_merge.yes) {
                                //     text += '<div class="mb-2"></div><small class="mt-2">Telah di merge pada<br>' + moment.unix(row.merge_from_at).format('DD MMM YYYY HH:mm:ss') + '<br>Dari trx <span class="text-danger">' + row.merge_from_ord_code + '</span></small>';
                                // }
                                if (row.invc_to_client == State.invc_to_client.yes) {
                                    if (State.is_paid.paid == row.is_bill_paid) {
                                        text += '<div class="mb-2"></div><small class="mt-2">Tagihan<br>ke client lunas pada<br>' + moment.unix(row.paid_bill_at).format('DD MMM YYYY HH:mm:ss') + '</small>';
                                    } else {
                                        text += '<div class="mb-2"></div><small class="mt-2">Akan ditagihkan<br>ke client</small>';
                                    }
                                }
                                text += `<div></div><small class="mt-2">#${row.ord_code}</small>`;
                                for (const child of row.childs) {
                                    if (child.group_merge_code) {
                                        text += '<br>' + child.desc;
                                        text += `<div></div><small class="mt-2">#${child.ord_code}</small>`;
                                    }
                                }
                                return text;
                            },
                        },
                        {
                            data: 'amt_total_flat',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let totalTax = 0,
                                    totalBase = 0;
                                let textTax = '',
                                    textBase = '',
                                    taxType = '';

                                if (row.amt_tax_type == State.tax_type.include) {
                                    taxType = 'Perpajakan: Sudah Termasuk Pajak<br>';
                                    textBase = 'Harga Dasar Rp';
                                    textTax = 'Setelah dikenakan pajak Rp';
                                    totalBase += Number(row.amt_base_flat) * Number(row.unit_qty);
                                    totalTax += Number(row.amt_total_tax_flat) * Number(row.unit_qty);
                                } else if (row.amt_tax_type == State.tax_type.exclude) {
                                    taxType = 'Perpajakan: Belum Termasuk Pajak<br>';
                                    textBase = 'Harga Dasar Rp';
                                    textTax = 'Setelah dikenakan pajak Rp';
                                    totalBase += Number(row.amt_base_flat) * Number(row.unit_qty);
                                    totalTax += Number(data);
                                } else {
                                    taxType = 'Perpajakan: Tanpa Pajak<br>';
                                    textBase = 'Rp';
                                    totalBase += Number(data);
                                }

                                for (const child of row.childs) {
                                    if (child.group_merge_code) {
                                        if (child.amt_tax_type == State.tax_type.include) {
                                            totalBase += Number(child.amt_base_flat) * Number(child.unit_qty);
                                            totalTax += Number(child.amt_total_flat);
                                        } else if (child.amt_tax_type == State.tax_type.exclude) {
                                            totalBase += Number(child.amt_base_flat) * Number(child.unit_qty);
                                            totalTax += Number(child.amt_total_flat);
                                        } else {
                                            totalBase += Number(child.amt_total_flat);
                                        }
                                    }
                                }

                                let text = '';
                                if (row.amt_tax_type == State.tax_type.include) {
                                    text += taxType + textBase + (new Intl.NumberFormat('id-ID')).format(totalBase) + '<br>' + textTax + (new Intl.NumberFormat('id-ID')).format(totalTax) + '<br>';
                                } else if (row.amt_tax_type == State.tax_type.exclude) {
                                    text += taxType + textBase + (new Intl.NumberFormat('id-ID')).format(totalBase) + '<br>' + textTax + (new Intl.NumberFormat('id-ID')).format(totalTax) + '<br>';
                                } else {
                                    text += taxType + textBase + (new Intl.NumberFormat('id-ID')).format(totalBase);
                                }
                                return text;
                            },
                        },
                        {
                            data: 'ddln_pay_at',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (State.ddln_pay_type.time == row.ddln_pay_type) {
                                    if (data == 0) {
                                        return '-';
                                    }
                                    return moment.unix(data).format('DD MMM YYYY HH:mm');
                                } else if (State.ddln_pay_type.ord_finish == row.ddln_pay_type) {
                                    if (row.drop_chk_at != 0) {
                                        return `
                                            <p class="mb-0 text-success small">Pengantaran selesai</p>
                                            <p class="mb-0 text-nowrap small text-muted">${moment.unix(row.drop_chk_at).format('DD MMM YYYY HH:mm')}</p>
                                        `;
                                    } else {
                                        // return '<p class="mb-0 text-danger small">Menunggu pengantaran selesai</p>';
                                        if (row?.previous_termin?.length === 1) {
                                            if (row.previous_termin[0].is_paid == State.is_paid.paid) {
                                                return '<p class="mb-0 text-success small">Pembayaran termin 1 telah selesai</p>';
                                            } else {}
                                        } else {}
                                        return '<p class="mb-0 text-danger small">Menunggu pembayaran termin 1 selesai</p>';
                                    }
                                } else {
                                    return '<p class="mb-0 text-success text-nowrap small">Kapan saja</p>';
                                }
                            },
                        },
                        {
                            data: 'bank_acc_name',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (row.bank_acc_name) {
                                    return `
                                        <p class="mb-0 text-nowrap small">${row.bank_name} (${row.bank_short_name})</p>
                                        <p class="mb-0 text-nowrap small">${row.bank_acc_number}</p>
                                        <p class="mb-0 text-nowrap small">A/N. ${row.bank_acc_name}</p>
                                    `;
                                }
                                return '-';
                            },
                        },
                        {
                            data: 'is_paid',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (State.is_paid.paid == data) {
                                    return `
                                        <p class="mb-0 text-success text-nowrap small">Lunas</p>
                                        <p class="mb-0 text-nowrap small text-muted">${moment.unix(row.paid_at).format('DD MMM YYYY HH:mm')}</p>
                                    `;
                                } else {
                                    return `
                                        <p class="mb-0 text-danger text-nowrap small">Belum Bayar</p>
                                    `;
                                }
                            },
                        },
                    ],
                });
            },
        };

        const ArcvTable = {
            activate: function() {
                ArcvTable.reload();
            },
            reload: function() {
                // $('#tblAdditionalArchv').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                let ord_ids = '';
                const {
                    orders
                } = State;
                for (let iOrd in orders) {
                    ord_ids += `${orders[iOrd].ord_id},`;
                }
                if (ord_ids.slice(-1) === ',') {
                    ord_ids = ord_ids.slice(0, -1);
                }
                $('#tblAdditionalArchv').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_finance_list_adt_items_payments') }}?ord_id=" + ord_ids + "&is_aprv=" + State.is_aprv.no,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            // const data = jqXHR.responseJSON;
                            // 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 = '';
                                if (State.is_aprv.yes != row.is_aprv) {
                                    action += `
                                        <p class="mb-0 text-muted small">Pengajuan ditolak oleh ${row.urjct_name} pada tanggal ${moment.unix(row.rjct_at).format('DD MMM YYYY HH:mm:ss')}</p>
                                    `;
                                    return action;
                                }
                                return action;
                            }
                        },
                        {
                            data: 'desc',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-ord_a_item_id', rowData.ord_a_item_id);
                                $(td).attr('data-ord_id', rowData.ord_id);
                                $(td).attr('data-ord_code', rowData.ord_code);
                                $(td).attr('data-v_termin_id', rowData.v_termin_id);
                            },
                            render: function(data, type, row, meta) {
                                let text = data;
                                if (row.invc_to_client == State.invc_to_client.yes) {
                                    if (State.is_paid.paid == row.is_bill_paid) {
                                        text += '<div class="mb-2"></div><small class="mt-2">Tagihan<br>ke client lunas pada<br>' + moment.unix(row.paid_bill_at).format('DD MMM YYYY HH:mm:ss') + '</small>';
                                    } else {
                                        text += '<div class="mb-2"></div><small class="mt-2">Akan ditagihkan<br>ke client</small>';
                                    }
                                }
                                text += `<div></div><small class="mt-2">#${row.ord_code}</small>`;
                                return text;
                            },
                        },
                        {
                            data: 'amt_total_flat',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let text = 'Rp' + (new Intl.NumberFormat('id-ID')).format(data);
                                return text;
                            },
                        },
                        {
                            data: 'ddln_pay_at',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (State.ddln_pay_type.time == row.ddln_pay_type) {
                                    if (data == 0) {
                                        return '-';
                                    }
                                    return moment.unix(data).format('DD MMM YYYY HH:mm');
                                } else if (State.ddln_pay_type.ord_finish == row.ddln_pay_type) {
                                    if (row.drop_chk_at != 0) {
                                        return `
                                            <p class="mb-0 text-success small">Pengantaran selesai</p>
                                            <p class="mb-0 text-nowrap small text-muted">${moment.unix(row.drop_chk_at).format('DD MMM YYYY HH:mm')}</p>
                                        `;
                                    } else {
                                        // return '<p class="mb-0 text-danger small">Menunggu pengantaran selesai</p>';
                                        return '<p class="mb-0 text-danger small">Menunggu pembayaran termin 1 selesai</p>';
                                    }
                                } else {
                                    return '<p class="mb-0 text-success text-nowrap small">Kapan saja</p>';
                                }
                            },
                        },
                        {
                            data: 'bank_acc_name',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (row.bank_acc_name) {
                                    return `
                                        <p class="mb-0 text-nowrap small">${row.bank_name} (${row.bank_short_name})</p>
                                        <p class="mb-0 text-nowrap small">${row.bank_acc_number}</p>
                                        <p class="mb-0 text-nowrap small">A/N. ${row.bank_acc_name}</p>
                                    `;
                                }
                                return '-';
                            },
                        },
                        {
                            data: 'is_paid',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                if (State.is_paid.paid == data) {
                                    return `
                                        <p class="mb-0 text-success text-nowrap small">Lunas</p>
                                        <p class="mb-0 text-nowrap small text-muted">${moment.unix(row.paid_at).format('DD MMM YYYY HH:mm')}</p>
                                    `;
                                } else {
                                    return `
                                        <p class="mb-0 text-danger text-nowrap small">Belum Bayar</p>
                                    `;
                                }
                            },
                        },
                    ],
                });
            },
        };

        const OrdNoteFnnc = {
            activate: function() {
                OrdNoteFnnc.event();
            },
            event: function() {
                const {
                    orders
                } = State;
                for (let iOrd in orders) {
                    $(`#btnSaveFnncNote${iOrd}`).on('click', function(e) {
                        e.preventDefault();
                        let data = OrdNoteFnnc.getData(iOrd);
                        let isValid = OrdNoteFnnc.checkData(data, true);
                        if (!isValid) return false;
                        OrdNoteFnnc.submitData(data, iOrd);
                    });
                }
            },
            getData: function(no) {
                const data = {};

                data.ord_id = $(`#fnnc-note${no}`).data('ord_id');
                data.fnnc_note = $(`#fnnc-note${no}`).val();

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.fnnc_note.length < 2) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Catatan minimal 2 karakter');
                    return false;
                }
                return true;
            },
            submitData: async function(data, no) {
                return new Promise((resolve, reject) => {
                    if (typeof $(`#btnSaveFnncNote${no}`).attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $(`#btnSaveFnncNote${no}`).attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_save_note', '') }}/" + data.ord_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) => {
                            $(`#btnSaveFnncNote${no}`).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 menyimpan catatan');
                            $('#mdlpayAdd').modal('hide');
                            ATable.reload();
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $(`#btnSaveFnncNote${no}`).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'
                            });
                        }
                    })
                })
            },
        }

        // Compress image
        async function convertImgHtmlToFile(imgHtml, imgWidth, imgHeight, mimeType, fileName) {
            return new Promise((resolve, reject) => {
                try {
                    let canvas = document.createElement("canvas")

                    // Draw image to canvas.
                    canvas.width = imgWidth
                    canvas.height = imgHeight
                    let ctx = canvas.getContext('2d')
                    ctx.drawImage(imgHtml, 0, 0)

                    // Convert canvas to ImageState.
                    let imageData = ctx.getImageData(0, 0, imgWidth, imgHeight)
                    // console.log(imageState.data.byteLength + ' bytes.')

                    // Convert canvas to Blob
                    canvas.toBlob((blob) => {
                        let newReader = new FileReader();
                        newReader.addEventListener('loadend', () => {
                            // Convert canvas to ArrayBuffer
                            let arrayBuffer = newReader.result
                            // console.log(arrayBuffer.byteLength + ' bytes.')

                            // Convert ArrayBuffer to Blob
                            // let blob = new Blob([arrayBuffer], {type: mimeType})

                            // Dispay Blob content in an Image.
                            // console.log(URL.createObjectURL(blob))

                            // Generate as file
                            let newFile = new File([arrayBuffer], fileName, {
                                type: mimeType,
                                lastModified: new Date(),
                                size: arrayBuffer.byteLength,
                            })
                            resolve(newFile)
                        });
                        newReader.readAsArrayBuffer(blob);
                    }, mimeType);
                } catch (e) {
                    reject(e.message)
                }
            });
        }

        const JimpWorkerSingle = {
            worker_up_paid_proof: null,
            // add item
            worker_is_paid_proof: null,
            worker_submission_proof: null,
            activate: function(x) {
                let linkWorker = State.file_jimp_worker
                this.setWorker(linkWorker, x, function(res) {
                    if (res.stts) {
                        let pureDataURL = res.data.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                        let fileSize = window.atob(pureDataURL).length // in Byte
                        // (fileSize/1000) + ' Kb'
                        $('#inpt-group_' + x + '_spinner').addClass('d-none');
                        $('#inpt-' + x + '-status').html('Compressed')
                        $('#inpt-' + x + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                        $('#inpt-' + x + '-img').removeClass('d-none')
                        $('#inpt-' + x + '-img').attr('src', res.data)
                        $('#inpt-' + x + '-base64').val(res.data)
                    } else {
                        console.error(res.data)
                    }
                    $('.page-loader-wrapper').fadeOut()
                });
            },
            runWorker: function(dataURL, x) {
                $('#inpt-group_' + x + '_spinner').removeClass('d-none');
                this['worker_' + x].postMessage(dataURL)
            },
            setWorker: function(urlFileJs, x, cbFinish) {
                let worker = new Worker(urlFileJs);
                worker.onmessage = function(e) {
                    // e = {status:(true,false), data:(dataURL)}

                    // append a new img element using the base 64 image
                    // let img = document.createElement('img');
                    // img.setAttribute('src', e.data);
                    // document.body.appendChild(img);

                    cbFinish(e.data);
                };
                this['worker_' + x] = worker
            }
        }
        const FileUploadSingle = {
            activate: function(x) {
                this.initReader(x)
                JimpWorkerSingle.activate(x)
                this.event(x)
                RotateImgSingle.activate(x)
            },
            event: function(x) {
                $('#inpt-' + x + '-choose').on('click', function(e) {
                    $('#inpt-' + x + '-file').trigger('click')
                })
                // $('#inpt-' + x + '-file').on('click', function() {
                //     $('#inpt-' + x + '-file').val();
                // })
            },
            initReader: function(x) {
                let reader = new FileReader();
                reader = this.setEventFile(reader, x);
                $('#inpt-' + x + '-file').on('change', async function(e) {
                    try {
                        if (browserBack()) return false;
                        FileUploadSingle.clearFile(x);
                        let file = e.target.files[0];
                        let type = file.type.split('/');
                        if (type[1] == 'jpeg' || type[1] == 'png' || type[1] == 'jpg') {
                            $('.page-loader-wrapper').fadeIn()

                            // fix auto rotate when select file
                            let newImg = await loadImage(file, {
                                orientation: true
                            })

                            let newFile = await convertImgHtmlToFile(newImg.image, newImg
                                .originalWidth, newImg.originalHeight, file.type, file
                                .name)

                            FileUploadSingle.readFile(reader, newFile);

                            $('#inpt-' + x + '-status').html('Loading on compressing...')
                        } else if (type[1] == 'pdf') {
                            // 1mb binary
                            if (file.size > 1048576) Helper.toast('Validasi', 'just-now', 'Maksimal size pdf 1MB');
                            FileUploadSingle.readFile(reader, file);
                        } else {
                            Helper.toast('Validasi', 'just-now', 'File tidak valid');
                        }
                    } catch (e) {
                        console.error(e.message)
                    }
                })
            },
            setEventFile: function(reader, x) {
                reader.onload = function(e) {
                    let data = e.target.result;
                    if (data.indexOf('data:image') > -1) {
                        $('#inpt-' + x + '-img-old').attr('src',
                            data) // preview, -old mungkin kedepannya bakal diganti jadi -new
                        // $('#inpt-'+x+'-img-base64').val(data) // real-data
                        console.log('Compressing ' + x);
                        JimpWorkerSingle.runWorker(data, x)
                        RotateImgSingle.toggleBtnRotate(x, 'show');
                    } else if (data.indexOf('data:application') > -1) {
                        $('#inpt-' + x + '-base64').val(data);
                    }
                };

                reader.onerror = function(err) {
                    $('.page-loader-wrapper').fadeOut()
                    $('#' + x).attr('hidden', true)
                    console.error(err);
                };

                reader.onabort = function(err) {
                    console.log(err);
                }

                return reader;
            },
            readFile: function(reader, file) {
                // reader.readAsArrayBuffer(file);
                reader.readAsDataURL(file);
            },
            clearFile: function(x) {
                $('#inpt-' + x + '-img').addClass('d-none')
                $('#inpt-' + x + '-filesize').html('');
                $('#inpt-' + x + '-base64').val('');
                // $('#inpt-' + x + '-img').attr('src', '');
                RotateImgSingle.toggleBtnRotate(x, 'hidden');
            },
        }
        const RotateImgSingle = {
            activate: function(id) {
                this.event(id)
            },
            event: function(id) {
                $('#inpt-group_rotate_' + id).on('click', '.btnRotateRight', function(e) {
                    $('#inpt-' + id + '-img').addClass('d-none')
                    RotateImgSingle.rotateBase64Image($('#inpt-' + id + '-base64').val(), 90).then(
                        function(base64) {
                            RotateImgSingle.updateImg(id, base64)
                        })
                })
                $('#inpt-group_rotate_' + id).on('click', '.btnRotateLeft', function(e) {
                    $('#inpt-' + id + '-img').addClass('d-none')
                    RotateImgSingle.rotateBase64Image($('#inpt-' + id + '-base64').val(), -90).then(
                        function(base64) {
                            RotateImgSingle.updateImg(id, base64)
                        })
                })
            },
            rotateBase64Image: function(base64data, degrees) {
                return new Promise((resolve, reject) => {
                    try {
                        let x = 0,
                            y = 0,
                            w = 0,
                            h = 0;
                        let canvas = document.createElement("canvas");
                        let image = document.createElement("img"); // new Image();
                        image.src = base64data; // image.src = 'data:image/jpg;base64,' + base64data;
                        image.onload = function() {
                            // current image size for processing rotate
                            w = image.width;
                            h = image.height;
                            let angle = degrees * Math.PI / 180.0; // angle/rads
                            let ctx = canvas.getContext("2d");

                            // new image size for after cropped
                            let c = Math.cos(angle);
                            let s = Math.sin(angle);
                            if (s < 0) {
                                s = -s;
                            }
                            if (c < 0) {
                                c = -c;
                            }
                            let rw = h * s + w * c;
                            let rh = h * c + w * s;

                            // set canvas size
                            canvas.width = rw;
                            canvas.height = rh;
                            // save the unrotated context of the canvas so we can restore it later
                            // the alternative is to untranslate & unrotate after drawing
                            ctx.save();
                            // draw the rect in the center of the newly sized canvas
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            // move to the center of the canvas
                            // ctx.translate(x+w/2, y+h/2); // ctx.translate(x, h);
                            // move to the upper left corner when rotating in 90deg increments
                            ctx.translate(Math.abs(w / 2 * Math.cos(angle) + h / 2 * Math.sin(angle)),
                                Math.abs(h / 2 * Math.cos(angle) + w / 2 * Math.sin(angle)));
                            // rotate the canvas to the specified degrees
                            ctx.rotate(angle); // ctx.rotate(180 * Math.PI / 180);
                            // move to the center of the canvas (origin)
                            ctx.translate(-x - w / 2, -y - h / 2);
                            // since the context is rotated, the image will be rotated also
                            ctx.drawImage(image, 0, 0, w, h);
                            // we’re done with the rotating so restore the unrotated context
                            ctx.restore();
                            // convert to base64
                            resolve(canvas.toDataURL('image/jpeg', 1.0));
                        };
                    } catch (err) {
                        reject(err);
                    }
                });
            },
            updateImg: function(id, base64) {
                // update data
                let pureDataURL = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, '')
                let fileSize = window.atob(pureDataURL).length // in Byte
                // (fileSize/1000) + ' Kb'
                $('#inpt-' + id + '-status').html('Compressing...')
                $('#inpt-' + id + '-filesize').html('<samp>(' + fileSize / 1000 + ' Kb)</samp>')
                $('#inpt-' + id + '-img').attr('src', base64)
                $('#inpt-' + id + '-base64').val(base64) // real-data

                // compress again because base64 from rotate is rather bigger in range 200kb than compress 50kb
                JimpWorkerSingle.runWorker(base64, id);
            },
            toggleBtnRotate: function(id, hide = 'hidden') {
                if (hide == 'show') {
                    $('#inpt-group_rotate_' + id).removeClass('d-none')
                    return true;
                }
                $('#inpt-group_rotate_' + id).addClass('d-none')
                return true;
            },
        }

        Wrapper.activate();
    </script>
@endsection
