@extends('layouts.app')
@section('content')
<!-- The Modal -->
<div class="modal fade" id="marhunModal">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title"></h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <h4>Marhun</h4>
                        <table id="biasa" class="table table-striped table-bordered text-center" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Bil</th>
                                    <th>Jenis Marhun</th>
                                    <th>Berat Bersih</th>
                                    <th>Karat</th>
                                    <th>Nilai Marhun</th>
                                    <th>Nota</th>
                                    <th>Berat Permata</th>
                                </tr>
                            </thead>
                            <tbody id="tablemarhun">
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 text-right">
                        Jumlah Berat Marhun (gm)
                    </div>
                    <div class="col-md-4">
                        <input type="text" readonly id="jumlah_berat" name="jumlah_berat" class="form-control">
                    </div>
                </div>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>

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

<div class="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"><a href="{{ url('menu') }}">Khazanah</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Kelulusan Pembiayaan</li>
                    </ol>
                </nav>

                <div class="card-body text-center">
                    @if (\Session::has('type') == true && Session::get('type') == 'unavailable')
                    <script>
                        Swal.fire(
                            "{!! \Session::get('message') !!}",
                            "{{ \Session::get('norujukan') }}",
                            'warning'
                        )

                    </script>
                    @elseif(\Session::has('type') == true && Session::get('type') == 'scanned')
                    <div class="alert alert-success text-bold d-flex mx-auto justify-content-center w-50">
                        {!! \Session::get('message') !!} <br> {{ \Session::get('norujukan') }}
                    </div>
                    @endif
                    <div class="row mb-4">
                        <div class="col-2 justify-content-start">
                        </div>
                        <div class="col-8 justify-content-center">
                            <form action="{{ route('barcode.scanned') }}" method="post">
                                @csrf
                                <label>Scan Barcode Kemasukan Marhun Ke Peti Besi</label>
                                <input type="text" class="form-control col-4 mx-auto" name="norujukan_barcode"
                                    autocomplete="off" id="norujukan_barcode" required />
                                <input type="submit" id="submit_button" name="submit_button" hidden>
                            </form>
                        </div>
                        <div class="col-2">
                        </div>
                    </div>

                    <ul class="nav nav-tabs" id="myTab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="gadaian-semasa-tab" data-toggle="tab" href="#gadaian-semasa"
                                role="tab" aria-controls="gadaian-semasa" aria-selected="true">Pembiayaan Masuk</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="gadaian-belum-serah-tab" data-toggle="tab"
                                href="#gadaian-belum-serah" role="tab" aria-controls="gadaian-belum-serah"
                                aria-selected="false">Pengesahan Marhun</a>
                        </li>
                    </ul>

                    <div class="tab-content" id="myTabContent">
                        <div class="tab-pane fade show active" id="gadaian-semasa" role="tabpanel"
                            aria-labelledby="gadaian-semasa-tab">
                            <div class="row mb-4">
                                <div class="col-2">
                                </div>
                                <div class="col-8 justify-content-center">
                                </div>
                                <div class="col-2 justify-content-end">
                                </div>
                            </div>
                            <table class='table table-striped table-hover' id='table-gadaian-semasa'>
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Rujukan</th>
                                        <th>Pembiayaan</th>
                                        <th>N. Marhun</th>
                                        <th>Teller</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if (is_array($gadai) || is_object($gadai))
                                    @foreach($gadai as $index=>$gadaian)
                                    <tr>
                                        <td>{{ $index+1 }}</td>
                                        <td>
                                            @php
                                            $marhun = Http::withOptions(['verify' =>
                                            config('app.api_verify')])->get($api_url . '/api/marhun/' .
                                            $gadaian['norujukan'] )->json();
                                            @endphp
                                            <a style="user-select: none;" href="#" data-toggle="modal"
                                                data-berat="{{$gadaian['berat']}}"
                                                data-marhun="{{ json_encode($marhun) }}"
                                                data-norujukan="{{$gadaian['norujukan']}}"
                                                data-hargajualan="{{$gadaian['hargajualan']}}"
                                                data-kodcaw="{{ $gadaian['kodcaw'] }}" data-target="#marhunModal">
                                                {{$gadaian['norujukan']}}</a>
                                        </td>
                                        <td>{{ number_format($gadaian['pinjaman'],2) }}</td>
                                        <td>{{ number_format($gadaian['nilaimarhun'],2) }}</td>
                                        <td>{{ $gadaian['teller'] }}</td>
                                    </tr>
                                    @endforeach
                                    @endif
                                </tbody>
                            </table>
                        </div>

                        <div class="tab-pane fade" id="gadaian-belum-serah" role="tabpanel"
                            aria-labelledby="gadaian-belum-serah-tab">
                            <div class="row mb-4">
                                <div class="col-1">
                                </div>
                                <div class="col-8 justify-content-center">
                                </div>
                                <div class="col-3 justify-content-end">
                                </div>
                            </div>
                            <table class='table table-striped table-hover' id='table-gadaian-belum-serah'>
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Rujukan</th>
                                        <th>Masa Terima</th>
                                        <th>N. Marhun</th>
                                        <th>Marhun</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if (is_array($petibesi) || is_object($petibesi))
                                    @php $total_nm = 0; @endphp
                                    @foreach($petibesi as $index=>$marhun)
                                    @php $total_nm += $marhun['nilaimarhun']; @endphp
                                    <tr>
                                        <td>{{ $index+1 }}</td>
                                        <td>
                                            @php
                                            $marhun_detail = Http::withOptions(['verify' =>
                                            config('app.api_verify')])->get($api_url . '/api/marhun/' .
                                            $marhun['norujukan'] )->json();
                                            @endphp
                                            <a href="#" data-toggle="modal" data-berat="{{$marhun['berat']}}"
                                                data-marhun="{{ json_encode($marhun_detail) }}"
                                                data-norujukan="{{$marhun['norujukan']}}"
                                                data-hargajualan="{{$marhun['hargajualan']}}"
                                                data-kodcaw="{{ $marhun['kodcaw'] }}" data-target="#marhunModal">
                                                {{$marhun['norujukan']}}</a>
                                        </td>
                                        <td>{{ number_format($marhun['pinjaman'],2) }}</td>
                                        <td>{{ number_format($marhun['nilaimarhun'],2) }}</td>
                                        <td>{{ $marhun['teller'] }}</td>
                                    </tr>
                                    @endforeach
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="row mt-5">
                        <div class="col-md-12">
                            <div class="row form-group justify-content-end">
                                <label class="label-control mr-3">Nilai Marhun Terkumpul</label>
                                <input class="form-control col-md-3" type="text"
                                    value="{{ number_format($total_nm,2) }}" readonly />
                            </div>
                        </div>

                    </div>
                    <div class="row mt-2 d-flex justify-content-end">
                        <a href="{{ route('laporanscanbarcode') }}" target="_blank" class="btn btn-info mr-md-2">Rekod
                            Barcode Pembiayaan</a>
                        <!-- <a href="#" class="btn btn-info">Senarai Pembatalan No Rujukan</a> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var api_url = "<?php echo $api_url ?>";
    var cawangan = "{{ Auth::user()->cawangan }}";


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

    //modal

    var tablegadaianmasuk = $('#table-gadaian-semasa').DataTable({
        //   "scrollX": true
    });

    var pengesahanmarhun = $('#table-gadaian-belum-serah').DataTable({
        //   "scrollX": true
    });

    var pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
        cluster: 'ap1',
        encrypted: true
    });

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

        if (cawangan == data.kodcaw) {
            fetchGadaianEverytime();
        }
    });

    $(document).ready(function () {
        $('#norujukan_barcode').focus();
    })

    $('#marhunModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // button yg trigger
        var arraymarhun = button.data('marhun');
        var norujukan = button.data('norujukan');
        var kodcaw = button.data('kodcaw');
        var hargajualan = button.data('hargajualan');
        var total_berat = button.data('berat');

        $('#jumlah_berat').val(total_berat);
        var bil_count = 0;
        $('#tablemarhun').empty();
        $.each(arraymarhun, function (index, marhun) {
            $.each(marhun, function (index, marhun_detail) {
                var marhun_name;
                $.ajax({
                    method: 'GET',
                    url: api_url + '/api/jemas/nama_marhun',
                    dataType: 'json',
                    data: {
                        marhun: marhun_detail['marhun']
                    },
                    success: function (marhun_ajax) {
                        bil_count++;
                        var valBatuPermata = marhun_detail['berat_batu_permata'] != null ? marhun_detail['berat_batu_permata'] : '';
                        var valTagPermata = marhun_detail['tag_permata'] == 1 ? '(PMT) ' : '';
                        var notaDanTag = valTagPermata + marhun_detail['nota'];
                        $("#tablemarhun").append("<tr><td>" + bil_count +
                            "</td><td>" + marhun_ajax['descpt'] + "</td><td>" +
                            marhun_detail['berat'] + "</td><td>" +
                            marhun_detail['karat'] + "</td><td>RM " +
                            marhun_detail['n_marhun'].toLocaleString(
                                undefined, {
                                    minimumFractionDigits: 2
                                }) + "</td><td>" + notaDanTag +
                                    "</td><td>" + valBatuPermata +
                            "</td></tr>");
                    }
                });
            });
        });

    })

    function fetchGadaianEverytime() {

        tablegadaianmasuk.clear().draw();

        $.ajax({
            method: 'get',
            url: api_url + '/api/gadai/serah_marhun/khazanah/' + cawangan,
            success: function (data) {
                var count = 0;
                $.each(data, function (index, gadaianmasuk) {
                    $.ajax({
                        url: api_url + '/api/marhun/' + gadaianmasuk['norujukan'],
                        method: 'get',
                        success: function (rekodmarhun) {

                            count++;
                            tablegadaianmasuk.row.add([
                                count,
                                '<a style="user-select: none;" href="#" data-toggle="modal" data-berat=' +
                                gadaianmasuk['berat'] + ' data-marhun=' + JSON
                                .stringify(rekodmarhun) + '  data-pinjaman=' +
                                gadaianmasuk['pinjaman'] + ' data-norujukan=' +
                                gadaianmasuk['norujukan'] +
                                ' data-hargajualan=' + gadaianmasuk[
                                    'hargajualan'] + ' data-kodcaw=' +
                                gadaianmasuk['kodcaw'] +
                                ' data-target="#marhunModal"> ' + gadaianmasuk[
                                    'norujukan'] + '</a>',
                                formatter.format(gadaianmasuk['pinjaman']),
                                formatter.format(gadaianmasuk['nilaimarhun']),
                                gadaianmasuk['teller']
                            ]).draw();
                        }
                    });
                });
            }
        });
    }

    // function checkserah(func){
    //     event.preventDefault();
    //     var norujukan = $('#norujukan_barcode').val();
    //     $.ajax({
    //         method:'get',
    //         url: api_url + '/api/check/serah/gadai',
    //         datatype:'json',
    //         data:{
    //             'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
    //             'norujukan': norujukan
    //         },
    //         success:function(data){
    //             console.log(data);
    //             if(data == 'true'){
    //                 Swal.fire({
    //                     icon: 'error',
    //                     title: 'Amaran',
    //                     text: 'Gadaian Sudah Scan'
    //                 });
    //                 event.preventDefault();
    //                 return false;
    //             }else if(data == 'false'){
    //                 $(func).attr("onSubmit","return true;");
    //                 $(func).submit();
    //                 return true;
    //             }
    //         }
    //     });
    // }

</script>
@endsection
