@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-6" id="">
                    <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>
                                    @if ($order->crt_type_order === \App\Models\Orders::CRT_TYPE_ORDER_ADMIN_SPECIAL)
                                        <span class="badge bg-warning text-dark">Pesanan Khusus</span>
                                    @endif
                                </div>
                                <div class="col text-end">
                                    <button class="btn btn-secondary btn-sm" onclick="location.href='{{ route('view_keuangan_billing') }}'">Kembali</button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <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-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-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</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->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 ($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-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-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 Client</p>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Nama Client</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0">{{ $order->c_pt_name }}</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-sm-12">
                                            <label for="" class="form-label">PIC</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0">{{ $order->c_pt_pic_name }}</p>
                                                    <p class="mb-0">
                                                        <a href="tel:0{{ $order->c_pt_pic_phone_val }}">
                                                            <i class="text-dark ion-ios-telephone me-2"></i>
                                                            {{ implode(' ', str_split('0' . $order->c_pt_pic_phone_val, 4)) }}
                                                        </a>
                                                    </p>
                                                    <p class="mb-0">
                                                        <a href="https://api.whatsapp.com/send/?phone=0{{ $order->c_pt_pic_phone_val }}&amp;text=Halo&amp;app_absent=0" class="" target="_blank"><i class="text-success ion-social-whatsapp me-1"></i>
                                                            {{ implode(' ', str_split('0' . $order->c_pt_pic_phone_val, 4)) }}
                                                        </a>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-end">
                            <button type="button" id="btnChangePICInvoice" class="btn btn-primary btn-sm">Ganti PIC Invoice</button>
                        </div>
                    </div>
                </div>
                {{-- berkas driver --}}
                <div class="col-sm-6">
                    @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
                    {{-- invoicing termin 1 --}}
                    @php
                        $prev_yi = 0;
                    @endphp
                    @foreach ($group_items_by_termin as $yi => $y)
                        @php
                            $result_is_enable_btn = App\Helper::viewBillFncIsEnableBtn(isset($group_items_by_termin[$prev_yi]) ? $group_items_by_termin[$prev_yi][0] : 0, $y[0]);
                            $sub_total = 0;
                            $invc_items = '';
                        @endphp
                        <div class="card">
                            <div class="card-header">
                                <div class="row d-flex align-items-center justify-content-between">
                                    <div class="col">
                                        <p class="card-title text-bold mb-0">Data Penagihan | Termin {{ $y[0]->termin_sequence }}</p>
                                        @if ($result_is_enable_btn === 0)
                                            {{-- <small class="text-danger">Menunggu Pengantaran Selesai</small> --}}
                                            <small class="text-danger">Menunggu Pembayaran Termin 1 Selesai</small>
                                        @elseif ($result_is_enable_btn === 2)
                                            <small class="text-muted">Pengantaran Selesai pada {{ date('d-m-Y H:i', $y[0]->drop_chk_at) }}</small>
                                        @elseif ($result_is_enable_btn === 4)
                                            <small class="text-success">Penagihan telah dibayar pada {{ date('d-m-Y H:i', $y[0]->termin_paid_at) }}</small>
                                        @endif
                                    </div>
                                    @if ($result_is_enable_btn === 1 || $result_is_enable_btn === 2)
                                        <div class="col-auto text-end ps-0">
                                            <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#mdlTax">Pajak</button>
                                        </div>
                                        <div class="col-auto text-end ps-0">
                                            <button class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#mdlDiskon">Diskon</button>
                                        </div>
                                        <div class="col-auto text-end ps-0">
                                            <button class="btn btn-sm btn-primary" id="btnMdlNewAdtItem">Tambah Item</button>
                                        </div>
                                    @elseif ($result_is_enable_btn === 3)
                                        <div class="col-auto text-end ps-0">
                                            <small class="text-danger">Termin sebelumnya belum selesai</small>
                                        </div>
                                    @endif
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table" id="tblInvoice">
                                        <thead>
                                            <tr class="">
                                                <th class="">#</th>
                                                <th class=""></th>
                                                <th class="">Item</th>
                                                <th class="text-nowrap text-end">Jumlah</th>
                                                <th class="">Satuan</th>
                                                <th class="text-nowrap text-end">Harga (Rp)</th>
                                                <th class="text-nowrap text-end">Total (Rp)</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($y as $xi => $x)
                                                @php
                                                    $amt_bill_base_flat = $x->amt_bill_base_flat;
                                                    $amt_bill_total_flat = $x->amt_bill_total_flat;
                                                    if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE) {
                                                        $before_ppn = round($amt_bill_base_flat / \App\Models\OrdersAItems::PPN_PERCENT_INCLUDE);
                                                        $ppn = round($amt_bill_base_flat - $before_ppn);
                                                        $amt_bill_base_flat = round($before_ppn);
                                                        $amt_bill_total_flat = round($amt_bill_base_flat * $x->unit_qty);
                                                    } else {
                                                        $amt_bill_total_flat = round($amt_bill_base_flat * $x->unit_qty);
                                                    }
                                                @endphp
                                                <tr class="">
                                                    <td class="small">{{ $xi + 1 }}</td>
                                                    <td class="small">
                                                        @if ($x->a_item_type != \App\Models\OrdersAItems::A_TYPE_PRIMARY)
                                                            @if ($result_is_enable_btn === 1 || $result_is_enable_btn === 2)
                                                                <a href="javascript:void(0)" class="text-primary btnDelItem"><span class="icon ion-trash-b fz-16"></span></a>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td class="small" data-ord_a_item_id="{{ $x->ord_a_item_id }}">
                                                        {!! $x->desc !!}
                                                    </td>
                                                    <td class="small text-nowrap text-end">{{ $x->unit_qty }}</td>
                                                    <td class="small">{{ $x->unit_type_name }}</td>
                                                    <td class="small text-nowrap text-end">{{ number_format($amt_bill_base_flat, 0, ',', '.') }}</td>
                                                    <td class="small text-nowrap text-end">{{ number_format($amt_bill_total_flat, 0, ',', '.') }}</td>
                                                    @php
                                                        $sub_total += $amt_bill_total_flat;
                                                        $invc_items .= "$x->ord_a_item_id,";
                                                    @endphp
                                                </tr>
                                            @endforeach
                                        </tbody>
                                        <tfooter>
                                            @php
                                                $total = $sub_total;
                                                $sign_tax = '';
                                                if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE) {
                                                    $ppn_flat = round(($sub_total * $y[0]->termin_tax_ppn_percent) / 100);
                                                    $before_ppn = round($sub_total - $ppn_flat); // +
                                                    $pph_flat = round(0 * -1 * (($before_ppn * $y[0]->termin_tax_pph_percent) / 100)); // -1 *
                                                    $before_ppn_pph = round($sub_total + $ppn_flat + $pph_flat); // + +
                                                    $tax_flat = round($ppn_flat + $pph_flat);
                                                    $total = round($before_ppn_pph);
                                                    // $sign_tax = '-';
                                                }
                                                // $disc_flat = round($x->invc_disc_flat) ?? 0; ngebug kalo diskon sudah ada tetapi ada item baru, kalkulasinya tidak terupdate tetapi ke yang lama
                                                if ($x->invc_disc_type === \App\Models\OrdersAItems::AMT_TYPE_FLAT) {
                                                    $disc_flat = round($x->invc_disc_flat);
                                                } else {
                                                    $disc_flat = round(($total / 100) * $x->invc_disc_percent);
                                                }
                                                $pengurangan_disc = round($total - ($disc_flat ?? 0));
                                                $total = $pengurangan_disc;
                                                if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE) {
                                                    $ppn_flat = round(($total * $y[0]->termin_tax_ppn_percent) / 100);
                                                    $after_ppn = round($total + $ppn_flat);
                                                    $pph_flat = round((0 * $after_ppn * $y[0]->termin_tax_pph_percent) / 100);
                                                    $tax_flat = round($ppn_flat + $pph_flat);
                                                    $total += $tax_flat;
                                                } elseif ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_WITHOUT) {
                                                    $ppn_flat = 0;
                                                    $pph_flat = 0;
                                                    $tax_flat = 0;
                                                }
                                            @endphp
                                            <tr class="border-0">
                                                <td class="text-nowrap text-end border-0" colspan="6">Sub total</td>
                                                @if ($result_is_enable_btn === 1 || $result_is_enable_btn === 2)
                                                    <td id="subTotal" class="text-nowrap text-end border-0" data-items="{{ $invc_items }}" data-subtotal="{{ round($sub_total) }}" data-terminid="{{ $x->c_group_termin_id }}" data-taxtype="{{ $y[0]->termin_tax_type }}" data-ppnpercent="{{ $y[0]->termin_tax_ppn_percent }}" data-ppnflat="{{ round($ppn_flat) }}" data-pphpercent="{{ $y[0]->termin_tax_pph_percent * 0 }}" data-pphflat="{{ round($pph_flat) }}" data-taxflat="{{ round($tax_flat) }}" data-disctype="{{ $x->invc_disc_type ?? 0 }}" data-discpercent="{{ $x->invc_disc_percent ?? 0 }}" data-discflat="{{ round($disc_flat ?? 0) }}" data-total="{{ round($total) }}">
                                                        @if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE)
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @elseif ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE)
                                                            {{-- {{ number_format($before_ppn_pph, 0, ',', '.') }} --}}
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @else
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @endif
                                                    </td>
                                                @else
                                                    <td class="text-nowrap text-end border-0">
                                                        @if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE)
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @elseif ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE)
                                                            {{-- {{ number_format($before_ppn_pph, 0, ',', '.') }} --}}
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @else
                                                            {{ number_format($sub_total, 0, ',', '.') }}
                                                        @endif
                                                    </td>
                                                @endif
                                            </tr>
                                            @if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE)
                                                <td class="text-nowrap text-end border-0" colspan="6">
                                                    @if ($x->invc_disc_type === \App\Models\OrdersInvoices::AMT_TYPE_PERCENT)
                                                        Diskon ({{ $x->invc_disc_percent }}%)
                                                    @else
                                                        Diskon
                                                    @endif
                                                </td>
                                                <td class="text-nowrap text-end border-0">{{ $disc_flat > 0 ? '-' . number_format($disc_flat, 0, ',', '.') : $disc_flat }}</td>
                                                <tr class="border-bottom">
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;" colspan="6">PPN ({{ $y[0]->termin_tax_ppn_percent }}%)</td>
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;">{{ $sign_tax . number_format($ppn_flat, 0, ',', '.') }}</td>
                                                </tr>
                                                @if ($pph_flat > 0)
                                                    <tr class="border-0">
                                                        <td class="text-nowrap text-end border-0" colspan="6">PPH ({{ $y[0]->termin_tax_pph_percent }}%)</td>
                                                        <td class="text-nowrap text-end border-0">{{ $sign_tax . number_format($pph_flat, 0, ',', '.') }}</td>
                                                    </tr>
                                                @endif
                                            @elseif ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE)
                                                <tr class="border-0">
                                                    <td class="text-nowrap text-end border-0" colspan="6">
                                                        @if ($x->invc_disc_type === \App\Models\OrdersInvoices::AMT_TYPE_PERCENT)
                                                            Diskon ({{ $x->invc_disc_percent }}%)
                                                        @else
                                                            Diskon
                                                        @endif
                                                    </td>
                                                    <td class="text-nowrap text-end border-0">{{ $disc_flat > 0 ? '-' . number_format($disc_flat, 0, ',', '.') : $disc_flat }}</td>
                                                </tr>
                                                <tr class="border-bottom">
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;" colspan="6">PPN ({{ $y[0]->termin_tax_ppn_percent }}%)</td>
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;">{{ $sign_tax . number_format($ppn_flat, 0, ',', '.') }}</td>
                                                </tr>
                                                @if ($pph_flat > 0)
                                                    <tr class="border-0">
                                                        <td class="text-nowrap text-end border-0" colspan="6">PPH ({{ $y[0]->termin_tax_pph_percent }}%)</td>
                                                        <td class="text-nowrap text-end border-0">{{ $sign_tax . number_format(-1 * $pph_flat, 0, ',', '.') }}</td>
                                                    </tr>
                                                @endif
                                            @else
                                                <tr class="border-bottom">
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;" colspan="6">
                                                        @if ($x->invc_disc_type === \App\Models\OrdersInvoices::AMT_TYPE_PERCENT)
                                                            Diskon ({{ $x->invc_disc_percent }}%)
                                                        @else
                                                            Diskon
                                                        @endif
                                                    </td>
                                                    <td class="text-nowrap text-end border-bottom" style="border-bottom: 1px solid !important;">{{ $disc_flat > 0 ? '-' . number_format($disc_flat, 0, ',', '.') : $disc_flat }}</td>
                                                </tr>
                                            @endif
                                        </tfooter>
                                        <tfooter>
                                            <tr class="bg-light">
                                                <td class="text-nowrap text-end border-0 text-bold" colspan="6">TOTAL</td>
                                                <td class="text-nowrap text-end border-0 text-bold">
                                                    @if ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_EXCLUDE)
                                                        {{ number_format($total, 0, ',', '.') }}
                                                    @elseif ($y[0]->termin_tax_type === \App\Models\OrdersAItems::AMT_TAX_TYPE_INCLUDE)
                                                        {{-- {{ number_format($sub_total - ($disc_flat ?? 0), 0, ',', '.') }} --}}
                                                        {{ number_format($total, 0, ',', '.') }}
                                                    @else
                                                        {{ number_format($total, 0, ',', '.') }}
                                                    @endif
                                                </td>
                                            </tr>
                                        </tfooter>
                                    </table>
                                </div>
                            </div>
                            @if ($result_is_enable_btn === 1 || $result_is_enable_btn === 2)
                                <div class="card-footer">
                                    <div class="row d-flex align-items-center justify-content-between">
                                        <div class="{{ $x->invc_id === null ? 'col-8' : 'col-lg-5 col-md-4' }}">
                                            <p class="mb-0">
                                                Apakah item diatas sudah seluruhnya di masukkan?
                                            </p>
                                        </div>
                                        <div class="col-auto text-end d-flex">
                                            @if ($x->invc_id !== null && $x->is_gnrt_invc === \App\Models\OrdersInvoices::IS_GNRT_INVC_YES)
                                                {{-- {{ asset('pdf/invoice.pdf') }} --}}
                                                <button type="button" id="confirmInvc" class="btn btn-warning btn-block btn-sm text-nowrap" data-bs-toggle="modal" data-bs-target="#mdlConfirmInvc" data-id={{ $x->invc_id }} data-code={{ $x->invc_code }}>
                                                    Konfirmasi Pembayaran</button>
                                            @endif
                                            {{-- {{ asset('pdf/invoice.pdf') }} --}}
                                            <a href="#" target="_blank" id="btnGnrtInvc" class="btn btn-primary btn-block btn-sm text-nowrap">Generate Invoice</a>
                                        </div>
                                    </div>
                                </div>
                            @else
                                @if ($y[0]->amt_bill_confirm !== 0)
                                    <div class="card-footer">
                                        <div class="row d-flex align-items-center justify-content-between">
                                            <div class="col-8">
                                                <p class="mb-0"><span class="fw-bold">Nilai yang diterima:</span> <span class="fw-bold">Rp{{ number_format($y[0]->amt_bill_confirm, 0, ',', '.') }}</span></p>
                                                <p class="mb-0"><span class="fw-bold">Keterangan:</span></p>
                                                <p class="mb-0"><span class="">{!! nl2br($y[0]->amt_bill_confirm_note) !!}</span></p>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                            @endif
                        </div>
                        @php
                            $prev_yi += $yi;
                        @endphp
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    {{-- Modal --}}
    <div class="modal" id="mdlDiskon" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlDiskonLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlDiskonLabel">Tambah Diskon</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="addDisc" class="form-label">Tipe Diskon</label>
                        <select name="addDisc" id="addDisc" class="select2 form-control" style="width: 100% !important">
                            <option value="0" selected>Tidak ada tipe diskon yang dipilih</option>
                            <option value="{{ \App\Models\OrdersInvoices::AMT_TYPE_FLAT }}">Fixed</option>
                            <option value="{{ \App\Models\OrdersInvoices::AMT_TYPE_PERCENT }}">Percent</option>
                        </select>
                    </div>
                    <div id="disFieldWrapper" class="d-none">
                        <div id="groupDiscPercent" class="mb-3">
                            <label for="discPercent" class="form-label">Masukkan Diskon (%)</label>
                            <input class="form-control" type="number" min="1" max="100" name="discPercent" id="discPercent">
                        </div>
                        <div id="groupDiscFlat" class="mb-3">
                            <label for="discFlat" class="form-label">Besaran Diskon (Rp)</label>
                            <input class="form-control" type="text" name="discFlat" id="discFlat">
                        </div>
                    </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="btnSaveDisc">Save</button>
                </div>
            </div>
        </div>
    </div>
    <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 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 class="mb-3">
                            <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 d-none">
                            <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 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 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>
                <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="btnSubmitAddItem">Save</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="mdlConfirmInvc" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlConfirmInvcLabel" 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="mdlConfirmInvcLabel"></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="">
                        <div class="mb-3">
                            <label for="amt_bill_confirm" class="form-label">Nilai yang diterima <span class="text-danger">*</span></label>
                            <input type="text" name="amt_bill_confirm" id="amt_bill_confirm" class="form-control" value="0">
                        </div>
                        <div class="mb-3">
                            <label for="amt_bill_confirm_note" class="form-label">Keterangan </label>
                            <textarea name="amt_bill_confirm_note" id="amt_bill_confirm_note" class="form-control" cols="30" rows="3"></textarea>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" name="isCheckConfirmInvc" type="checkbox" value="yes" id="isCheckConfirmInvc">
                            <label class="form-check-label text-dark" for="isCheckConfirmInvc">
                                Setelah konfirmasi pembayaran maka data penagihan yang dikonfirmasi akan diClose dan tidak bisa dirubah
                            </label>
                        </div>
                    </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="btnConfirmInvc" disabled>Konfirmasi</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="mdlTax" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="mdlTaxLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlTaxLabel">Perpajakan</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="add-invc_tax_type" class="form-label">Perpajakan <span class="text-danger">*</span></label>
                        <select name="add-invc_tax_type" id="add-invc_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 groupTaxTax d-none">
                        <div class="col">
                            <label for="add-invc_tax_ppn_percent" class="form-label">Percent PPN % <span class="text-danger">*</span></label>
                            <input type="number" name="add-invc_tax_ppn_percent" id="add-invc_tax_ppn_percent" class="form-control" readonly>
                        </div>
                        <div class="col d-none">
                            <label for="add-invc_tax_pph_percent" class="form-label">Percent PPH % <span class="text-danger">*</span></label>
                            <input type="number" name="add-invc_tax_pph_percent" id="add-invc_tax_pph_percent" class="form-control" readonly>
                        </div>
                    </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="btnSaveTax">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="mdlChangePICInvoice" aria-labelledby="mdlChangePICInvoiceLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="mdlChangePICInvoiceLabel">Ganti PIC Invoice</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="formUpdt">
                        <div class="mb-3">
                            <p class="text-danger text-bold mb-0">Ganti PIC Invoice</p>
                            <small>Ganti PIC Invoice</small>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="mb-3">
                                    <div class="col-12">
                                        <label for="c_pt_name" class="form-label text-nowrap">Nama Perusahaan <span class="text-danger">*</span></label>
                                    </div>
                                    <input type="text" name="c_pt_name" id="c_pt_name" class="form-control" value="{{ $order->c_pt_name }}">
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="mb-3">
                                    <div class="col-12">
                                        <label for="c_pt_addr" class="form-label text-nowrap">Alamat Perusahaan <span class="text-danger">*</span></label>
                                    </div>
                                    <textarea name="c_pt_addr" id="c_pt_addr" class="form-control" rows="3" style="width:100%;">{{ $order->c_pt_addr }}</textarea>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="mb-3">
                                    <div class="col-12">
                                        <label for="c_pt_pic_name" class="form-label text-nowrap">Nama PIC <span class="text-danger">*</span></label>
                                    </div>
                                    <input type="text" name="c_pt_pic_name" id="c_pt_pic_name" class="form-control" value="{{ $order->c_pt_pic_name }}">
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="mb-3">
                                    <div class="col-12">
                                        <label for="c_pt_pic_phone_val" class="form-label text-nowrap">Phone PT PIC <span class="text-danger">*</span></label>
                                    </div>
                                    <input type="number" name="c_pt_pic_phone_val" id="c_pt_pic_phone_val" class="form-control" value="{{ $order->c_pt_pic_phone_val }}" placeholder="Tanpa nol didepan">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button id="btnSubmitChangePICInvoice" type="button" class="btn btn-sm btn-danger">Ganti</button>
                    <div id="btnSubmitChangePICInvoiceSpinner" class="d-none">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {{-- ./Modal --}}
