@extends('layouts.app')

@section('content')
<div class="col-12 container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">

                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb pb-3">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Bajet</li>
                    </ol>
                </nav>

                <div class="card-body text-center">


                    <div class="d-flex">

                        <div id="divpembharian" class="card bg-light mb-3 col-4 mr-1">
                            <div class="card-header font-weight-bold">Pembiayaan</div>
                            <div class="card-body">
                                <div class="progress mb-2">
                                    <div id="pembprogress"
                                        class="progress-bar progress-bar-striped progress-bar-animated"
                                        role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0"
                                        aria-valuemax="100">0%</div>
                                </div>

                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">HARIAN</span>
                                        <span class="col-1">:</span>
                                        <span id="pembharian" class="col-6 text-left"></span>
                                    </div>
                                    <div>
                                        <span id="pembpercent">-100%</span>
                                    </div>

                                </div>
                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">BAJET</span>
                                        <span class="col-1">:</span>
                                        <span id="pembbajet" class="col-6 text-left"></span>
                                    </div>
                                    <span>varians</span>
                                </div>
                            </div>
                        </div>

                        <div class="card bg-light mb-3 col-4 mr-1">
                            <div class="card-header font-weight-bold">Penyelesaian Pembiayaan</div>
                            <div class="card-body">
                                <div class="progress mb-2">
                                    <div id="penbprogress"
                                        class="progress-bar progress-bar-striped progress-bar-animated"
                                        role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0"
                                        aria-valuemax="100">0%</div>
                                </div>

                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">HARIAN</span>
                                        <span class="col-1">:</span>
                                        <span id="penbharian" class="col-6 text-left"></span>
                                    </div>
                                    <div>
                                        <span id="penbpercent">0%</span>
                                    </div>

                                </div>
                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">BAJET</span>
                                        <span class="col-1">:</span>
                                        <span id="penbbajet" class="col-6 text-left"></span>
                                    </div>
                                    <span>varians</span>
                                </div>
                            </div>
                        </div>

                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">Keuntungan</div>
                            <div class="card-body">
                                <div class="progress mb-2">
                                    <div id="keunprogress"
                                        class="progress-bar progress-bar-striped progress-bar-animated"
                                        role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0"
                                        aria-valuemax="100">0%</div>
                                </div>

                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">HARIAN</span>
                                        <span class="col-1">:</span>
                                        <span id="keunharian" class="col-6 text-left"></span>
                                    </div>
                                    <div>
                                        <span id="keunpercent">0%</span>
                                    </div>

                                </div>
                                <div class="d-flex justify-content-between col-12">
                                    <div class="row col-9">
                                        <span class="col-4 font-weight-bold ml-n4 text-left">BAJET</span>
                                        <span class="col-1">:</span>
                                        <span id="keunbajet" class="col-6 text-left"></span>
                                    </div>
                                    <span>varians</span>
                                </div>
                            </div>
                        </div>
                    </div>


                    <div class="mt-3">
                        <div class="d-flex justify-content-center">
                            <div class="card bg-light mb-3 col-4 mr-1">
                                <span class="font-weight-bold mt-2 mb-2">Pembiayaan Bulanan</span>
                                <div class="card-body">
                                    <div id="chartpembiayaan">
                                    </div>
                                </div>
                            </div>

                            <div class="card bg-light mb-3 col-4 mr-1">
                                <span class="font-weight-bold mt-2 mb-2">Penyelesaian Pembiayaan Bulanan</span>
                                <div class="card-body">
                                    <div id="chartpenebusan">
                                    </div>
                                </div>
                            </div>

                            <div class="card bg-light mb-3 col-4">
                                <span class="font-weight-bold mt-2 mb-2">Keuntungan Bulanan</span>
                                <div class="card-body">
                                    <div id="chartkeuntungan">
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>

                    <div class="mt-3 row">

                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">Pembiayaan Terkumpul</div>
                            <div class="card-body">
                                <div class="row justify-content-center">
                                    <div class="card text-white bg-info mb-3 col-5 mr-2 pt-4 pb-4">
                                        ACTUAL : <span id="pembactualtahunan"></span>
                                    </div>

                                    <div class="card text-white bg-info mb-3 col-5 p-4">
                                        BAJET : <span id="pembbajettahunan"></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">Penyelesaian Pembiayaan Terkumpul</div>
                            <div class="card-body">

                                <div class="row justify-content-center">
                                    <div class="card text-white bg-info mb-3 col-5 mr-2 p-4">
                                        ACTUAL : <span id="penbactualtahunan"></span>
                                    </div>

                                    <div class="card text-white bg-info mb-3 col-5 p-4">
                                        BAJET : <span id="penbbajettahunan"></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">Keuntungan Terkumpul</div>
                            <div class="card-body">

                                <div class="row justify-content-center">
                                    <div class="card text-white bg-info mb-3 col-5 mr-2 p-4">
                                        ACTUAL : <span id="keunactualtahunan"></span>
                                    </div>

                                    <div class="card text-white bg-info mb-3 col-5 p-4">
                                        BAJET : <span id="keunbajettahunan"></span>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </div>

                    <div class="mt-3 row">
                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">Outstanding</div>
                            <div class="card-body">
                                <table class="table">
                                    <thead class="thead-dark">
                                        <tr>
                                            <th scope="col">Tempoh</th>
                                            <th scope="col">Bil</th>
                                            <th scope="col">RM</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @for($i=0;$i<13;$i++)
                                        <tr>
                                            <td>{{ ($i == 12) ? '12 >' : ($i + 1)  }} bulan</td>
                                            <td>{{ number_format($data_sebenar['count'][$i]) }}</td>
                                            <td>{{ number_format($data_sebenar['sum'][$i],2) }}</td>
                                        </tr>
                                        @endfor
                                    </tbody>
                                    <tfoot class="thead-light">
                                        <tr>
                                            <th scope="col">Keseluruhan</th>
                                            <th scope="col">{{ number_format($data_sebenar['count'][13]) }}</th>
                                            <th scope="col">{{ number_format($data_sebenar['sum'][13],2) }}</th>
                                        </tr>
                                    </tfoot>
                                </table>

                            </div>
                        </div>
                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">6 Bulan <i class="fas fa-times-circle text-danger"></i></div>
                            <div class="card-body">
                                <table class="table">
                                    <table class="table">
                                        <thead class="thead-dark">
                                            <tr>
                                                <th scope="col">Tempoh</th>
                                                <th scope="col">Bil</th>
                                                <th scope="col">RM</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @for($i=0;$i<13;$i++)
                                            <tr>
                                                <td>{{ ($i == 12) ? '12 >' : ($i + 1)  }} bulan</td>
                                                <td>{{ number_format($data_lelong['count'][$i]) }}</td>
                                                <td>{{ number_format($data_lelong['sum'][$i],2) }}</td>
                                            </tr>
                                            @endfor
                                        </tbody>
                                        <tfoot class="thead-light">
                                            <tr>
                                                <th scope="col">Keseluruhan</th>
                                                <th scope="col">{{ number_format($data_lelong['count'][13]) }}</th>
                                                <th scope="col">{{ number_format($data_lelong['sum'][13],2) }}</th>
                                            </tr>
                                        </tfoot>
                                    </table>

                            </div>
                        </div>
                        <div class="card bg-light mb-3 col-4">
                            <div class="card-header font-weight-bold">6 Bulan <i class="fas fa-check-square text-success"></i></div>
                            <div class="card-body">
                                <table class="table">
                                    <thead class="thead-dark">
                                        <tr>
                                            <th scope="col">Tempoh</th>
                                            <th scope="col">Bil</th>
                                            <th scope="col">RM</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @for($i=0;$i<13;$i++)
                                        <tr>
                                            <td>{{ ($i == 12) ? '12 >' : ($i + 1)  }} bulan</td>
                                            <td>{{ number_format($data_filter['count'][$i]) }}</td>
                                            <td>{{ number_format($data_filter['sum'][$i],2) }}</td>
                                        </tr>
                                        @endfor
                                    </tbody>
                                    <tfoot class="thead-light">
                                        <tr>
                                            <th scope="col">Keseluruhan</th>
                                            <th scope="col">{{ number_format($data_filter['count'][13]) }}</th>
                                            <th scope="col">{{ number_format($data_filter['sum'][13],2) }}</th>
                                        </tr>
                                    </tfoot>
                                </table>

                            </div>
                        </div>
                    </div>

                    <div class="mt-3 d-flex justify-content-center">

                        <div class="card bg-light mb-3 col-10">
                            <span class="font-weight-bold mt-2 mb-2">Bilangan Orang Bulanan</span>
                            <div class="card-body">
                                <div id="chartbilangan">
                                </div>
                            </div>
                        </div>

                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script>
    const d = new Date();
    let tahunsemasa = d.getFullYear();
    let pusherenv = "{{ env('PUSHER_APP_KEY') }}";
    let api_url = "{{ $api_url }}";

    const formatter = new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2
    });

    var options = {
        series: [{
            name: 'Actual',
            data: []
        }],
        chart: {
            id: 'pembiayaan-bulanan',
            height: 350,
            type: 'bar'
        },
        yaxis: {
            labels: {
                formatter: function (value) {
                    return 'RM ' + formatter.format(value);
                }
            },
        },
        plotOptions: {
            bar: {
                columnWidth: '60%',
                dataLabels: {
                    position: 'top',
                },
            }
        },
        colors: ['#3498db'],
        dataLabels: {
            enabled: true,
            style: {
                colors: ['#333']
            },
            offsetY: -30,
            formatter: function (val, opt) {
                let total = ((val - opt.w.globals.seriesGoals[0][opt.dataPointIndex][0]['value']) / opt.w
                    .globals.seriesGoals[0][opt.dataPointIndex][0]['value']) * 100

                if (isNaN(total)) {
                    return 0.00
                } else {
                    if (isFinite(total)) {
                        if (total == -100) {
                            return 0.00
                        } else {
                            return total.toFixed(2)
                        }
                    } else {
                        return 0.00
                    }
                }
            },
        },
        legend: {
            show: true,
            showForSingleSeries: true,
            customLegendItems: ['Actual', 'Expected'],
            markers: {
                fillColors: ['#3498db', '#e74c3c']
            }
        }
    };

    var optionsbilangan = {
        series: [{
            name: 'Pembiayaan',
            data: []
        }, {
            name: 'Penyelesaian Pembiayaan',
            data: []
        }],
        chart: {
            id: 'bilangan-bulanan',
            height: 350,
            type: 'bar'
        },
        plotOptions: {
            bar: {
                horizontal: false,
                columnWidth: '55%',
                endingShape: 'rounded',
                dataLabels: {
                    position: 'top',
                },
            },

        },
        dataLabels: {
            enabled: true,
            distributed: true,
            style: {
                colors: ['#333'],
                fontSize: '12px',
                fontWeight: 'bold'
            },
            dropShadow: {
                enabled: true,
                left: 2,
                top: 2,
                opacity: 0.5
            },
            offsetY: -30,
            background: {
                enabled: true,
                foreColor: '#fff',
                borderRadius: 2,
                padding: 4,
                opacity: 0.9,
                borderWidth: 1,
                borderColor: '#fff'
            },
            formatter: function (val, opt) {
                let total = ((val - opt.w.globals.seriesGoals[0][opt.dataPointIndex][0]['value']) / opt.w
                    .globals.seriesGoals[0][opt.dataPointIndex][0]['value']) * 100

                if (isNaN(total)) {
                    return 0.00
                } else {
                    if (isFinite(total)) {
                        if (total == -100) {
                            return 0.00
                        } else {
                            return total.toFixed(2)
                        }
                    } else {
                        return 0.00
                    }
                }
            },
        },
        stroke: {
            show: true,
            width: 2,
            colors: ['transparent']
        },
        legend: {
            show: true,
            showForSingleSeries: true,
            customLegendItems: ['Pembiayaan', 'Penyelesaian Pembiayaan', 'Expected'],
            markers: {
                fillColors: ['#70a1ff', '#7bed9f', '#e74c3c']
            }
        },
        yaxis: {
            title: {
                text: '(Bilangan Orang)'
            }
        },
        fill: {
            opacity: 1,
            colors: ['#70a1ff', '#7bed9f']
        },
        tooltip: {
            y: {
                formatter: function (val) {
                    return val + " orang"
                }
            }
        }
    };


    var caw = "{{ $cawangan_info['kodcaw'] }}";
    //Declaration of Engine --> 0:idle 1:waiting 2:success
    var pembbul = 0;
    penbbul = 0;
    keunbul = 0;
    var pembtah = 0;
    penbtah = 0;
    keuntah = 0;
    var pembhar = 0;
    penbhar = 0;
    keunhar = 0;
    var bilangan = 0;


    //pusher
    var pusher = new Pusher(pusherenv, {
        cluster: 'ap1',
        encrypted: true
    });

    var channel = pusher.subscribe('gadai-notify');
    channel.bind('trigger-gadai', function (data) {

        if (pembbul == 0 && pembtah == 0 && pembhar == 0 && bilangan == 0) {
            if (data.cawangan === caw) {
                CallPembBulanan();
                CallPembTahunan();
                CallPembToday();
                CallBilangan();
            }
        }

    });

    var channel = pusher.subscribe('tebus-notify');
    channel.bind('trigger-tebus', function (data) {
        if (penbbul == 0 && penbtah == 0 && penbhar == 0 && bilangan == 0) {
            if (data.cawangan === caw) {
                CallPenbBulanan();
                CallPenbTahunan();
                CallPenbToday();
                CallBilangan();
            }
        }

    });

    var channel = pusher.subscribe('keuntungan-notify');
    channel.bind('trigger-keuntungan', function (data) {
        if (keunbul == 0 && keuntah == 0 && keunhar == 0) {
            if (data.cawangan === caw) {
                CallKeunBulanan();
                CallKeunTahunan();
                CallKeunToday();
            }
        }

    });


    function CallPembBulanan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/pembiayaanBulanan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                pembbul = 1;
            },
            success: function (data) {
                pembbul = 2;
                datapembiayaan(data);
            }
        });

    }

    function CallPenbBulanan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/penebusanBulanan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                penbbul = 1;
            },
            success: function (data) {
                penbbul = 2;
                datapenebusan(data);
            }
        });

    }

    function CallKeunBulanan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/keuntunganBulanan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                keunbul = 1;
            },
            success: function (data) {
                keunbul = 2;
                datakeuntungan(data);
            }
        });

    }

    function CallPembToday() {
        $.ajax({
            method: 'get',
            url: api_url + '/admin/pembiayaanToday',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            beforeSend: function () {
                pembhar = 1;
            },
            success: function (data) {
                $('#pembharian').text('RM' + formatter.format(data[0].gadaiToday));
                $('#pembbajet').text('RM' + formatter.format(data[0].bajetharian.toFixed(2)));
                $('#pembpercent').text(data[0].percentDiff.toFixed(2) + '%');
                $('#pembprogress').text(100 - data[0].percentcum + '%');
                // $("#pembprogress").css("width",100 - data[0].percentcum);
                $("#pembprogress").width(100 - data[0].percentcum + '%');
                // this.gadaianremaining = formatter.format(data[0].remaining.toFixed(2)),
                // this.percentcumgadai = (100 - data[0].percentcum)
                pembhar = 0;
            }
        });

    }

    function CallPenbToday() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/penebusanToday',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            beforeSend: function () {
                penbhar = 1;
            },
            success: function (data) {
                $('#penbharian').text('RM' + formatter.format(data[0].tebusToday));
                $('#penbbajet').text('RM' + formatter.format(data[0].bajetharian.toFixed(2)));
                $('#penbpercent').text(data[0].percentDiff.toFixed(2) + '%');
                $('#penbprogress').text(100 - data[0].percentcum + '%');
                // $("#penbprogress").css("width",100 - data[0].percentcum);
                $("#penbprogress").width(100 - data[0].percentcum + '%');
                // this.gadaianremaining = formatter.format(data[0].remaining.toFixed(2)),
                // this.percentcumgadai = (100 - data[0].percentcum)
                penbhar = 1;
            }
        });
    }

    function CallKeunToday() {
        $.ajax({
            method: 'get',
            url: api_url + '/admin/keuntunganToday',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            beforeSend: function () {
                keunhar = 1;
            },
            success: function (data) {
                $('#keunharian').text('RM' + formatter.format(data[0].upahToday));
                $('#keunbajet').text('RM' + formatter.format(data[0].bajetharian.toFixed(2)));
                $('#keunpercent').text(data[0].percentDiff.toFixed(2) + '%');
                $('#keunprogress').text(100 - data[0].percentcum + '%');
                // $("#keunprogress").css("width",100 - data[0].percentcum);
                $("#keunprogress").width(100 - data[0].percentcum + '%');
                // this.gadaianremaining = formatter.format(data[0].remaining.toFixed(2)),
                // this.percentcumgadai = (100 - data[0].percentcum)
                keunhar = 0;
            }
        });
    }

    function CallPembTahunan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/pembiayaanTahunan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                pembtah = 1;
            },
            success: function (data) {

                $('#pembactualtahunan').text('RM' + formatter.format(data[0].total));
                $('#pembbajettahunan').text('RM' + formatter.format(data[0].bajet));
                pembtah = 0;
            }
        });

    }

    function CallPenbTahunan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/penebusanTahunan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa

            },
            beforeSend: function () {
                penbtah = 1;
            },
            success: function (data) {

                $('#penbactualtahunan').text('RM' + formatter.format(data[0].total));
                $('#penbbajettahunan').text('RM' + formatter.format(data[0].bajet));
                penbtah = 0;
            }
        });
    }

    function CallKeunTahunan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/keuntunganTahunan',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                keuntah = 1;
            },
            success: function (data) {

                $('#keunactualtahunan').text('RM' + formatter.format(data[0].total));
                $('#keunbajettahunan').text('RM' + formatter.format(data[0].bajet));
                keuntah = 0;
            }
        });

    }

    function CallBilangan() {

        $.ajax({
            method: 'get',
            url: api_url + '/admin/bilangan/gadai',
            datatype: 'json',
            data: {
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'year': tahunsemasa
            },
            beforeSend: function () {
                bilangan = 1;
            },
            success: function (datagadai) {

                $.ajax({
                    method: 'get',
                    url: api_url + '/admin/bilangan/tebus',
                    datatype: 'json',
                    data: {
                        'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                        'year': tahunsemasa
                    },
                    success: function (datatebus) {
                        bilangan = 2;
                        bilanganbulanan(datagadai, datatebus);
                    }
                });
            }
        });
    }


    $(document).ready(function () {

        CallPembBulanan();
        CallPenbBulanan();
        CallKeunBulanan();
        CallPembToday();
        CallPenbToday();
        CallKeunToday();
        CallPembTahunan();
        CallPenbTahunan();
        CallKeunTahunan();
        CallBilangan();

    });

    function datapembiayaan(datapemb) {
        let chartpemb = new ApexCharts(document.querySelector("#chartpembiayaan"), options);
        chartpemb.render();
        chartpemb.updateSeries([{
            data: datapemb
        }]);

        pembbul = 0;
        pembtah = 0;
        pembhar = 0;
    }

    function datapenebusan(datapen) {
        var chartpen = new ApexCharts(document.querySelector("#chartpenebusan"), options);
        chartpen.render();
        chartpen.updateSeries([{
            data: datapen
        }]);

        penbbul = 0;
        penbtah = 0;
        penbhar = 0;
    }

    function datakeuntungan(datakeun) {
        var charkeun = new ApexCharts(document.querySelector("#chartkeuntungan"), options);
        charkeun.render();
        charkeun.updateSeries([{
            data: datakeun
        }]);

        keunbul = 0;
        keuntah = 0;
        keunhar = 0;
    }

    function bilanganbulanan(datagadai, datatebus) {
        var charbil = new ApexCharts(document.querySelector("#chartbilangan"), optionsbilangan);
        charbil.render();
        charbil.updateSeries(
            [{
                    name: 'Gadai',
                    data: datagadai
                },
                {
                    name: 'Tebus',
                    data: datatebus
                },
            ]
        );

        bilangan = 0;
    }

</script>

@endsection
