@extends('layouts.app')
@section('content')
@include('modal.historybayaran')
@include('modal.wakil')


<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">

            <nav aria-label="breadcrumb">
                <ol class="breadcrumb pb-3">
                  <li class="breadcrumb-item"><a href="#" style="cursor:not-allowed;">Home</a></li>
                  <li class="breadcrumb-item"><a href="#" style="cursor:not-allowed;">Pengenalan Diri</a></li>
                  <li class="breadcrumb-item"><a href="#" style="cursor:not-allowed;">Pelanggan</a></li>
                  <li class="breadcrumb-item active" aria-current="page">Penyelesaian Pem.</li>
                </ol>
              </nav>

            <div class="form-group row col-12">

            <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <b>NAMA</b>
                        </div>
                        <div class="col-8">
                        <input type="text" value="{{ $nama }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <b> NO PELANGGGAN</b>
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['nopelanggan'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <b>NO RUJUKAN</b>
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['norujukan'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <b>NO KAD PENGENALAN</b>
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['nokp'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <b>JENIS PENYELESAIAN PEMBIAYAAN</b>
                        </div>
                        <div class="col-8">
                            <select class="form-control" id="sltjenistebus">
                                <option value="T">T = Penyelesaian Pembiayaan</option>
                                @if($gadai['hargajualan'] != null)
                                    <option value="A">A = Ansuran Pembiayaan</option>
                                    <option value="S">S = Separuh</option>
                                    <option value="P">P = Tambah Pembiayaan</option>
                                @endif
                                @if($gadai['hargajualan'] == null)
                                    <option value="U">U = Bayaran Keuntungan</option>
                                @endif
                              </select>
                        </div>
                    </div>
                </div>
                {{-- <div class="col-4"><b>
                    <div class="form-group row" >
                        <div class="col-4<b>">
                            <b>NO SIRI TEBUS</b>
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control">
                        </div>
                    </div>
                </div> --}}
                <div class="col-6">
                    {{-- <div class="form-group row">
                        <div class="col-4">
                            <b>WAKIL</b>
                        </div>
                        <div class="col-6">
                            <input type="text" class="form-control" name="wakil" id="wakiltxt" />
                        </div>
                        <div class="col-2">
                            <button class="btn btn-primary" id="caribtn" onclick="wakilfunction(this)">Cari</button>
                        </div>
                    </div> --}}
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <table id="tablemarhun" class="table table-striped table-hover table-bordered text-center">
                        <thead class="thead-dark">
                            <tr>
                                <th>Bil</th>
                                <th>Marhun</th>
                                <th>N. Marhun</th>
                                <th>N. Marhun Semasa</th>
                                <th>Berat/gram</th>
                                <th>Karat</th>
                                <th>Harga</th>
                                <th>Harga Semasa</th>
                                <th>Nota</th>
                            </tr>
                        </thead>
                        <tbody>
                            @php $count = 0; @endphp
                            @foreach ($marhun as $index=>$m)
                            <tr>
                            @php
                                $karatbaru = str_replace('.','-',$m['karat']);
                                $hargabaru = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') . '/api/harga_emas/'. $karatbaru)->json();

                                $hargaemassemasa = floatval($hargabaru['harga']) * floatval($m['berat']);
                                @endphp
                            <td><input type="checkbox" id="checkmarhun" data-nmhs="{{ $hargaemassemasa }}" data-recno="{{ $m['recno'] }}" data-nm="{{ $m['n_marhun'] }}" data-marhun="{{ $m['marhun'] }}" data-berat="{{ $m['berat'] }}" style="display:none;"/><span class="spannar">{{ $index+1 }}</span></td>
                            @php
                            $marhunperibadi = Http::withOptions(['verify' => config('app.api_verify')])->get(config('api.url') .'/api/jemas/nama_marhun/',["marhun" => $m['marhun']])->json();
                            @endphp
                            <td>{{ $marhunperibadi['descpt'] }}</td>
                            <td>RM {{ number_format($m['n_marhun'],2) }}</td>
                            <td>@php
                                echo "RM " . number_format($hargaemassemasa,2);
                            @endphp</td>
                            <td>{{ $m['berat'] }}</td>
                            <td>{{ $m['karat'] }}</td>
                            <td>RM {{ $m['harga'] }}</td>
                            <td>RM {{ number_format(floatval($hargabaru['harga']),2) }} @php  if($m['harga'] > $hargabaru['harga']) echo '<span class="fas fa-arrow-down text-danger"></span>'; if($m['harga'] < $hargabaru['harga']) echo '<span class="fas fa-arrow-up text-success"></span>';
                            if($m['harga'] === $hargabaru['harga']) echo '<span class="fas fa-minus text-info"></span>';
                            @endphp</td>
                            <td>RM {{ $m['nota'] }}</td>
                            </tr>
                            @php $count++; @endphp
                            @endforeach
                        </tbody>
                        <tr>
                            <td colspan="2"><b>JUMLAH</b></td>
                            <td id="nilai_marhun_total">RM {{ number_format($gadai['nilaimarhun'],2) }}</td>
                            <td id="nilai_marhun_total">RM {{ number_format($nilaihargasemasa,2) }}</td>
                            <td id="berat_marhun_total">{{ number_format($gadai['berat'],2) }}</td>
                            <td colspan="3"></td>
                          </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
            {{-- {{dd($gadai)}} --}}
            <div class="card">
                <div class="card-body">
                    <form action="">
                        <div class="col-12 form-group row">
                            {{-- <div class="col-4"></div> --}}
                            <div class="col-6" id="divbakihargajualan">

                                <div class="form-group row">
                                    <div class="col-4">
                                        BAKI HARGA JUALAN(RM)
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="bakihargajualan" value="{{ number_format($gadai['bakihargajualan'],2) }}" class="form-control" readonly/>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <div class="col-4">
                                        BAKI PEMBIAYAAN(RM)
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="pinjaman" value="{{ number_format($gadai['bakipjm'],2) }}" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>

                            <div class="col-6" id="divpembiayaanasal">

                                <div class="form-group row">
                                    <div class="col-4">
                                        PEMBIAYAAN ASAL(RM)
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="pinjamanasal" value="{{ number_format($gadai['pinjaman'],2) }}" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>

                            <div class="col-6">
                                <div class="form-group row">
                                    <div class="col-4">
                                        JUMLAH KEUNTUNGAN
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="jumlahupah" class="form-control" readonly/>
                                    </div>
                                </diV>

                                <div class="form-group row" id="divhargaemassemasa">
                                    <div class="col-4">
                                        PEMBIAYAAN H. ASAL (RM)
                                    </div>
                                    @php
                                        $percent_asal = ($gadai['bakipjm'] / $gadai['nilaimarhun']) * 100;
                                    @endphp
                                    <div class="col-8 input-group mb-2">
                                        <input type="text" id="hargapembiayaansemasa" class="form-control" value="{{ number_format($gadai['bakipjm'],2) }}" aria-describedby="basic-hargaemas" readonly/>
                                        <div class="input-group-append">
                                            <span class="input-group-text" id="basic-hargaemas">{{ number_format($percent_asal,2) }}</span>
                                        </div>
                                    </div>
                                </diV>

                                <div class="form-group row" id="divtelahdibayar">
                                    <div class="col-4">
                                        TELAH DIBAYAR(RM)
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="jumlahtelahdibayar" class="form-control" readonly/>
                                    </div>
                                </diV>
                            </div>
                            <div class="col-6">
                                <div class="form-group row" id="divbayaran">
                                    <div class="col-4">
                                       BAYARAN PEMBIAYAAN(RM)
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="bayaran" onkeyup="bayartambahan(this)" placeholder="0.00" class="form-control" disabled/>
                                    </div>
                                </div>
                                <div class="form-group row" id="divtambahpinjaman">
                                    <div class="col-4">
                                       TAMBAH PEMBIAYAAN(RM)
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="tambahpinjam" onkeyup="bayarpinjam(this)" placeholder="0.00" class="form-control"/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="tambahpinjamsebenar" placeholder="0.00" class="form-control" disabled/>
                                    </div>
                                </diV>

                            </div>

                            <div class="col-6" id="divbakipinjaman">
                                <div class="form-group row">
                                    <div class="col-4">
                                        <b>PEMBIAYAAN BARU(RM)</b>
                                    </div>
                                    <div class="col-8 input-group mb-2">
                                        <input type="text" placeholder="0.00" id="bakipinjaman" class="form-control" readonly/>
                                    <div class="input-group-append">
                                        <span class="input-group-text" id="basic-separuh"></span>
                                    </div>
                                </div>
                                </div>
                            </div>

                            <div class="col-6" id="divperludibayar">
                                <div class="form-group row">
                                    <div class="col-4">
                                        <b>PERLU DIBAYAR(RM)</b>
                                    </div>
                                    <div class="col-8">
                                        <input type="text" id="perludibayar" onkeyup="bayarkey(this)" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>


                            <div class="col-6" id="divpinjamanbaru">

                                <div class="form-group row">
                                    <div class="col-4">
                                        <b>PEMBIAYAAN BARU(RM)</b>
                                    </div>
                                    @php
                                        $percent_hargaemassemasa = ($gadai['bakipjm'] / $nilaihargasemasa) * 100;
                                    @endphp
                                    <div class="col-8 input-group mb-3">
                                        <input type="text" id="pinjamanbaru" value="{{ number_format($gadai['bakipjm'],2) }}" class="form-control" aria-describedby="basic-addon2" readonly/>
                                        <div class="input-group-append">
                                        <span class="input-group-text" id="basic-addon2">{{ number_format($percent_hargaemassemasa,2) }}</span>
                                          </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6" id="divbayaranditerima">
                                <div class="form-group row">
                                    <div class="col-4">
                                        <b>BAYARAN DITERIMA(RM)</b>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="bayaranditerima" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>


                            <div class="col-12">
                                <input type="button" class="float-right btn btn-danger mr-2" value="BATAL" onclick="window.location.replace('{{  route('khazanah.customer_info') }}')">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>

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

    $('form input').keydown(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

    var historybayarandatatable = $('#tablehistorybayaran').DataTable({
        "ordering": false
    });

    var api = '<?php echo $api_url ?>';
    let nw = 0;

    $('input[type="checkbox"]').hide();
    $('#divtambahpinjaman').hide();
    $('#divpinjamanbaru').hide();
    $('#divbayaranditerima').hide();
    $('#divbakipinjaman').hide();
    $('#divhargaemassemasa').hide();


    var array_recno = [];
    var array_nm = [];
    var array_marhun = [];
    var array_berat = [];
    // var array_nmhs = [];

    //max bayaran
    let jumlahasalmarhun = parseFloat("{{ $gadai['nilaimarhun'] }}");
    let totalmarhun = jumlahasalmarhun;
    let totalmarhunhargasemasa = jumlahasalmarhun;

    let bayaranseparuhasal = 0;

    let bilangan_marhun = Number("{{ $count }}");

    bilmarhun = () => {
        if(bilangan_marhun ==1){
            $('option[value="S"]').attr("disabled", true);
        }else{
            $('option[value="S"]').attr("disabled", false);
        }
    }

    bilmarhun();


    var hargajualan = "{{ $gadai['hargajualan'] }}";


    var kodcaw = "{{ $gadai['kodcaw'] }}";
    var norujukan = "{{ $gadai['norujukan'] }}";

    var jumlahperlu = 0;
    var jumlahminima = 0;


    $( document ).ready(function() {
        tebusan();

        $("#bayaran").inputFilter(function(value) {
            return /^\d*\.?(?:\d{1,2})?$/.test(value);    // Allow digits only, using a RegExp
        });

        $("#tambahpinjam").inputFilter(function(value) {
            return /^\d*\.?(?:\d{1,2})?$/.test(value);    // Allow digits only, using a RegExp
        });

    });

    function tebusan(){
        if(hargajualan != '' ){
            let maxgadaila = "{{ $maxgadai = ($gadai['nilaimarhun'] * 0.7) - $gadai['bakipjm'] }}";
            let maxgadaipembiayaanbaru = "{{ $maxgadaipemb = ($nilaihargasemasa * 0.7) - $gadai['bakipjm'] }}";

            $('#tambahpinjamsebenar').val(Number(maxgadaipembiayaanbaru).toFixed(2));

            $('#divpembiayaanasal').hide();
            $('#divbakihargajualan').show();
            $('#divtelahdibayar').show();
            $('#histbtn').show();

            //Upah Tawarruq
            $.ajax({
                method:'GET',
                url: api + '/api/upahtawarruq/' + kodcaw + '/' + norujukan,
                dataType: 'json',
                success:function(data){
                    $('#jumlahupah').val(data);
                    $('#bayaranditerima').val(data);
                }
            });

            //Tebus Tawarruq
            $.ajax({
                method:'GET',
                url: api + '/api/tebustawarruq/' + kodcaw + '/' + norujukan,
                dataType: 'json',
                success:function(harga_tebus){
                    $('#perludibayar').val(formatter.format(harga_tebus));
                }
            });


        }else if(hargajualan == ''){
            let maxgadaila = "{{ $maxgadai = ($gadai['nilaimarhun'] * 0.7) - $gadai['pinjaman'] }}";

            $('#tambahpinjamsebenar').val(formatter.format(Number(maxgadaila).toFixed(2)));

            $('#divpembiayaanasal').show();
            $('#divbakihargajualan').hide();
            $('#divtelahdibayar').hide();
            $('#histbtn').hide();

            //Upah Bukan Tawarruq
            $.ajax({
                method:'GET',
                url: api + '/api/upahbukantawarruq/' + kodcaw + '/' + norujukan,
                dataType: 'json',
                success:function(data){
                    $('#jumlahupah').val(data);
                    $('#bayaranditerima').val(data);
                }
            });

            //Tebus Bukan Tawarruq
            $.ajax({
                method:'GET',
                url: api + '/api/tebusbukantawarruq/' + kodcaw + '/' + norujukan,
                dataType: 'json',
                success:function(data){
                    $('#perludibayar').val(data);
                }
            });


        }

        // Telah dibayar
        $.ajax({
            method:'GET',
            url: api + '/api/transaction/' + norujukan,
            dataType: 'json',
            success:function(data){
                var totaltelahdibayar = 0;

                if(data == '')
                {
                    $('#jumlahtelahdibayar').val(0);
                }
                else
                {
                    $.each(data,function(index,transaksi){

                        totaltelahdibayar += parseFloat(transaksi.duit_masuk);
                    });

                    $('#jumlahtelahdibayar').val(formatter.format(totaltelahdibayar));
                }

            }
        });

    }

    if(hargajualan != ''){

        //checked box
        var checkboxes = document.querySelectorAll('input[type="checkbox"]');
        var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);

        //Separuh Bayar Tawarruq
        $(document).on('click', '#checkmarhun', function(e) {

            var totalCheckboxes = $('input[type="checkbox"]').length;
            let numbernotchecked = $("input:checkbox:not(:checked)").length;

            var recno = $(this).data('recno');
            var nilaimarhun = $(this).data('nm');
            var marhun = $(this).data('marhun');
            var berat = $(this).data('berat');
            var nilaimarhunhargasemasa = $(this).data('nmhs');
            var nmsemasa = parseFloat("{{ $nilaihargasemasa }}");
            let totalnilaimarhunseparuh = 0;


            if ($(this).is(':checked')) {
                array_recno.push(recno);
                // array_nm.push(nilaimarhun); //nilai harga lama
                array_marhun.push(marhun);
                array_berat.push(berat);
                array_nm.push(nilaimarhunhargasemasa); //nilai harga semasa


                totalmarhun = totalmarhun - parseFloat(nilaimarhun);
                totalmarhunhargasemasa = totalmarhunhargasemasa - parseFloat(nilaimarhunhargasemasa);

            }else{
                var rm = array_recno.findIndex(x => x === recno);
                // var rmnilai = array_nm.findIndex(y => y == nilaimarhun); // harga lama
                var rmnilai = array_nm.findIndex(y => y == nilaimarhunhargasemasa); // harga lama
                // var rmhargasemasa = array_nmhs.findIndex(y => y == nilaimarhunhargasemasa);
                var rmmarhun = array_marhun.findIndex(z => z == marhun);
                var rmberat = array_berat.findIndex(a => a == berat);

                array_recno.splice(rm,1);
                // array_nm.splice(rmnilai,1); // yang lama
                array_marhun.splice(rmmarhun,1);
                array_berat.splice(rmberat,1);
                array_nm.splice(rmnilai,1); //yang harga semasa

                totalmarhun = totalmarhun + parseFloat(nilaimarhun);
                totalmarhunhargasemasa = totalmarhunhargasemasa + parseFloat(nilaimarhunhargasemasa);
            }

            $.each( array_nm, function( index, value ) {
                totalnilaimarhunseparuh += parseFloat(value);
            });

            // console.log("TOTAL HARGA SEMASA :" + totalmarhunhargasemasa);
            // console.log("TOTAL HARGA SEMASA SPEARUH :" + totalnilaimarhunseparuh);
            // console.log("YANG DIAMBIL :" + nilaimarhunhargasemasa);


            if(numbernotchecked != totalCheckboxes){

                // console.log(nmsemasa);
                $.ajax({
                    method:'GET',
                    url: api + '/api/tebusseparuhtawarruq/' + kodcaw + '/' + norujukan,
                    dataType: 'json',
                    data:{
                    "array_recno" : array_recno,
                    "hargasemasa" : nmsemasa
                    },
                    success:function(success){
                        let bayarz = $('#bayaran').val(formatter.format(success));



                        bayaranseparuhasal = Number(success);

                        let bakihargajual = $('#bakihargajualan').val().replace(/[^0-9.-]+/g,"");

                        $('#perludibayar').val(formatter.format(Number(success) +  parseFloat($('#jumlahupah').val())));

                        let totalbakipinjam = parseFloat($('#pinjaman').val().replace(/[^0-9.-]+/g,"")) - success;
                        $('#bakipinjaman').val(formatter.format(totalbakipinjam));

                        let bakinm = nmsemasa - totalnilaimarhunseparuh;
                        var totalcalculate = ((totalbakipinjam/bakinm)*100);

                        $('#basic-separuh').text(Number(totalcalculate.toFixed(2)));

                    },error:function(xhr, textStatus, errorThrown){
                        console.log(xhr.responseText);
                        console.log(textStatus);
                    }
                });

            }else{
                $('#perludibayar').val(parseFloat($('#jumlahupah').val()));
                $('#bakipinjaman').val(0);
                $('#basic-separuh').text(0)
                $('#bayaran').val(0);

            }
        });

    }
    else if(hargajualan == ''){
        //Separuh Bayar Bukan Tawarruq
        $(document).on('click', '#checkmarhun', function(e) {

        //checked box
        var checkboxes = document.querySelectorAll('input[type="checkbox"]');
        var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);


        //jumlah upah
        var jumupah = parseFloat($('#jumlahupah').val());

            var recno = $(this).data('recno');
            var nilaimarhun = $(this).data('nm');
            var marhun = $(this).data('marhun');
            var berat = $(this).data('berat');

            if ($(this).is(':checked')) {
                array_recno.push(recno);
                array_nm.push(nilaimarhun);
                array_marhun.push(marhun);
                array_berat.push(berat);
            }
            else{
                var rm = array_recno.findIndex(x => x === recno);
                var rmnilai = array_nm.findIndex(y => y == nilaimarhun);
                var rmmarhun = array_marhun.findIndex(z => z == marhun);
                var rmberat = array_berat.findIndex(a => a == berat);

                array_recno.splice(rm,1);
                array_nm.splice(rmnilai,1);
                array_marhun.splice(rmmarhun,1);
                array_berat.splice(rmberat,1);

            }

            if (checkedOne == false) {
                $('#perludibayar').val(jumupah);
                $('#bayaran').val(jumupah);
            }else{
                $.ajax({
                    method:'GET',
                    url: api + '/api/tebusseparuhbukantawarruq/' + kodcaw + '/' + norujukan,
                    dataType: 'json',
                    data:{
                    "array_recno" : array_recno
                    },
                    success:function(success){
                        jumlahminima = Number(success.toFixed(2));

                        $('#bayaran').val(jumlahminima);

                        $('#bakipinjaman').val($('#pinjamanasal').val() - jumlahminima);

                        $('#perludibayar').val(Number(success.toFixed(2)) +  parseFloat($('#jumlahupah').val()));
                        jumlahperlu = Number(success.toFixed(2)) + parseFloat($('#jumlahupah').val());
                    },
                    error: function (request, status, error) {
                        console.log(request.responseText);
                    }
                });
            }
        });
    }




    $("#sltjenistebus").change(function(){

        var jumupah = parseFloat($('#jumlahupah').val());

        switch($(this).val()) {
            case "T":
                $('input[type="checkbox"]').hide();
                $('span.spannar').show();

                $("#bayaran").prop("disabled", true);
                $("#perludibayar").prop("readonly", true);
                $("#bayaran").val(0);

                $('#divtambahpinjaman').hide();
                $('#divpinjamanbaru').hide();
                $('#divbayaranditerima').hide();
                $('#divbakipinjaman').hide();
                $('#divhargaemassemasa').hide();



                $('#divtelahdibayar').show();
                $('#divbayaran').show();
                $('#divperludibayar').show();

                tebusan();
                break;

            case "A":
                $('input[type="checkbox"]').hide();
                $('span.spannar').show();

                $("#bayaran").prop("disabled", false);
                $("#perludibayar").prop("readonly", true);
                $("#bayaran").val(0);

                $('#divtambahpinjaman').hide();
                $('#divpinjamanbaru').hide();
                $('#divbayaranditerima').hide();
                $('#divbakipinjaman').hide();
                $('#divhargaemassemasa').hide();


                $('#divtelahdibayar').show();
                $('#divbayaran').show();
                $('#divperludibayar').show();

                $('#perludibayar').val(formatter.format(jumupah));

                break;

            case "S":
                $('input[type="checkbox"]').show();
                $('span.spannar').hide();

                $("#bayaran").prop("disabled", true);
                $("#perludibayar").prop("readonly", false);
                $("#bayaran").val(0);

                $('#divtambahpinjaman').hide();
                $('#divpinjamanbaru').hide();
                $('#divbayaranditerima').hide();
                $('#divhargaemassemasa').hide();


                $('#divbakipinjaman').show();
                $('#divtelahdibayar').show();
                $('#divbayaran').show();
                $('#divperludibayar').show();



                $('#perludibayar').val(formatter.format(jumupah));
                break;

            case "P":
                $('input[type="checkbox"]').hide();
                $('span.spannar').show();
                $('#divpinjaman').show();
                $('#divtambahpinjaman').show();
                $('#divpinjamanbaru').show();
                $('#divbayaranditerima').show();
                $('#divhargaemassemasa').show();

                $('#divtelahdibayar').hide();
                $('#divbakipinjaman').hide();
                $('#divbayaran').hide();
                $('#divperludibayar').hide();


                $("#bayaran").prop("disabled", false);
                $("#bayaran").val(0);
                break;
            case "U":
                $('input[type="checkbox"]').hide();
                $('span.spannar').show();

                $("#bayaran").prop("disabled", false);
                $("#perludibayar").prop("readonly", true);
                $("#bayaran").val(0);

                $('#divtambahpinjaman').hide();
                $('#divpinjamanbaru').hide();
                $('#divbayaranditerima').hide();
                $('#divbakipinjaman').hide();
                $('#divhargaemassemasa').hide();


                $('#divtelahdibayar').hide();
                $('#divbayaran').hide();
                $('#divperludibayar').show();

                $('#perludibayar').val(formatter.format(jumupah));
                break;
        }

    });

    function bayarkey(e){

        if($('#sltjenistebus').find(":selected").val() == 'S'){
            let byr = $(e).val();
            let total = 0;
            let pdbyr = 0;
            let totalseparuh = 0;
            let totalnilaimarhunseparuh = 0;
            var nmsemasa = parseFloat("{{ $nilaihargasemasa }}");


            // console.log($('#jumlahupah').val());
            // console.log(bayaranseparuhasal);
            // console.log(byr);

            $.each( array_nm, function( index, value ) {
                totalnilaimarhunseparuh += parseFloat(value);
            });

            if(byr < (bayaranseparuhasal + parseFloat($('#jumlahupah').val()))){
                $('#bayaran').val(bayaranseparuhasal.toFixed(2));
            }else{
                totalseparuh = byr - parseFloat($('#jumlahupah').val());
                $('#bayaran').val(totalseparuh.toFixed(2));
            }

            // pdbyr = parseFloat(byr);
            pdbyr = $('#bayaran').val();
            total =  $('#pinjaman').val().replace(/[^0-9.-]+/g,"") - pdbyr;

            // $('#perludibayar').val(pdbyr);
            $('#bakipinjaman').val(total.toFixed(2));



            let bakinm = nmsemasa - totalnilaimarhunseparuh;
            var totalcalculate = ((total/bakinm)*100);

            $('#basic-separuh').text(Number(totalcalculate.toFixed(2)));


        }
    }

    function bayartambahan(e){
        if($('#sltjenistebus').find(":selected").val() == 'A'){
            if(hargajualan == ''){

                let byr = $(e).val();
                let total = 0;
                let pdbyr = 0;

                if(byr == ''){
                    $('#perludibayar').val($('#jumlahupah').val());
                }else{
                    pdbyr = parseFloat(byr) + parseFloat($('#jumlahupah').val());

                    $('#perludibayar').val(pdbyr);
                    // $('#perludibayar').val(total);
                }

            }
        }
    }


    function bayarpinjam(e){

        var maxpinjam = parseFloat($('#tambahpinjamsebenar').val());
        var pinjambaru = parseFloat($('#pinjamanbaru').val().replace(/[^0-9.-]+/g,""));
        var pinjam = parseFloat($('#pinjaman').val().replace(/[^0-9.-]+/g,""));
        var pembiayaanbaru = parseFloat($('#hargapembiayaansemasa').val().replace(/[^0-9.-]+/g,"")); //pembiayaan yang baru

        var nm = parseFloat("{{ $gadai['nilaimarhun'] }}");
        var nmsemasa = parseFloat("{{ $nilaihargasemasa }}");

        const percentpinj = parseFloat("{{ $percent_asal }}");
        const percentpemb = parseFloat("{{ $percent_hargaemassemasa }}"); //pembiayaan yang baru

        var totalpinjbaru=0;

        totalpinjbaru = pinjam + parseFloat(e.value);

        console.log(totalpinjbaru);

        var maxpinjaman = nmsemasa * 0.7;

        var bakimaxpinjaman = maxpinjaman - totalpinjbaru;

        $(e).val() == ''  ? $('#pinjamanbaru').val(pinjam.toFixed(2)) : $('#pinjamanbaru').val(totalpinjbaru.toFixed(2));
        $(e).val() == ''  ? $('#hargapembiayaansemasa').val(pinjam.toFixed(2)) : $('#hargapembiayaansemasa').val(totalpinjbaru.toFixed(2));

        // if(parseFloat($(e).val()) > maxpinjam)
        //     $(e).val(maxpinjam);

        var total = totalpinjbaru/nmsemasa * 100;
        var totalsemasa = totalpinjbaru/nm * 100;

        $(e).val() == ''  ? $('#tambahpinjamsebenar').val(maxpinjam.toFixed(2)) : $('#tambahpinjamsebenar').val(bakimaxpinjaman.toFixed(2));
        $(e).val() == ''  ? $('#basic-addon2').text(percentpemb.toFixed(2)) : $('#basic-addon2').text(total.toFixed(2));
        $(e).val() == ''  ? $('#basic-hargaemas').text(percentpinj.toFixed(2)) : $('#basic-hargaemas').text(totalsemasa.toFixed(2));

    }

    let teller = "{{ Auth::user()->name }}";


    function wakilfunction(e)
    {
        let wakil = $('#wakiltxt').val();

        if(wakil.length == 12)
        {
            $.ajax({
                method:'GET',
                url: "{{ route('wakil.search') }}",
                data:{
                    'wakil' : wakil
                },
                success:function(data){

                    if(data == 'no-data')
                    {
                        Swal.fire({
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonText: '<i class="fa fa-thumbs-up"></i> Daftar Dulu Boss!',
                        icon: 'info',
                        title: 'Maklumat anda tiada dalam senarai wakil! Tekan button okay untuk mendaftar!'
                        }).then(function(){
                            daftarfunction(wakil);
                        });
                    }else{
                        Swal.fire({
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonText: '<i class="fa fa-thumbs-up"></i> OK!!',
                        icon: 'success',
                        title: 'Maklumat Anda Berjaya Direkodkan!',
                        html: '<b class="text-danger">' + data.nama + '</b><br><b class="text-danger">' + data.nokp + '</b>'
                        });
                        nw = data.nowakil;

                        $('#wakiltxt').prop( "disabled", true );
                        $(e).html("Ubah");
                        $(e).attr("onclick","ubahwakil(this)");
                    }

                },error: function (request, status, error) {
                console.log(request.responseText);
            }
            });
        }
        else
        {
            Swal.fire({
                icon: 'error',
                titleText: 'Kad Pengenalan',
                text: 'mestilah tidak melebihi dan kurang daripada 12 patah perkataan'
            });
        }

    }

    function daftarwakil()
    {
        let nopelanggan = $('#nopelangganwakil').val();
        let nowakil = $('#nowakil').val();
        let nama = $('#namawakil').val();
        let hubungan = $('#slthubungan').val();
        let alamat = $('#alamatwakil').val();
        let telefon = $('#notelwakil').val();
        let nota = $('#notawakil').val();
        let nokp = $('#nokpwakil').val();


        $.ajax({
            method:'POST',
            url: "{{ route('wakil.create') }}",
            data:{
                "_token": "{{ csrf_token() }}",
                "nopelanggan" : nopelanggan,
                "nowakil" : nowakil,
                "nama" : nama,
                "hubungan" : hubungan,
                "alamat" : alamat,
                "telefon" : telefon,
                "nota" : nota,
                "icno" : nokp
                },
            success:function(data){

                if(data == 1)
                {
                    $('#WakilModal').hide();
                    $('#WakilModal').modal('hide');
                    nw = nowakil;
                    Swal.fire({
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonText: '<i class="fa fa-thumbs-up"></i> OK!!',
                        icon: 'success',
                        title: 'Berjaya Mendaftar Wakil Pelanggan!'
                    }).then(function(){
                        $('#wakiltxt').prop( "disabled", true );
                        $('#caribtn').html("Ubah");
                        $('#caribtn').attr("onclick","ubahwakil(this)");


                    });
                }

            },error: function (request, status, error) {
                console.log(request.responseText);
            }
        });
    }

    function daftarfunction(id)
    {
        $('#nokpwakil').val(id);

        $.ajax({
            method:'GET',
            url: "{{ route('wakil.caricustomer') }}",
            data:{ "icno" : id },
            success:function(data){

                $('#WakilModal').modal();
                $('#namawakil').val('');
                $('#alamatwakil').val(data['']);
                $('#notelwakil').val(data['']);

                //get first wakil
                $.ajax({
                    method:'GET',
                    url: "{{ route('wakil.first') }}",
                    success:function(getfirstwakil)
                    {
                        let firstwakil = parseInt(getfirstwakil);

                        $('#nowakil').val(firstwakil+1);
                    }
                });

                if(data != 'no-data')
                {
                    $('#namawakil').val(data['nama']);
                    $('#alamatwakil').val(data['alamat1']);
                    $('#notelwakil').val(data['telefon']);
                    $('#nopelangganwakil').val(data['nopelanggan']);
                }


            },error: function (request, status, error) {
                console.log(request.responseText);
            }

        });
    }

function ubahwakil(e)
{
    $('#wakiltxt').prop( "disabled", false);
    $(e).html("Cari");
    $(e).attr( "onclick", "wakilfunction(this)");
}


 // Restricts input for the set of matched elements to the given inputFilter function.
 (function($) {
    $.fn.inputFilter = function(inputFilter) {
      return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
        if (inputFilter(this.value)) {
          this.oldValue = this.value;
          this.oldSelectionStart = this.selectionStart;
          this.oldSelectionEnd = this.selectionEnd;
        } else if (this.hasOwnProperty("oldValue")) {
          this.value = this.oldValue;
          this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
        } else {
          this.value = "";
        }
      });
    };
  }(jQuery));


</script>
@endsection