@extends('app.app')
@section('title')
    Finance - Payment
@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 pb-0">
                            <div class="row d-flex">
                                <div class="col-5 mb-3">
                                    <div class="row">
                                        <div class="col-sm-12 mb-3">
                                            <p class="text-danger text-bold mb-0">Penjemputan dan Pengantaran</p>
                                        </div>
                                        <div class="col-sm-12 mb-3">
                                            <label for="" class="form-label">Tanggal Penjemputan</label>
                                            <div class="card bg-light border mb-0">
                                                <div class="card-body">
                                                    <p class="mb-0"><span id="view-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>
                            <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>
                </div>
                <div class="col-sm-6">
                    {{-- invoicing termin 1 --}}
                    @php
                    $current_group_termin_id = 0;
                    $prev_group_termin_id = 0;
                    @endphp
                    @foreach ($group_termins as $yi => $y)
                        @if ($y->c_group_termin_id !== $current_group_termin_id)
                        @php
                        $prev_group_termin_id = $current_group_termin_id;
                        $prev_group_termin_is_paid = $y->termin_is_paid;
                        $result_is_enable_btn = App\Helper::viewBillFncIsEnableBtn($y->termin_ddln_type, $y->drop_chk_at, $prev_group_termin_id, $prev_group_termin_is_paid);
                        $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->termin_sequence }}</p>
                                    </div>
                                    @if ($result_is_enable_btn === 0)
                                    <div class="col-auto text-end ps-0">
                                        <small class="text-danger">Menunggu Pengantaran Selesai</small>
                                    </div>
                                    @elseif ($result_is_enable_btn === 1)
                                    <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 === 2)
                                        <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>
                                        <div class="col-auto text-end ps-0">
                                            <small class="text-success">Pengantaran Selesai pada {{ date('Y-m-d H:i', $y->drop_chk_a) }}</small>
                                        </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="">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>
                        @endif
                                            @foreach ($ord_a_items as $xi => $x)
                                            @if ($x->c_group_termin_id === $y->c_group_termin_id)
                                            <tr class="">
                                                <td class="small">1</td>
                                                <td class="small">
                                                    {!! $x->desc !!}
                                                </td>
                                                <td class="small text-nowrap text-end">{{ $x->unit_qty }}</td>
                                                <td class="small">{{ \App\Models\OrdersAItems::getUnitTypeText($x->unit_type) }}</td>
                                                <td class="small text-nowrap text-end">{{ number_format($x->amt_base_flat, 0, ',', '.') }}</td>
                                                <td class="small text-nowrap text-end">{{ number_format($x->amt_total_flat, 0, ',', '.') }}</td>
                                                @php
                                                $sub_total += $x->amt_total_flat;
                                                $invc_items .= "$x->ord_a_item_id,";
                                                @endphp
                                            </tr>
                                            @endif
                                            @endforeach
                        @if ($y->c_group_termin_id !== $current_group_termin_id)
                        @php
                        $current_group_termin_id = $y->c_group_termin_id;
                        @endphp
                                        </tbody>
                                        <tfooter>
                                            @php
                                            $tax = $sub_total * \App\Models\OrdersInvoices::DFT_TAX_PERCENT / 100;
                                            @endphp
                                            <tr class=" border-0">
                                                <td class="text-nowrap text-end border-0" colspan="5">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="{{ $sub_total }}"
                                                        data-terminid="{{ $current_group_termin_id }}"
                                                        data-taxpercent="{{ \App\Models\OrdersInvoices::DFT_TAX_PERCENT }}"
                                                        data-taxflat="{{ $tax }}"
                                                        data-discount="{{ (round($x->invc_disc_flat) ?? 0) }}"
                                                        data-total="{{ number_format($sub_total + $tax - (round($x->invc_disc_flat) ?? 0), 0, ',', '.') }}">
                                                        {{ number_format($sub_total, 0, ',', '.') }}</td>
                                                @else
                                                    <td class="text-nowrap text-end border-0"
                                                        data-items="{{ $invc_items }}"
                                                        data-subtotal="{{ $sub_total }}"
                                                        data-terminid="{{ $current_group_termin_id }}"
                                                        data-taxpercent="{{ \App\Models\OrdersInvoices::DFT_TAX_PERCENT }}"
                                                        data-taxflat="{{ $tax }}"
                                                        data-discount="{{ (round($x->invc_disc_flat) ?? 0) }}"
                                                        data-total="{{ number_format($sub_total + $tax - (round($x->invc_disc_flat) ?? 0), 0, ',', '.') }}">
                                                        {{ number_format($sub_total, 0, ',', '.') }}</td>
                                                @endif
                                            </tr>
                                            <tr class=" border-0">
                                                <td class="text-nowrap text-end border-0" colspan="5">
                                                    @if ($x->invc_disc_type === \App\Models\OrdersInvoices::AMT_TYPE_PERCENT)
                                                        Diskon ({{ $x->c_group_termin_id }}%)
                                                    @else
                                                        Diskon
                                                    @endif
                                                </td>
                                                <td class="text-nowrap text-end border-0">-{{ number_format(round($x->invc_disc_flat) ?? 0, 0, ',', '.') }}</td>
                                            </tr>
                                            <tr class="border-bottom">
                                                <td class="text-nowrap text-end boder-bottom" style="border-bottom: 1px solid" colspan="5">PPN ({{ \App\Models\OrdersInvoices::DFT_TAX_PERCENT }}%)</td>
                                                <td class="text-nowrap text-end boder-bottom" style="border-bottom: 1px solid">{{ number_format($tax, 0, ',', '.') }}</td>
                                            </tr>
                                        </tfooter>
                                        <tfooter>
                                            <tr class="bg-light">
                                                <td class="text-nowrap text-end border-0 text-bold" colspan="5">TOTAL</td>
                                                <td class="text-nowrap text-end border-0 text-bold">{{ number_format($sub_total + $tax - (round($x->invc_disc_flat) ?? 0), 0, ',', '.') }}</td>
                                            </tr>
                                        </tfooter>
                                    </table>
                                </div>
                            </div>
                            @if ($result_is_enable_btn === 0)
                            @elseif ($result_is_enable_btn === 1)
                                <div class="card-footer">
                                    <div class="row d-flex align-items-center">
                                        <div class="col-8">
                                            <p class="mb-0">
                                                Apakah item diatas sudah seluruhnya di masukkan?
                                            </p>
                                        </div>
                                        <div class="col-4 text-end">
                                            <a href="{{ asset('pdf/invoice.pdf') }}" target="_blank" class="btn btn-primary btn-block btn-sm" id="btnCalculate">Generate Invoice</a>
                                        </div>
                                    </div>
                                </div>
                            @elseif ($result_is_enable_btn === 2)
                                <div class="card-footer">
                                    <div class="row d-flex align-items-center">
                                        <div class="col-8">
                                            <p class="mb-0">
                                                Apakah item diatas sudah seluruhnya di masukkan?
                                            </p>
                                        </div>
                                        <div class="col-4 text-end">
                                            <a href="{{ asset('pdf/invoice.pdf') }}" target="_blank" class="btn btn-primary btn-block btn-sm" id="btnCalculate">Generate Invoice</a>
                                        </div>
                                    </div>
                                </div>
                            @elseif ($result_is_enable_btn === 3)
                            @endif
                        </div>
                        @endif
                    @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="none" 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">Tutup</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSaveDisc">Simpan</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>
                            <label for="add-item_price" class="form-label">Harga Satuan <span class="text-danger">*</span></label>
                            <input type="text" name="add-item_price" id="add-item_price" class="form-control">
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" name="add-item_isAdmPrice" type="checkbox" value="yes" id="add-item_isAdmPrice">
                                <label class="form-check-label text-danger" for="add-item_isAdmPrice">
                                    Biaya admin bank ?
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="add-item_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">Tutup</button>
                    <button type="button" class="btn btn-sm btn-primary" id="btnSubmitAddItem">Simpan</button>
                </div>
            </div>
        </div>
    </div>
    {{-- ./Modal --}}