@endsection

@section('customjs')
    <script>
        // $('#tblInvoice').DataTable({
        //     bSort: false,
        //     searching: false,
        //     paging: false,
        //     info: false
        // });
        // $('#slctItem').select2({
        //     dropdownParent: $('#mdlAddItem')
        // });
        // $('#addDisc').select2({
        //     dropdownParent: $('#mdlDiskon')
        // });
        // $('#slctItem').on('change', function() {
        //     var data = $("#slctItem option:selected").val();
        //     console.log(data)
        //     if(data == 99999999){
        //         let a = `
    //             <div id="addNewItemContent">
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Nama Item</label>
    //                     <input type="text" class="form-control">
    //                 </div>
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Satuan</label>
    //                     <select name="" id="" class="select2 form-control" style="width: 100% !important">
    //                         <option value="none" selected disabled>Belum ada satuan yang dipilih</option>
    //                         <option value="">Paket</option>
    //                         <option value="">Unit</option>
    //                         <option value="">Pcs</option>
    //                     </select>
    //                 </div>
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Harga</label>
    //                     <input type="number" class="form-control">
    //                 </div>
    //         `
        //         $('#addNewItemWrapper').html(a)
        //         $('.select2').select2({
        //             dropdownParent: $('#mdlAddItem')
        //         });
        //     } else {
        //         $('#addNewItemContent').remove()
        //     }
        // })

        // $('#addDisc').on('change', function() {
        //     var data = $("#addDisc option:selected").val();
        //     console.log(data)
        //     // fixed
        //     if(data == 1){
        //         let a = `
    //             <div id="disFieldContent">
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Besaran Diskon (Rp)</label>
    //                     <input class="form-control" type="number" id="">
    //                 </div>
    //             </div>
    //         `
        //         $('#disFieldContent').remove()
        //         $('#disFieldWrapper').html(a)
        //     } else if (data == 2) {
        //         let a = `
    //             <div id="disFieldContent">
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Masukkan Diskon (%)</label>
    //                     <input class="form-control" type="number" min="1" max="100" id="">
    //                 </div>
    //                 <div class="mb-3">
    //                     <label for="" class="form-label">Besaran Diskon (Rp)</label>
    //                     <input class="form-control" type="number" id="" readonly>
    //                 </div>
    //             </div>
    //         `
        //         $('#disFieldContent').remove()
        //         $('#disFieldWrapper').html(a)
        //     } else {
        //         $('#disFieldContent').remove()
        //     }
        // if(data == 99999999){
        //     let a = `
    //         <div id="addNewItemContent">
    //             <div class="mb-3">
    //                 <label for="" class="form-label">Nama Item</label>
    //                 <input type="text" class="form-control">
    //             </div>
    //             <div class="mb-3">
    //                 <label for="" class="form-label">Satuan</label>
    //                 <select name="" id="" class="select2 form-control" style="width: 100% !important">
    //                     <option value="none" selected disabled>Belum ada satuan yang dipilih</option>
    //                     <option value="">Paket</option>
    //                     <option value="">Unit</option>
    //                     <option value="">Pcs</option>
    //                 </select>
    //             </div>
    //             <div class="mb-3">
    //                 <label for="" class="form-label">Harga</label>
    //                 <input type="number" class="form-control">
    //             </div>
    //     `
        //     $('#addNewItemWrapper').html(a)
        //     $('.select2').select2({
        //         dropdownParent: $('#mdlAddItem')
        //     });
        // } else {
        //     $('#addNewItemContent').remove()
        // }
        // })
    </script>
    <script>
        'use strict'

        const State = {
            ord_id: "{{ $order->ord_id }}",
            ord_code: "{{ $order->ord_code }}",
            set_pck_at: "{{ $order->set_pck_at }}",
            fix_price_at: "{{ $order->fix_price_at }}",
            order_place_at: "{{ $order->crt }}",
            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 }}",
            },
            only_client: {
                not: "{{ App\Models\OrdersAItems::ONLY_CLIENT_NO }}",
                yes: "{{ App\Models\OrdersAItems::ONLY_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 }}",
            },
            invc_amt_type: {
                flat: "{{ \App\Models\OrdersInvoices::AMT_TYPE_FLAT }}",
                percent: "{{ \App\Models\OrdersInvoices::AMT_TYPE_PERCENT }}",
            },
            stts_gnrt_invc: {
                no: "{{ \App\Models\OrdersInvoices::IS_GNRT_INVC_NO }}",
                yes: "{{ \App\Models\OrdersInvoices::IS_GNRT_INVC_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 }}",
            },
            ord_pck_drop: {
                is_aprv_no: "{{ App\Models\OrdersPckDrop::IS_APRV_NO }}",
                is_aprv_yes: "{{ App\Models\OrdersPckDrop::IS_APRV_YES }}",
            },
            ord: {
                ord_id: "{{ $order->ord_id }}",
                ord_code: "{{ $order->ord_code }}",
                ord_client_id: "{{ $order->ord_client_id }}",
                c_pt_id: "{{ $order->c_pt_id }}",
            },
            aprv_pck_at: "{{ $order->aprv_pck_at }}",
            delay_type_number: 1000,
            adtPoints: JSON.parse('{!! $adtPointsJson !!}'),
            storage_lara: "{{ asset('storage') }}/",
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            route_download_invc: "{{ route('view_finance_download_invoice') }}",
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                OrdView.activate();
                OrdAItem.activate();
                OrdInvc.activate();
                OrdTax.activate();
                OrdPayInvc.activate();
                OrdDelItem.activate();
                ChangePICInvoice.activate();
            },
            event: function() {
                $('#view-pickup_at').text(moment.unix(State.set_pck_at).format('DD MMM YYYY HH:mm:ss'));
                $('#view-pickup_date_at').text(moment.unix(State.set_pck_at).format('DD MMM YYYY'));
                $('#view-pickup_time_at').text(moment.unix(State.set_pck_at).format('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');

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

                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'
                            });
                        }
                    })
                });
            },
            initDateAdtPoints: function() {
                for (let iAdtPoint in State.adtPoints) {
                    iAdtPoint = Number(iAdtPoint);
                    $(`#view-pickup_date_at${iAdtPoint+1}`).text(moment.unix(State.adtPoints[iAdtPoint].set_pck_at).format('DD MMM YYYY'));
                    $(`#view-pickup_time_at${iAdtPoint+1}`).text(moment.unix(State.adtPoints[iAdtPoint].set_pck_at).format('HH:mm:ss'));
                }
            },
        };

        const OrdAItem = {
            activate: function() {
                OrdAItem.event();
            },
            event: function() {
                // init select2
                $('#slcItem').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_type').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_bill_tax_type').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');
                        $('#slcItemPrice').text('');
                    } else {
                        $('#addNewItemWrapper').addClass('d-none');
                        OrdAItem.clearInputAddNewItem();
                        $('#slcItemPrice').text('Harga: Rp' + (new Intl.NumberFormat('id-ID')).format(slc.data('price')));
                    }
                });
                // input
                $('#add-item_price').on('keyup', function() {
                    let price = $('#add-item_price').val().split('.').join('').replace(/[$,]+/g, ".");
                    $('#add-item_price').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                // 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);
                });
                OrdAItem.eventTax();
            },
            eventTax: function() {
                // 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);
                });
                $('#slcItem').on('change', function() {
                    // $('#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));
                });
                let newItemTimeoutBill = null;
                $('#add-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 = 'client') {
                let calc = {};

                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()),
                    };
                    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.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;
                }

                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('').replace(/[$,]+/g, ".");
                    data.a_invc_price = $('#add-item_price').val().split('.').join('').replace(/[$,]+/g, ".");
                    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.a_invc_price = slcType.data('price');
                    data.is_adm_price = slcType.data('is_adm_price');
                }
                let calcTaxClient = OrdAItem.calcTax('client');
                data.a_invc_price_tax_type = State.tax_type.without;
                // 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.a_qty = $('#add-item_qty').val();

                data.is_invc_to_client = State.invc_to_client.yes;
                data.only_client = State.only_client.yes;
                data.cash_type = State.cash_type.in;
                data.flow_type = State.flow_type.billing;

                data.ord_id = State.ord_id;
                data.ddln_pay_type = State.ddln_pay_type.time;
                data.is_calc_to_vdr = State.calc_to_vdr.no;
                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_invc_price < 0) {
                    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;
                }
                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');
                            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'
                            });
                        }
                    })
                })
            },
            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');
            },
        };

        const OrdInvc = {
            activate: function() {
                OrdInvc.event();
                // OrdInvc.updtInvc();
            },
            updtInvc: function() {
                if ($('#confirmInvc').data('id')) {
                    let data = OrdInvc.getData('gnrt_invc');
                    let isValid = OrdInvc.checkData(data, true);
                    if (!isValid) return false;
                    let result = OrdInvc.gnrtInvc(data);
                }
            },
            event: function() {
                // init select2
                $('#addDisc').select2({
                    dropdownParent: $('#mdlDiskon')
                });
                // event select
                $('#addDisc').on('change', function() {
                    let slc = $('#addDisc option:selected');
                    $('#disFieldWrapper').removeClass('d-none');
                    $('#discPercent').val('');
                    $('#discFlat').val('');
                    $('#groupDiscFlat').removeClass('d-none');
                    if (slc.val() == State.invc_amt_type.percent) {
                        $('#groupDiscPercent').removeClass('d-none');
                        $('#discFlat').attr('readonly', true);
                    } else if (slc.val() == State.invc_amt_type.flat) {
                        $('#groupDiscPercent').addClass('d-none');
                        $('#discFlat').removeAttr('readonly');
                    } else {
                        $('#groupDiscPercent').addClass('d-none');
                        $('#discFlat').attr('readonly', true);
                        $('#groupDiscFlat').addClass('d-none');
                    }
                });
                $('#addDisc').val($('#subTotal').data('disctype')).trigger('change');
                $('#discPercent').val($('#subTotal').data('discpercent'));
                $('#discFlat').val((new Intl.NumberFormat('id-ID')).format($('#subTotal').data('discflat')));
                // input
                $('#discFlat').on('keyup', function() {
                    let price = $('#discFlat').val().split('.').join('').replace(/[$,]+/g, ".");
                    if (Number(price) < 1) {
                        Helper.toast('Warning', 'just now', 'Besaran diskon wajib diisi');
                    }
                    $('#discFlat').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                $('#discPercent').on('keyup', function() {
                    let percent = $('#discPercent').val();
                    let subTotal = $('#subTotal').data('subtotal');
                    let total = $('#subTotal').data('total');
                    if (Number(percent) < 0) {
                        Helper.toast('Warning', 'just now', 'Diskon percent wajib diisi');
                        return true;
                    }
                    if (Number(percent) > 100) {
                        Helper.toast('Warning', 'just now', 'Diskon percent maksimal 100%');
                        return false;
                    }
                    let price = 0;
                    let taxType = $('#subTotal').data('taxtype');
                    if (taxType == State.tax_type.include) { // sudah termasuk pajak
                        price = total * percent / 100;
                    } else if (taxType == State.tax_type.exclude) { // belum termasuk pajak
                        price = subTotal * percent / 100;
                    } else {
                        price = subTotal * percent / 100;
                    }
                    $('#discFlat').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                // submit
                $('#btnSaveDisc').on('click', async function(e) {
                    e.preventDefault();
                    let data = OrdInvc.getData('save_disc');
                    let isValid = OrdInvc.checkData(data, true);
                    if (!isValid) return false;
                    let result = await OrdInvc.submitDataDisc(data);
                    if (result.type != 'success') return false;
                    Helper.toast('Success', 'just now', 'success update discount');
                    $('#mdlDiskon').modal('hide');
                    window.location.href = window.location.href;
                });
                $('#btnGnrtInvc').on('click', async function(e) {
                    e.preventDefault();
                    let data = OrdInvc.getData('gnrt_invc');
                    data.is_gnrt_invc = State.stts_gnrt_invc.yes;
                    let isValid = OrdInvc.checkData(data, true);
                    if (!isValid) return false;
                    let result = await OrdInvc.gnrtInvc(data);
                    if (result.type != 'success') return false;
                    window.open(State.route_download_invc + '?code=' + result.resp.code, '_blank').focus();
                    setTimeout(() => {
                        window.location.href = window.location.href;
                    }, 2000);
                });
            },
            getData: function(type = 'save_disc') {
                const data = {};

                data.ord_id = State.ord_id;
                data.ord_code = State.ord_code;
                data.termin_id = $('#subTotal').data('terminid');

                data.items = $('#subTotal').data('items');
                data.subtotal = Number($('#subTotal').data('subtotal'));

                data.tax_type = State.invc_amt_type.percent;
                data.tax_type_kind = Number($('#subTotal').data('taxtype'));
                data.ppn_percent = Number($('#subTotal').data('ppnpercent'));
                data.ppn_flat = Number($('#subTotal').data('ppnflat'));
                data.pph_percent = Number($('#subTotal').data('pphpercent'));
                data.pph_flat = Number($('#subTotal').data('pphflat'));
                data.tax_flat = Number($('#subTotal').data('taxflat'));
                data.total = Number($('#subTotal').data('total'));

                if (type === 'save_disc') {
                    let discType = $('#addDisc option:selected');
                    data.disc_type = discType.val();
                    if (data.disc_type == State.invc_amt_type.flat || data.disc_type == State.invc_amt_type.percent) {} else {
                        data.disc_type = 0;
                    }
                    data.disc_percent = Number($('#discPercent').val());
                    data.disc_flat = Number($('#discFlat').val().split('.').join('').replace(/[$,]+/g, "."));
                } else {
                    data.disc_type = Number($('#subTotal').data('disctype'));
                    data.disc_percent = Number($('#subTotal').data('discpercent'));
                    data.disc_flat = Number($('#subTotal').data('discflat'));
                }

                // sebelum ada ppn & pph
                // data.total = data.subtotal - data.disc_flat;
                // data.tax_flat = data.total * data.ppn_percent / 100;
                // data.total += data.tax_flat;

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.disc_type == State.invc_amt_type.percent) {
                    if (data.disc_percent < 0) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Diskon percent wajib diisi');
                        return false;
                    }
                    if (data.disc_percent > 100) {
                        if (isAlert) Helper.toast('Warning', 'just now', 'Diskon percent maksimal 100%');
                        return false;
                    }
                } else if (data.disc_type == State.invc_amt_type.flat) {
                    if (data.disc_flat < 1) {
                        Helper.toast('Warning', 'just now', 'Besaran diskon wajib diisi');
                    }
                }
                return true;
            },
            submitDataDisc: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSaveDisc').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSaveDisc').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_crt_updt_invc') }}",
                        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) => {
                            $('#btnSaveDisc').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: data,
                            });
                            window.location.href = window.location.href;
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSaveDisc').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'
                            });
                        }
                    })
                })
            },
            gnrtInvc: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnGnrtInvc').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnGnrtInvc').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_crt_updt_invc') }}",
                        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) => {
                            $('#btnGnrtInvc').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: data,
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnGnrtInvc').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 OrdTax = {
            activate: function() {
                OrdTax.event();
            },
            event: function() {
                // init select2
                $('#add-invc_tax_type').select2({
                    dropdownParent: $('#mdlTax')
                });
                // event select
                $('#add-invc_tax_type').on('change', function() {
                    const val = $('#add-invc_tax_type').val();
                    if (val == State.tax_type.include) {
                        $('.groupTaxTax').removeClass('d-none');
                        $('#add-invc_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        // $('#add-invc_tax_pph_percent').val(State.tax_type.pph_percent);
                        $('#add-invc_tax_pph_percent').val(0);
                    } else if (val == State.tax_type.exclude) {
                        $('.groupTaxTax').removeClass('d-none');
                        $('#add-invc_tax_ppn_percent').val(State.tax_type.ppn_percent);
                        // $('#add-invc_tax_pph_percent').val(State.tax_type.pph_percent);
                        $('#add-invc_tax_pph_percent').val(0);
                    } else { // without
                        $('.groupTaxTax').addClass('d-none');
                        $('#add-invc_tax_ppn_percent').val('');
                        $('#add-invc_tax_pph_percent').val('');
                    }
                });
                $('#add-invc_tax_type').trigger('change');
                // submit
                $('#btnSaveTax').on('click', async function(e) {
                    e.preventDefault();
                    let data = OrdTax.getData();
                    let isValid = OrdTax.checkData(data, true);
                    if (!isValid) return false;
                    let result = await OrdTax.submitDataTax(data);
                    if (result.type != 'success') return false;
                    Helper.toast('Success', 'just now', 'success save tax');
                    $('#mdlTax').modal('hide');
                    window.location.href = window.location.href;
                });

                // init data
                $('#add-invc_tax_type').val($('#subTotal').data('taxtype')).trigger('change');
            },
            getData: function() {
                const data = {};

                data.ord_id = State.ord_id;
                data.ord_code = State.ord_code;
                data.termin_id = $('#subTotal').data('terminid');

                data.items = $('#subTotal').data('items');
                data.subtotal = Number($('#subTotal').data('subtotal'));

                data.invc_tax_type = $('#add-invc_tax_type').val();
                data.invc_tax_ppn_percent = $('#add-invc_tax_ppn_percent').val() || 0;
                data.invc_tax_pph_percent = $('#add-invc_tax_pph_percent').val() || 0;

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.invc_tax_type == State.tax_type.without) {} else if (data.invc_tax_type == State.tax_type.include) {} else if (data.invc_tax_type == State.tax_type.exclude) {} else {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Perpajakan tidak valid');
                    return false;
                }

                // if (data.invc_tax_ppn_percent < 1) {
                //     if (isAlert) Helper.toast('Warning', 'just now', 'PPN Percent tidak boleh kurang dari 1%');
                //     return false;
                // }
                // if (data.invc_tax_pph_percent < 1) {
                //     if (isAlert) Helper.toast('Warning', 'just now', 'PPH Percent tidak boleh kurang dari 1%');
                //     return false;
                // }
                return true;
            },
            submitDataTax: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSaveTax').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSaveTax').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_crt_updt_tax') }}",
                        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) => {
                            $('#btnSaveTax').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: data,
                            });
                            window.location.href = window.location.href;
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSaveTax').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 OrdPayInvc = {
            activate: function() {
                OrdPayInvc.event();
            },
            event: function() {
                $('#confirmInvc').on('click', function() {
                    // OrdInvc.updtInvc();
                });
                $('#isCheckConfirmInvc').on('change', function() {
                    if ($('#isCheckConfirmInvc').prop('checked')) {
                        $('#btnConfirmInvc').removeAttr('disabled');
                    } else {
                        $('#btnConfirmInvc').attr('disabled', true);
                    }
                })
                // input
                $('#amt_bill_confirm').on('keyup', function() {
                    let price = $('#amt_bill_confirm').val().split('.').join('').replace(/[$,]+/g, ".");
                    $('#amt_bill_confirm').val((new Intl.NumberFormat('id-ID')).format(price));
                });
                // submit
                $('#btnConfirmInvc').on('click', async function(e) {
                    e.preventDefault();
                    let data = OrdPayInvc.getData();
                    OrdPayInvc.submitConfirm(data);
                });
            },
            getData: function() {
                let data = {};

                data.invc_id = $('#confirmInvc').data('id');
                data.invc_code = $('#confirmInvc').data('code');
                data.amt_invoicing = Number($('#subTotal').data('total'));
                data.amt_bill_confirm = Number($('#amt_bill_confirm').val().split('.').join('').replace(/[$,]+/g, "."));
                data.amt_bill_confirm_note = $('#amt_bill_confirm_note').val();

                return data;
            },
            submitConfirm: async function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnConfirmInvc').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnConfirmInvc').attr('disabed', true);
                    $.ajax({
                        url: "{{ route('api_finance_confirm_invc') }}",
                        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) => {
                            $('#btnConfirmInvc').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: data,
                            });
                            Helper.toast('Success', 'just now', 'success konfirmasi pembayaran invoice');
                            $('#mdlConfirmInvc').modal('hide');
                            window.location.href = window.location.href;
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnConfirmInvc').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 OrdDelItem = {
            activate: function() {
                OrdDelItem.event();
            },
            event: function() {
                $(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');
                });
                $('#btnSubmitDelItem').on('click', function(e) {
                    e.preventDefault();
                    let data = {};
                    data.is_del = 3;
                    data.ord_a_item_id = $('#mdlDelItem').data('ord_a_item_id');
                    OrdDelItem.submitDelData(data);
                });
            },
            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');
                            window.location.href = window.location.href;
                            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'
                            });
                        }
                    })
                })
            },
        }

        const ChangePICInvoice = {
            activate: function() {
                $('#btnChangePICInvoice').on('click', function() {
                    $('#mdlChangePICInvoice').modal('show');
                });

                $('#btnSubmitChangePICInvoice').on('click', function() {
                    const data = ChangePICInvoice.getData();
                    let isValid = ChangePICInvoice.checkData(data, true);
                    if (!isValid) return false;
                    ChangePICInvoice.submitData(data);
                });
            },
            getData: function() {
                const data = {
                    ord_id: State.ord.ord_id,
                    ord_client_id: State.ord.ord_client_id,
                    c_pt_name: $('#c_pt_name').val(),
                    c_pt_addr: $('#c_pt_addr').val(),
                    c_pt_pic_name: $('#c_pt_pic_name').val(),
                    c_pt_pic_phone_val: $('#c_pt_pic_phone_val').val(),
                };

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (data.c_pt_name == null || typeof data.c_pt_name == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Nama perusahaan wajib diisi');
                    return false;
                }
                if (data.c_pt_addr == null || typeof data.c_pt_addr == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Alamat perusahaan wajib diisi');
                    return false;
                }
                if (data.c_pt_pic_name == null || typeof data.c_pt_pic_name == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'PIC perusahaan wajib diisi');
                    return false;
                }
                if (data.c_pt_pic_phone_val == null || typeof data.c_pt_pic_phone_val == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Nomor telepon PIC perusahaan wajib diisi');
                    return false;
                }

                return true;
            },
            submitData: function(data) {
                return new Promise((resolve, reject) => {
                    if (typeof $('#btnSubmitChangePICInvoice').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnSubmitChangePICInvoice').attr('disabed', true);
                    $('#btnSubmitChangePICInvoiceSpinner').removeClass('d-none');
                    $('#btnSubmitChangePICInvoice').addClass('d-none');
                    $.ajax({
                        url: "{{ route('api_change_pic_invoice') }}",
                        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) => {
                            $('#btnSubmitChangePICInvoiceSpinner').addClass('d-none');
                            $('#btnSubmitChangePICInvoice').removeClass('d-none');
                            $('#btnSubmitChangePICInvoice').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success',
                                resp: data,
                            });
                            Helper.toast('Success', 'just now', 'sukses ganti pic invoice');
                            $('#mdlChangePICInvoice').modal('hide');
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnSubmitChangePICInvoiceSpinner').addClass('d-none');
                            $('#btnSubmitChangePICInvoice').removeClass('d-none');
                            $('#btnSubmitChangePICInvoice').removeAttr('disabed');
                            if (jqXHR.status >= 500) {
                                Helper.toast('Error', 'just now', 'please try again');
                            } else {
                                Helper.toast('Error', 'just now', jqXHR.responseJSON.meta
                                    .message);
                            }
                            resolve({
                                type: 'error'
                            });
                        }
                    })
                });
            },
        }

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