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

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="row">
                <div class="col-12">
                    <label for="" class="form-label">Periode</label>
                </div>
                <div class="col-sm-12 col-md-6 col-lg-4">
                    <div class="mb-3 d-flex align-items-center">
                        <input class="form-control" type="date" id="filter-startDate">
                        <div class="mx-3">-</div>
                        <input class="form-control" type="date" id="filter-endDate">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12 col-md-4 col-lg-3">
                    <div class="card">
                        <div class="card-body">
                            <h6 class="mb-3">Total</h6>
                            <h4 class="text-end mb-0">Rp<span id="totAllPayment">2.500.000</span></h4>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 col-md-4 col-lg-3">
                    <div class="card">
                        <div class="card-body">
                            <h6 class="mb-3">Uang Keluar</h6>
                            <h4 class="text-end mb-0">Rp<span id="totAllPaymentPayed">2.500.000</span></h4>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 col-md-4 col-lg-3">
                    <div class="card">
                        <div class="card-body">
                            <h6 class="mb-3">Belum Bayar</h6>
                            <h4 class="text-end mb-0">Rp<span id="totAllPaymentRemaining">2.500.000</span></h4>
                        </div>
                    </div>
                </div>

            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header">
                            <div class="row d-flex align-items-center">
                                <div class="col">
                                    <p class="card-title text-bold mb-0">Pembayaran</p>
                                    <p class="card-subtitle text-muted">Daftar Pembayaran</p>
                                </div>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="tPayments" class="table table-hover dataTable w-100">
                                    <thead>
                                        <tr class="">
                                            <th class="">#</th>
                                            <th class=""></th>
                                            <th class="text-nowrap">Kode Transaksi</th>
                                            <th class="text-nowrap">Nama Vendor</th>
                                            <th class="w-25">item</th>
                                            <th class="text-center">Total (Rp)</th>
                                            <th class="text-center">Dibayar (Rp)</th>
                                            <th class="text-center">Sisa (Rp)</th>
                                            <th class="text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr class="">
                                            <td class="">1</td>
                                            <td class="">
                                                <a href="{{ route('view_keuangan_payment_view') }}" class="">
                                                    <span class="icon ion-eye text-danger fz-16"></span>
                                                </a>
                                            </td>
                                            <td class="text-nowrap">#89901280921890</td>
                                            <td class="text-nowrap">Jangan Lupa Bahagia (JLB)</td>
                                            <td class="text-nowrap">
                                                <p class="mb-0">Pengantaran Logistik</p>
                                                <p class="mb-0">Jakarta - yogyakarta</p>
                                                <p class="mb-0">22 Apr 2022</p>
                                            </td>
                                            <td class="text-end">2.500.000</td>
                                            <td class="text-end text-success">
                                                <p class="mb-0">500 .000</p>
                                            </td>
                                            <td class="text-end text-danger">0</td>
                                            <td class="text-center"><span class="text-success">sLunas</span></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('customcss')
@endsection