@endsection

@section('customcss')
@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 }}",
            },
            storage_lara: "{{ asset('storage') }}/",
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
        };

        const Wrapper = {
            activate: function() {
                Wrapper.event();
                OrdView.activate();
                OrdAItem.activate();
                OrdInvc.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');
                });
            },
        };

        const OrdView = {
            activate: function() {
                OrdView.event();
            },
            event: function() { },
        };

        const OrdAItem = {
            activate: function() {
                OrdAItem.event();
            },
            event: function() {
                // init select2
                $('#slcItem').select2({
                    dropdownParent: $('#mdlAddItem'),
                });
                $('#add-item_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);
                });
            },
            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,".");
                    if($('#add-item_isAdmPrice').prop('checked')) {
                        data.is_adm_price = State.is_adm_price.yes
                    } else {
                        data.is_adm_price = State.is_adm_price.no
                    }
                } else if  (slcType.val() === '') {
                } else {
                    data.a_id = slcType.val(); // id
                    data.a_name = slcType.data('name');
                    data.a_type = slcType.data('type');
                    data.a_price = slcType.data('price');
                    data.is_adm_price = slcType.data('is_adm_price');
                }
                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.yes;
                data.crt_type = State.crt_type.finance;

                return data;
            },
            checkData: function(data, isAlert = false) {
                if (typeof data.a_id == 'undefined') {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item wajib diisi');
                    return false;
                }
                if (data.a_name == '' || data.a_name == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item nama wajib diisi');
                    return false;
                }
                if (data.a_type == '' || data.a_type == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item satuan wajib diisi');
                    return false;
                }
                if (data.a_price == '' || data.a_price == null) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Item harga wajib diisi');
                    return false;
                }
                if (typeof data.a_qty == 'undefined' || Number(data.a_qty) < 1) {
                    if (isAlert) Helper.toast('Warning', 'just now', 'Jumlah wajib diisi');
                    return false;
                }
                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();
            },
            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');
                    }
                });
                // 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');
                    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 = 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();
                    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;
                });
            },
            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.tax_type = State.invc_amt_type.percent;
                data.tax_percent = Number($('#subTotal').data('taxpercent'));
                data.tax_flat = Number($('#subTotal').data('taxflat'));

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

                data.total = data.subtotal + data.tax_flat - data.disc_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'
                            });
                        },
                        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 $('#btnCalculate').attr('disabed') != 'undefined') {
                        resolve({
                            type: 'fail'
                        });
                        return false;
                    }
                    $('#btnCalculate').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) => {
                            $('#btnCalculate').removeAttr('disabed');
                            if (data.meta.type != 'success') {
                                resolve({
                                    type: 'fail'
                                });
                                Helper.toast('Warning', 'just now', data.meta.message);
                                return false;
                            }
                            resolve({
                                type: 'success'
                            });
                        },
                        error: (jqXHR, textStatus, error) => {
                            $('#btnCalculate').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