@section('customjs')
    <script>
        // $('.dataTable').DataTable({
        //     "columnDefs": [ {
        //         "targets": 1,
        //         "orderable": false
        //     } ]
        // });
    </script>
    <script>
        'use strict';
        const State = {
            file_jimp_worker: "{{ asset('assets/js/worker/jimp.js') }}",
            storage_lara: "{{ asset('storage') }}/",
            periodeStartDate: '', // unix timestamps
            periodeEndDate: '', // unix timestamps
            stts_order: {
                wait: "{{ App\Models\Orders::STTS_WAIT }}",
                confirm: "{{ App\Models\Orders::STTS_CONFIRM }}",
                have_get_vhc: "{{ App\Models\Orders::STTS_HAVE_GET_VHC }}",
                pck: "{{ App\Models\Orders::STTS_PCK }}",
                go: "{{ App\Models\Orders::STTS_GO }}",
                arv: "{{ App\Models\Orders::STTS_ARV }}",
                drop: "{{ App\Models\Orders::STTS_DROP }}",
                client_pay: "{{ App\Models\Orders::STTS_CLIENT_PAY }}",
                vendor_payed: "{{ App\Models\Orders::STTS_VENDOR_PAYED }}",
                close: "{{ App\Models\Orders::STTS_CLOSE }}",
                cancel: "{{ App\Models\Orders::STTS_CANCEL }}",
            },
            is_paid: {
                yes: "{{ App\Models\Orders::IS_PAID_YES }}",
                no: "{{ App\Models\Orders::IS_PAID_NO }}",
            },
            url_view_detail: "{{ route('view_keuangan_payment_view') }}",
            delay_typing_front: 1000,
        };

        const Wrapper = {
            activate: function() {
                Filter.activate();
                Wrapper.event();
                DTable.activate();
            },
            event: function() {},
            getHtmlSttsOrd: function(stts, row) {
                if (row.total_payment === row.total_payed) {
                    return '<span class="text-success">Lunas</span>';
                } else if (State.is_paid.yes == row.is_vdr_paid) {
                    if (row.total_payment !== row.total_payed) {
                        return '<span class="text-danger">Belum lunas</span>';
                    }
                    return '<span class="text-success">Lunas</span>';
                } else if (State.stts_order.drop == stts) {
                    // return '<span class="text-dark">Selesai Melakukan Pengantaran</span>';
                    return '<span class="text-danger">Belum lunas</span>';
                } else if (State.stts_order.client_pay == stts) {
                    // return '<span class="text-danger">Invoicing to Client</span>';
                    return '<span class="text-danger">Belum lunas</span>';
                } else if (State.stts_order.vendor_payed == stts) {
                    // return '<span class="text-success">Payment to Vendor</span>';
                    return '<span class="text-danger">Belum lunas</span>';
                } else if (State.stts_order.close == stts) {
                    return '<span class="text-success">Lunas</span>';
                } else if (State.stts_order.cancel == stts) {
                    return '<span class="text-danger">Dibatalkan</span>';
                } else {
                    // return '<span class="text-dark">-</span>';
                    return '<span class="text-danger">Belum lunas</span>';
                }
            },
        };

        const Filter = {
            activate: function() {
                const startDate = moment().startOf('month');
                const endDate = moment().endOf('month');
                $('#filter-startDate').val(startDate.format('YYYY-MM-DD')).trigger('change');
                $('#filter-endDate').val(endDate.format('YYYY-MM-DD')).trigger('change');
                State.periodeStartDate = startDate.unix();
                State.periodeEndDate = endDate.unix();
                Filter.evPeriodeDate();
            },
            evPeriodeDate: function() {
                $('#filter-startDate').on('change', function(e) {
                    const {
                        isValid,
                        data
                    } = Filter.calcPeriodeDate(moment($('#filter-startDate').val()), moment($('#filter-endDate').val()))
                    if (!isValid) return false;
                    State.periodeStartDate = data.startDate.unix();
                    State.periodeEndDate = data.endDate.unix();
                    DTable.reload();
                });
                $('#filter-endDate').on('change', function(e) {
                    const {
                        isValid,
                        data
                    } = Filter.calcPeriodeDate(moment($('#filter-startDate').val()), moment($('#filter-endDate').val()))
                    if (!isValid) return false;
                    State.periodeStartDate = data.startDate.unix();
                    State.periodeEndDate = data.endDate.unix();
                    DTable.reload();
                });
            },
            calcPeriodeDate: function(startDate, endDate) {
                if (startDate.format('YYYY-MM-DD') === 'Invalid date') {
                    Helper.toast('Warning', 'just now', 'Tanggal mulai periode tidak valid');
                    return {
                        isValid: false
                    };
                }
                if (endDate.format('YYYY-MM-DD') === 'Invalid date') {
                    Helper.toast('Warning', 'just now', 'End date of the period is not valid');
                    return {
                        isValid: false
                    };
                }
                const duration = moment.duration(endDate.diff(startDate));
                const diffDays = duration.days();
                if (diffDays > 30) {
                    Helper.toast('Warning', 'just now', 'Maksimal periode 1 bulan');
                    return {
                        isValid: false
                    };
                }
                if (diffDays < 0) {
                    Helper.toast('Warning', 'just now', 'Rentang periode tidak valid');
                    return {
                        isValid: false
                    };
                }
                return {
                    isValid: true,
                    data: {
                        startDate,
                        endDate
                    }
                };
            },
        }

        const DTable = {
            activate: function() {
                DTable.reload();
            },
            reload: function() {
                // $('#tPayments').DataTable();
                // if (Driver.Table.firstInitDataTable == 1) { loadTableSkeletonLoading() } else { Driver.Table.firstInitDataTable = 1; }
                DTable.setSummary({
                    total_payment: 0,
                    total_payed: 0,
                    total_remaining: 0,
                });
                $('#tPayments').DataTable({
                    processing: true,
                    serverSide: false,
                    bLengthChange: true,
                    deferRender: true,
                    destroy: true,
                    ajax: {
                        url: "{{ route('api_finance_list_payments') }}?start_date=" + State.periodeStartDate + "&end_date=" + State.periodeEndDate,
                        type: 'GET',
                        complete: function(jqXHR, textStatus, c) {
                            const {
                                total_payment,
                                total_payed,
                                total_remaining,
                            } = jqXHR.responseJSON.summary;
                            DTable.setSummary({
                                total_payment,
                                total_payed,
                                total_remaining,
                            });
                            // removeTableSkeletonLoading()
                        },
                    },
                    deferRender: true,
                    columns: [{
                            data: 'DT_RowIndex',
                            className: 'text-end',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'action',
                            className: 'text-center',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let ord_codes = row.ord_code;
                                if (typeof row.childs != 'undefined' && row.childs.length > 0) {
                                    for (const child of row.childs) {
                                        ord_codes += ',' + child.ord_code;
                                    }
                                }
                                let action = `
                                    <a href="${State.url_view_detail}?code=${ord_codes}" class="">
                                        <span class="icon ion-eye text-danger fz-16"></span>
                                    </a>
                                    `;
                                return action;
                            }
                        },
                        {
                            data: 'ord_code',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            createdCell: function(td, cellData, rowData, row, col) {
                                $(td).attr('data-ord_id', rowData.ord_id);
                                $(td).attr('data-ord_code', rowData.ord_code);
                            },
                            render: function(data, type, row, meta) {
                                let txt = '#' + data;
                                for (const child of row.childs) {
                                    txt += '<br>#' + child.ord_code;
                                }
                                return txt;
                            },
                        },
                        {
                            data: 'vdr_name',
                            className: 'text-start text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                        },
                        {
                            data: 'main_item',
                            className: 'text-start',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let txt = data;
                                for (const child of row.childs) {
                                    txt += '<br><br>' + child.main_item;
                                }
                                return txt;
                            },
                        },
                        {
                            data: 'total_payment',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let txt = data;
                                for (const child of row.childs) {
                                    txt += child.total_payment;
                                }
                                return (new Intl.NumberFormat('id-ID')).format(txt);
                            },
                        },
                        {
                            data: 'total_payed',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let txt = data;
                                for (const child of row.childs) {
                                    txt += child.total_payed;
                                }
                                return '<span class="text-success">' + (new Intl.NumberFormat('id-ID')).format(txt) + '</span>';
                            },
                        },
                        {
                            data: 'total_remaining',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let txt = data;
                                for (const child of row.childs) {
                                    txt += child.total_remaining;
                                }
                                return '<span class="text-danger">' + (new Intl.NumberFormat('id-ID')).format(txt) + '</span>';
                            },
                        },
                        {
                            data: 'ord_status',
                            className: 'text-end text-nowrap',
                            visible: true,
                            orderable: true,
                            searchable: true,
                            render: function(data, type, row, meta) {
                                let txt = Wrapper.getHtmlSttsOrd(data, row);
                                if (txt.indexOf('>Belum') > -1) {
                                    return txt;
                                }
                                for (const child of row.childs) {
                                    txt = Wrapper.getHtmlSttsOrd(child.ord_status, child);
                                    if (txt.indexOf('>Belum') > -1) {
                                        return txt;
                                    }
                                }
                                return txt;
                            },
                        },
                    ],
                });
            },
            setSummary: function({
                total_payment,
                total_payed,
                total_remaining,
            }) {
                $('#totAllPayment').text((new Intl.NumberFormat('id-ID')).format(total_payment));
                $('#totAllPaymentPayed').text((new Intl.NumberFormat('id-ID')).format(total_payed));
                $('#totAllPaymentRemaining').text((new Intl.NumberFormat('id-ID')).format(total_remaining));
            },
        };

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