@extends('layouts.app')



@section('content')
@include('modal.editmarhun')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 col-lg-12">
            <h3 class="text-center text-uppercase">Pembiayaan</h3>
            <div class="form-group row col-12">
                <input type="hidden" name="kodcaw" id="kodcaw" value="{{$cawangan_info['kodcaw']}}">
                <input type="hidden" name="nokp" id="nokp" value="{{ $customer_info['kpbaru'] }}">
                <div class="col-md-4">
                    <div class="form-group row">
                        <div class="col-md-4">
                            No Rujukan
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="norujukan" id="norujukan" readonly value="{{ $norujukan }}">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-12 text-right mb-2">
                <button type="button" style="margin:auto" class="btn btn-primary" data-toggle="modal" data-target="#daftar_marhun">Daftar Marhun</button>
            </div>
            <div class="card">
                <div class="card-body">
                    <table class="table table-striped table-hover text-center" id="myTable">
                        <thead class="thead-dark">
                            <tr>
                                <th>Bil</th>
                                <th>Recno</th>
                                <th>Marhun</th>
                                <th>Nilai Marhun</th>
                                <th>Karat</th>
                                <th>Berat</th>
                                <th>Kuantiti</th>
                                <th>Nota</th>
                                <th>Harga</th>
                                <th>Batu Permata</th>
                                <th>Berat Permata</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tfoot class="thead-dark">
                            <th colspan="3" class="text-center">Jumlah</th>
                            <th id="totalnilaimarhuntable"></th>
                            <th></th>
                            <th id="totalberattable"></th>
                            <th id="totalkuantititable"></th>
                            <th colspan="5"></th>
                        </tfoot>
                    </table>
                </div>
            </div>
            <div class="card">
                <div class="card-body">
                    <form name="gadaistore" action="{{ route('gadai.editstore') }}" method='post' onsubmit="verifyGadai(this)">
                    {{-- <!-- <form action="{{ route('gadai.store') }}" method='post'> --> --}}
                        @csrf
                        <div class="col-12 form-group row">
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <div class="col-5">
                                        Pembiayaan Max
                                    </div>
                                    <div class="col-7 input-group">
                                        <input type="text" style="height:50px !important" class="form-control" readonly name="pembiayaan_max_teller" id="pembiayaan_max_teller">
                                        <div class="input-group-append">
                                            <span class="input-group-text span-pinjaman-max"></span>
                                        </div>
                                    </div>
                                </diV>
                            </div>
                            @php

                                $kadarupah = Http::get(config('api.url'). '/api/kadarujrah',[
                                    'nilaimarhun' => $gadaiannorujukan['nilaimarhun'],
                                    'kodcaw' => $gadaiannorujukan['kodcaw']
                                ])->json();
                                
                                function getRoundedMethod(float $number = 0.0) : Float{
                                    $number_string = number_format(floor($number * 100)/100,2);

                                    $rounded = substr($number_string, 0, -1);
                                    $lastDigit = substr($number_string, -1);

                                    if ($lastDigit >= 0 && $lastDigit <= 2) {
                                        if(strpos($rounded,',')){
                                            $rounded = str_replace(',','',$rounded);
                                        }
                                        return $rounded;
                                    } elseif ($lastDigit >= 3 && $lastDigit <= 7) {
                                        $rounded = $rounded . '5';
                                        if(strpos($rounded,',')){
                                            $rounded = str_replace(',','',$rounded);
                                        }
                                        return $rounded;
                                    } else {
                                        return round($number,PHP_ROUND_HALF_UP);
                                    }
                                }

                                $array_keuntungan = Http::post(config('api.url'). '/api/onepercent',[
                                    'nilaimarhun' => $gadaiannorujukan['nilaimarhun'],
                                    'pembiayaan' => $gadaiannorujukan['pinjaman'],
                                    'kadarujrah' => $kadarupah,
                                    'margin' => $gadaiannorujukan['percentpinj'],
                                    'kodcaw' => $gadaiannorujukan['kodcaw']
                                ]);

                                $keuntungan_sebulan = getRoundedMethod($array_keuntungan['keuntungan']);
                                $keuntungan_6bln = getRoundedMethod($keuntungan_sebulan * 6);
                                $ujrah = getRoundedMethod($array_keuntungan['ujrah']);
                                $onepercent = getRoundedMethod($array_keuntungan['onepercent']);
                            
                            @endphp 
                            <div class="col-3">
                                <div class="form-group row">
                                    <div class="col-md-6">
                                        Keuntungan Sebulan
                                    </div>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" readonly name="keuntungan_sebulan" id="keuntungan_sebulan" value="{{ number_format((float)$keuntungan_sebulan,2) }}">
                                    </div>
                                </diV>
                            </div>
                            {{-- <div class="col-5">
                                <div class="form-group row">
                                </diV>
                            </div> --}}
                            <div class="col-3">
                                <div class="form-group row">
                                    <div class="col-md-6">
                                        Lain-Lain Caj
                                    </div>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" readonly name="ujrah" id="ujrah" value="{{ number_format((float)$ujrah,2)}}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group row">
                                    <div class="col-5">
                                        Pembiayaan
                                    </div>
                                    <div class="col-7 input-group">
                                        <input type="text" class="form-control" name="pinjaman" value="{{ $gadaiannorujukan['pinjaman'] }}" id="pinjaman">
                                        <div class="input-group-append">
                                            <span class="input-group-text span-pinjaman"></span>
                                        </div>
                                    </div>
                                </diV>
                            </div>
                            <div class="col-3">
                                <div class="form-group row">
                                    <div class="col-md-6">
                                        Keuntungan 6 Bulan
                                    </div>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" readonly name="keuntungan_6bln" id="keuntungan_6bln" value="{{ number_format((float)$keuntungan_6bln,2) }}">
                                    </div>
                                </diV>
                            </div>
                            <div class="col-3">
                                <div class="form-group row">
                                    <div class="col-md-6">
                                        Keuntungan
                                    </div>
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" readonly name="onepercent" id="onepercent" value="{{ number_format((float)$onepercent,2)}}">
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="form-group row">
                                    <div class="col-md-5">
                                        Pembiayaan Max Pelulus
                                    </div>
                                    <div class="col-md-7 input-group">
                                        <input type="text" class="form-control" readonly name="pembiyaan_max_pelulus" id="pembiyaan_max_pelulus">
                                        <div class="input-group-append">
                                            <span class="input-group-text span-pinjaman-max-pelulus"></span>
                                        </div>
                                    </div>
                                </diV>
                            </div>
                            <div class="col-12">
                                <input type="text" name="norujukan_gadai" id="norujukan_gadai" value="{{ $norujukan }}" hidden>
                                <input type="text" name="marhun_detail" id="marhun_detail" value="" hidden>
                                <input type="text" name="total_berat" id="total_berat" value="" hidden>
                                <input type="text" name="kadarkeuntungan" id="kadarkeuntungan" value="" hidden>
                                <input type="text" name="kuantiti_marhun" id="kuantiti_marhun" value="" hidden>
                                <input type="text" name="total_nilai_marhun" id="total_nilai_marhun" value="" hidden>
                                <a href="{{ route('customer_info') }}" class="float-right btn btn-danger mr-2">Batal</a>
                                {{-- <a href="{{ route('gadai.batalmarhun',['norujukan'=>$norujukan]) }}" class="float-right btn btn-danger mr-2">Batal</a> --}}
                                <input type="submit" name="terima_gadai" id="terima_gadai" class="float-right btn btn-primary mr-2" value="Terima">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <!-- modal daftar marhun-->
            <div class="modal fade" id="daftar_marhun" tabindex="-1" data-backdrop="static"  aria-labelledby="ModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="ModalLabel">Daftar Marhun</h5>
                        </div>
                        <div class="modal-body">
                            <form action="" id="maklumat_marhun" method="post">
                                <div class="row justify-content-center">
                                    <div class="col-md-6">
                                        <div class="form-group row">
                                            <input type="hidden" name="kodcaw" id="kodcaw" value="">
                                            <div class="col-md-4">No Rujukan</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="norujukan_marhun" id="norujukan_marhun" value="{{ $norujukan }}"></div>
                                            <div class="col-md-4">Marhun</div>
                                            <div class="col-md-8">
                                                <select class="form-control" name="marhun" id="marhun">
                                                    <option disabled selected value> -- Pilih Jenis Marhun -- </option>
                                                </select>
                                            </div>
                                            <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Nota</label>
                                                <select name="nota" id="nota" class="select2 form-control" multiple="multiple" data-placeholder="Nota Tambahan" style="width: 100%;">
                                                    <option>Rosak</option>
                                                    <option>Putus</option>
                                                    <option>Patah</option>
                                                    <option>Sebelah</option>
                                                </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">Kuantiti</div>
                                            <div class="col-md-8">
                                                <input class="form-control" name="kuantiti" id="kuantiti" type="text" pattern="\d*" maxlength="2" disabled>
                                            </div>

                                            <div class="col-md-4">Karat</div>
                                            <div class="col-md-8">
                                                <select class="form-control" name="karat" id="karat">
                                                    <option disabled selected value> -- Pilih Karat -- </option>
                                                </select>
                                            </div>
                                            <div class="col-md-4">Berat Bersih</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="berat_emas" id="berat_emas"></div>
                                            <div class="col-md-4">Harga</div>
                                            <div class="col-md-8"><input class="form-control .harga" type="text" name="harga" id="harga" readonly></div>
                                            <div class="col-md-4">Nilai Marhun</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="nilai_marhun" id="nilai_marhun" readonly></div>
                                            <div class="col-md-4">Bilangan Marhun</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="bilangan_marhun" id="bilangan_marhun" readonly></div>
                                            <div class="col-md-4">Jumlah Kuantiti</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="bilangan_jumlah_kuantiti" id="bilangan_jumlah_kuantiti" readonly></div>
                                            <div class="col-md-4">Jumlah Nilai Marhun</div>
                                            <div class="col-md-8"><input class="form-control" type="text" name="jumlah_nilai_marhun" id="jumlah_nilai_marhun" readonly></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6" id="col_right" style="display: none">
                                        <div class="form-group row">
                                            <div class="col-md-12">
                                                <div class="form-group">
                                                    <div class="d-flex justify-content-between">
                                                        <span>Ada Batu Permata?</span>
                                                        <div>
                                                            <label for="tagpermata">Ya</label>
                                                            <input type="checkbox" id="tagpermata" name="tagpermata">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex" id="divanggaran" style="visibility: hidden">
                                                <div class="col-8">Anggaran Berat Permata</div>
                                                <div class="col-4"><input class="form-control" type="text" name="beratpermata" id="beratpermata" autocomplete="off"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                        <div class="modal-footer">
                            <div class="form-group row">
                                <input class="btn btn-primary mr-2" type="button" name="tambah_marhun" id="tambah_marhun" value="Tambah">
                                <input class="btn btn-primary mr-2" type="button" name="terima_marhun" id="terima_marhun" value="Terima">
                                <button type="button" class="btn btn-danger" name="batal_marhun" id="batal_marhun">Batal</button>
                            </div>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="{{ asset('js/rounded-methods.js') }}"></script>
<script>
    var api_url = "<?php echo $api_url ?>";
    var kodcaw_ujrah = "<?php echo $cawangan_info['kodcaw'] ?>";

    $('form input').keydown(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });
    function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
    $(document).ready( function () {
        $.ajax({
            method: 'get',
            url: api_url + '/api/marhun/' + "{{ $norujukan }}",
            success:function(data){
                let count = 0;
                let jumlah = 0;
                $.each(data,function(index,marhun){
                    $.each(marhun,function(index,mar){
                        jumlah += Number(mar['n_marhun']);
                        count++;
                    })
                })
                $('#bilangan_marhun').val(count);
                $('#jumlah_nilai_marhun').val(formatter.format(jumlah));
            }
        });

        $(document).on("keydown", disableF5);
        var norujukan = $('#norujukan').val();
        getMarhun(norujukan);

        $.ajax({
            method:'GET',
            url: api_url + '/api/jemas',
            success:function(data){
                $.each(data,function(index,jemas){
                    $("#marhun").append(new Option(jemas['descpt'], jemas['marhun']));
                })
            }
        });

        $.ajax({
            method:'GET',
            url: api_url + '/api/harga_emas',
            success:function(data){
                $.each(data,function(index,harga_emas){
                    var text = harga_emas['karat']+' - '+harga_emas['keterangan'];
                    $("#karat").append(new Option(text, harga_emas['karat']));
                })
            }
        });
    });

    function getMarhun(norujukan){
        $.ajax({
            method:'GET',
            url: api_url + '/api/marhun/'+norujukan,
            success:function(data){
                marhuntable(data);
            }
        });
    }

    let arrayBatuPermata = [
        'DNR',
        'SYE',
        'WFR',
        'G/B',
    ];

    $('#marhun').change(function(){
        var marhun = this.value;

        if (!arrayBatuPermata.includes(marhun)) {
            $("#col_right").css("display", "block");
        } else {
            $("#col_right").css("display", "none");
            $('#tagpermata').prop('checked', false);
            $("#divanggaran").css("visibility", "hidden");
            $('#beratpermata').val("");        
        }

        if(marhun == 'G/B' || marhun == 'WFR' || marhun == 'SYE' || marhun == 'DNR'){
            if(marhun == 'DNR' || marhun == 'SYE'){
                $('#sltkarat option').show();
                $('#sltkarat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }else{
                $('#sltkarat option').show();
                $('#sltkarat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }

            $('#text-berat').html('Berat Keseluruhan');
            $('#kuantiti_edit').attr('disabled', false);
        }else{
            $('#kuantiti_edit').val(1);
            $('#sltkarat option').show();
            $('#text-berat').html('Berat');
            $('#kuantiti_edit').attr('disabled', true);
        }
    });

    $('#tagpermata').change(function () {
        if($('#tagpermata').is(':checked')) {
            $("#divanggaran").css("visibility", "visible");
        } else {
            $("#divanggaran").css("visibility", "hidden");
            $('#beratpermata').val("");
        }
    });

    $('#tagpermataedit').change(function () {
        if($('#tagpermataedit').is(':checked')) {
            $(".div_anggaran_edit").css("display", "block");
        } else {
            $(".div_anggaran_edit").css("display", "none");
            $('#beratpermataedit').val("");
        }
    });
    
    $('#marhun_edit').change(function(){
        var marhun = this.value;
        
        if (!arrayBatuPermata.includes(marhun)) {
            $(".col_edit_permata").css("display", "block");
            $(".div_anggaran_edit").css("display", "none");
            $('#beratpermataedit').val("");
        } else {
            $(".col_edit_permata").css("display", "none");
            $('#tagpermataedit').prop('checked', false);
            $(".div_anggaran_edit").css("display", "none");
            $('#beratpermataedit').val("");
        }

        $('#kuantiti').val('');

        $('#karat').val('');
        if(marhun == 'G/B' || marhun == 'WFR' || marhun == 'SYE' || marhun == 'DNR'){
            if(marhun == 'DNR' || marhun == 'SYE'){
                $('#karat option').show();
                $('#karat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }else{
                $('#karat option').show();
                $('#karat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }

            $('#text-berat').html('Berat Keseluruhan');
            $('#kuantiti').attr('disabled', false);
        }else{
            $('#karat option').show();
            $('#text-berat').html('Berat');
            $('#kuantiti').attr('disabled', true);
        }
    });

    $('#karat').change(function(){
        var karat = this.value;
        karat = karat.replace(/\./g,'-');
        var berat = $('#berat_emas').val();
        getHargaEmas(karat,berat)
    });

    $('#berat_emas').on('input',function(){
        var berat = this.value;
        var karat = $('#karat').val();
        karat = karat.replace(/\./g,'-');
        getHargaEmas(karat,berat)
    })

    $('#batal_marhun').click(function(){
        
        $('#nota').val('').trigger("change");
        $('#tagpermata').prop("checked", false);
        $("#col_right").css("display", "none");
        $("#divanggaran").css("visibility", "hidden");
        $('#beratpermata').val("");
        $('#marhun').val(0);
        $('#karat').val(0);
        $('#berat_emas').val("");
        $('#harga').val("");
        $('#nilai_marhun').val("");
        $('#daftar_marhun').modal('hide');
    })

    function getHargaEmas(karat,berat){
        $.ajax({
            method:'GET',
            url: api_url + '/api/harga_emas/'+karat,
            success:function(data){

                var nilai_marhun = data['harga'] * berat;
                $('#harga').val(formatter.format(data['harga']));
              
                $('#nilai_marhun').val(formatter.format(nilai_marhun));
            },error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message);
                console.log(err.Message);
            }
        })
    }

    var tablemarhun = $('#myTable').DataTable({
        "ordering": false,
        "columnDefs": [
            {
                "targets": [ 1 ],
                "visible": false,
                "searchable": false
            },
            {
                "targets": [ 7 ],
                "visible": false,
                "searchable": false
            }
        ]
    });

    $(".select2").select2({
        dropdownParent: $('#daftar_marhun'),
        tags: true,
        tokenSeparators: [',', ' '],
        allowClear: true,
        closeOnSelect: false
    });

    $(".select2_daftar_batu_permata").select2({
        dropdownParent: $('#daftar_marhun'),
        tags: true,
        tokenSeparators: [',', ' '],
        allowClear: true,
        closeOnSelect: false
    });

    $(".select2_nota").select2({
        dropdownParent: $('#editMarhunModal'),
        tags: true,
        tokenSeparators: [',', ' '],
        allowClear: true,
        closeOnSelect: false
    });

    $('#nota_edit').select2({
        tags: true,
        placeholder: "Select or add options",
        width: 'resolve'
    });

    $(".select2_batupermata").select2({
        dropdownParent: $('#editMarhunModal'),
        tags: true,
        tokenSeparators: [',', ' '],
        allowClear: true,
        closeOnSelect: false
    });

    var total_nilai_marhun = 0;
    var total_berat = 0;
    var total_kuantiti = 0;
    var kadarupah = 0;
    var jumlah_marhun = 0;
    var jumlah_nilai_marhun = 0;
    var pinjaman_pelulus = 0;
    var pinjaman_teller = 0;
    function marhuntable(data){
        var counter = 1;
        var count = 0;
        total_nilai_marhun = 0;
        total_berat = 0;
        total_kuantiti = 0;
        var marhun_details = '';
        tablemarhun.clear().draw();
        $.each(data,function(index,marhun){
            $.each(marhun,function(index,marhun_detail){
                total_nilai_marhun = total_nilai_marhun + Number(marhun_detail['n_marhun']);
                total_berat = total_berat + Number(marhun_detail['berat']);
                marhun_details = marhun_details + marhun_detail['bil'] + " " + marhun_detail['marhun'] +",";
                jumlah_nilai_marhun += Number(marhun_detail['n_marhun']);
                status_tag_permata = marhun_detail['tag_permata'] == 1 ? 'Ada' : '';
                total_kuantiti += Number(marhun_detail['bil']);
                tablemarhun.row.add([
                    counter,
                    marhun_detail['recno'],
                    marhun_detail['marhun'],
                    formatter.format(marhun_detail['n_marhun']),
                    marhun_detail['karat'],
                    formatter.format(marhun_detail['berat']),
                    marhun_detail['bil'],
                    marhun_detail['nota'],
                    marhun_detail['harga'],
                    status_tag_permata,
                    marhun_detail['berat_batu_permata'],
                    "<div class='buttonpunya text-center'><button onclick='editmarhun(this)' class='btn btn-primary'><i class='fas fa-edit'></i></button> <button onclick='deletemarhun(this)' class='btn btn-danger'><i class='fas fa-trash-alt'></i></button></div>"
                ]).draw();
                count++;
                counter = counter + 1;
            });
        });
        $('#totalberattable').text(formatter.format(total_berat));
        $('#totalkuantititable').text(total_kuantiti);
        $('#totalnilaimarhuntable').text(formatter.format(jumlah_nilai_marhun));
        $('#bilangan_marhun').val(formatter.format(counter-1));
        $('#bilangan_jumlah_kuantiti').val(formatter.format(total_kuantiti));
        $('#jumlah_nilai_marhun').val(formatter.format(jumlah_nilai_marhun));
        if (count == 1){
            $('.buttonpunya').html("<button onclick='editmarhun(this)' class='btn btn-primary'><i class='fas fa-edit'></i></button>");
        }
        
        // if(total_nilai_marhun > 0 && total_nilai_marhun < 401){
        //     kadarupah = 1.2/100;
        // }else if(total_nilai_marhun >= 401 && total_nilai_marhun < 2001){
        //     kadarupah = 1.5/100;
        // }else if(total_nilai_marhun >= 2001 ){
        //     kadarupah = 1.7/100;
        // }

        $.ajax({
            method:'GET',
            url: api_url + '/api/kadarujrah',
            async:false,
            data:{
                'nilaimarhun' : total_nilai_marhun,
                'kodcaw' : kodcaw_ujrah
            },
            success:function(data){
                kadarupah = data;
            }
        });

        $('#total_nilai_marhun').val(formatter.format(total_nilai_marhun));
        $('#marhun_detail').val(marhun_details);
        $('#total_berat').val(formatter.format(total_berat));
        $('#kadarkeuntungan').val(formatter.format(kadarupah));
        $('#kuantiti_marhun').val(formatter.format(jumlah_marhun));
        
        let perpinjam = ($('#pinjaman').val()/total_nilai_marhun)*100;

        $.ajax({
            method:'POST',
            url: api_url + '/api/onepercent',
            async:false,
            data:{
                'nilaimarhun' : total_nilai_marhun,
                'pembiayaan' : parseFloat($('#pinjaman').val()),
                'kadarujrah' : kadarupah,
                'margin' : perpinjam,
                'kodcaw' : "{{ $cawangan_info['kodcaw'] }}"
            },
            success:function(data){
                array_keuntungan = data;
            }
        });

        let keuntungan_sebulan = getRoundedMethod(array_keuntungan['keuntungan']);
        let keuntungan_6bln = getRoundedMethod(keuntungan_sebulan * 6);   
        
        $('.span-pinjaman').text(formatter.format(perpinjam.toFixed(2)) + ' %');
        $('#keuntungan_sebulan').val(formatter.format(keuntungan_sebulan.toFixed(2)));
        $('#keuntungan_6bln').val(formatter.format(keuntungan_6bln.toFixed(2)));

        $.ajax({
            method:'GET',
            url: api_url + '/api/maxpinjaman',
            success:function(data){
                
                $.each(data,function(index,pinjaman){
                    if(pinjaman['user_type'] == 'teller'){
                        pinjaman_teller = Number(pinjaman['max']);
                    }
                    if(pinjaman['user_type'] == 'khazanah'){
                        pinjaman_pelulus = Number(pinjaman['max']);
                    }
                });
                $('.span-pinjaman-max-pelulus').text(formatter.format(pinjaman_pelulus) + ' %');
                $('.span-pinjaman-max').text(formatter.format(pinjaman_teller) + ' %');
                var max_teller = total_nilai_marhun * (pinjaman_teller/100);
                var max_pelulus = total_nilai_marhun * (pinjaman_pelulus/100);
                $('#pembiayaan_max_teller').val(formatter.format(max_teller));
                $('#pembiyaan_max_pelulus').val(formatter.format(max_pelulus.toFixed(2)));
            }
        });
    }

    function deletemarhun(e){
        let marhun = $(e).closest('tr').children('td:eq(1)').text();let selectedrow = $(e).closest('tr');let recnozz = tablemarhun.row(selectedrow).data();
        let norujuk = $('#norujukan').val();

        $.ajax({
            method: 'put',
            url: '{{ route("gadai.editmarhun") }}',
            data: {
                "_token": "{{ csrf_token() }}",
                "norujukan" : norujuk,
                "recno" : recnozz[1],
                "teller": "{{ Auth::user()->name }}"
            },
            success:function(data){
                location.reload();
            },error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(xhr.responseText);
            }
        });
    }

    function editmarhun(e){
        let norujuk = $('#norujukan').val();
        let selectedrow = $(e).closest('tr');
        let recno = tablemarhun.row(selectedrow).data();
        let nm = recno[3];
        let karat = recno[4];
        let berat = recno[5];
        let harga = recno[8];
        let nota = recno[7];
        let tag_permata_edit = recno[8];
        let beratpermata = recno[10];
        let kuantiti = recno[6];
        let jenismarhun = recno[2];
        var res = nota.split(",");

        // if(jenismarhun == 'G/B' || jenismarhun == 'WFR' || jenismarhun == 'SYE' || jenismarhun == 'DNR'){
        //     $('#kuantiti_modal').attr('disabled', false);
        //     $(".div_kuantiti_edit").css("display", "block");
        //     $(".div_column_kuantiti_edit").css("display", "block");
        //     $('#kuantiti_edit').val(kuantiti);
        // }else{
        //     $('#kuantiti_modal').attr('disabled', false);
        //     $(".div_kuantiti_edit").css("display", "none");
        //     $(".div_column_kuantiti_edit").css("display", "none");
        //     $('#kuantiti_edit').val(1);
        // }

        if (!arrayBatuPermata.includes(jenismarhun)) {
            $(".col_edit_permata").css("display", "block");
            if(beratpermata != null) {
                $('#tagpermataedit').prop('checked', true);
                $(".div_anggaran_edit").css("display", "block");
                $('#beratpermataedit').val(beratpermata);
            } else {
                $('#tagpermataedit').prop('checked', false);
                $(".div_anggaran_edit").css("display", "none");
                $('#beratpermataedit').val("");       
            }
        } else {
            $(".col_edit_permata").css("display", "none");
            $('#tagpermataedit').prop('checked', false);
            $(".div_anggaran_edit").css("display", "none");
            $('#beratpermataedit').val("");        
        }

        $.ajax({
            method:'GET',
            url: api_url + '/api/jemas',
            async:false,
            success:function(data){
                $.each(data,function(index,jemas){
                    $("#marhun_edit").append(new Option(jemas['descpt'], jemas['marhun']));
                    
                    res.forEach(function(value) {
                        if ($('#nota_edit').find("option[value='" + value + "']").length === 0) {
                            let newOption = new Option(value, value, true, true);
                            $('#nota_edit').append(newOption).trigger('change');
                        }
                    });
                    $('#nota_edit').val(res).trigger('change');

                    $('#kuantiti_edit').val(kuantiti);

                    $('#sltkarat').val(karat);
                    $('#marhun_edit').val(jenismarhun);
                    $('#berat_edit').val(berat);
                    $('#nilaimarhun_edit').val(nm);
                    $('#harga_edit').val(harga);
                    $('#norujukedit').val(norujuk);
                    $('#recnoedit').val(recno[1]);
                    $('#editMarhunModal').modal();
                })
            }
        });

        
    }

    $("#marhun_edit").change(function(e){
        
        var marh = $(this).find(':selected').val();
        $('#kuantiti_modal').val('');

        if(marh == 'G/B' || marh == 'WFR' || marh == 'SYE' || marh == 'DNR'){
            if(marh == 'DNR' || marh == 'SYE'){
                $('#sltkarat option').show();
                console.log('test');
                $('#sltkarat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }else{
                $('#sltkarat option').show();
                $('#sltkarat option').not('[value="21.0K"]').not('[value="22.0K"]').not('[value="23.0K"]').not('[value="24.0K"]').not('[value="24.0Kgb"]').not(':first').hide();
            }
            $('#text_berat_modal').html('Berat Keseluruhan');
            $('#kuantiti_modal').attr('disabled', false);
        }else{
            $('#text_berat_modal').html('Berat');
            $('#kuantiti_modal').attr('disabled', true);
        }
    });

    $("#sltkarat").change(function(e){
        let hargaref = $(this).find(':selected').data('harga');
        let ber = parseFloat($('#berat_edit').val());
        let total = ber * hargaref;
        $('#nilaimarhun_edit').val(formatter.format(total));
        $('#harga_edit').val(hargaref);
    });

    function calculationharga(e){
        let berat = $(e).val();
        let total = 0;
        let harga = $('#harga_edit').val();

        total = berat * harga;

        $('#nilaimarhun_edit').val(formatter.format(total));
    }

    $('#terima_edit').on('click',function(){
        var nota_edit = $('#nota_edit').val();
        var tagpermata_edit = $('input[id=tagpermataedit]').is(':checked') ? 1 : 0;
        var beratpermata_edit = $('#beratpermataedit').val();
        var norujukedit = $('#norujukedit').val();
        var recnoedit = $('#recnoedit').val();
        var marhun_edit = $('#marhun_edit').val();
        var sltkarat = $('#sltkarat').val();
        var berat_edit = $('#berat_edit').val();
        var harga_edit = $('#harga_edit').val();
        var nilaimarhun_edit = $('#nilaimarhun_edit').val();
        var nilai_marhun_edit = Number(nilaimarhun_edit.replace(/[^0-9.-]+/g,""));
        var kuantiti = $('#kuantiti_edit').val();

        if(nota_edit != null){
            var nota = nota_edit.toString();
        }else{
            var nota = '';
        }

        if(kuantiti > 10)
        {
            Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Kuantiti tidak boleh melebihi 10'
            });

            event.preventDefault();
            return false;
        }

        var resultValidation = validateBatuPermata(tagpermata_edit, beratpermata_edit);
        if(resultValidation == false) {
            return false;
        }

        if($.isNumeric(berat_edit) == false){
            Swal.fire({
                icon: 'error',
                title: 'Amaran!',
                text: 'Sila Masukkan Berat Marhun'
            });
            event.preventDefault();
            return false;
        }else{
            $.ajax({
                method:'put',
                url: api_url + '/api/gadai/ubah/marhun/' + "{{ $cawangan_info['kodcaw'] }}" + '/' + norujukedit,
                datatype:'json',
                data:{
                    'recno' : recnoedit,
                    'karat' : sltkarat,
                    'berat' : berat_edit,
                    'harga' : harga_edit,
                    'n_marhun' : nilai_marhun_edit,
                    'marhun' : marhun_edit,
                    // 'nota' : nota,
                    'tag_permata' : tagpermata_edit,
                    'berat_batu_permata' : beratpermata_edit,
                    "teller": "{{ Auth::user()->name }}",
                    "kuantiti" : (kuantiti) ? kuantiti : 1
                },
                success:function(data){
                    getMarhun(norujukedit);
                    $('#editMarhunModal').modal('hide');
                }
            })
        }
        
    });

    $('#pinjaman').on('input',function(){
        var pinjaman = Number(this.value);
        var nilaimarhun = Number($('#jumlah_nilai_marhun').val());
        let perpinjam = ($('#pinjaman').val()/total_nilai_marhun)*100;
        let array_keuntungan = [];

        if(this.value)
        $.ajax({
            method:'POST',
            url: api_url + '/api/onepercent',
            async:false,
            data:{
                'nilaimarhun' : total_nilai_marhun,
                'pembiayaan' : parseFloat($('#pinjaman').val()),
                'kadarujrah' : kadarupah,
                'margin' : perpinjam,
                'kodcaw' : "{{ $cawangan_info['kodcaw'] }}"
            },
            success:function(data){
                array_keuntungan = data;
            }
        });


        var keuntungan_sebulan = (array_keuntungan['keuntungan']) ? getRoundedMethod(array_keuntungan['keuntungan']) : 0;
        var keuntungan_6bln = getRoundedMethod(keuntungan_sebulan * 6);

        percent_pinjaman = (Number(pinjaman)/Number(total_nilai_marhun))*100;

        $('.span-pinjaman').text(formatter.format(percent_pinjaman.toFixed(2)) + ' %');
        $('#keuntungan_sebulan').val(formatter.format(keuntungan_sebulan.toFixed(2)));
        $('#keuntungan_6bln').val(formatter.format(keuntungan_6bln.toFixed(2)));
        $('#ujrah').val(formatter.format(getRoundedMethod(array_keuntungan['ujrah']).toFixed(2)));
        $('#onepercent').val(formatter.format(getRoundedMethod(array_keuntungan['onepercent']).toFixed(2)));
    });

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

    $('#terima_marhun').click(function(){
        var kodcaw = $('#kodcaw').val();
        var norujukan = $('#norujukan').val();
        var marhun = $('#marhun').val();
        var karat = $('#karat').val();
        var berat_emas = $('#berat_emas').val();
        var harga = $('#harga').val();
        var nilaimarhun = $('#nilai_marhun').val();
        var bilangan_marhun_daftar = Number($('#bilangan_marhun').val());
        var nilai_marhun = Number(nilaimarhun.replace(/[^0-9.-]+/g,""));
        var nota_array = $('#nota').val();
        var berat_permata = $('#beratpermata').val();
        var tag_permata = $('input[id=tagpermata]').is(':checked') ? 1 : 0;
        var kuantiti = $('#kuantiti').val();
        
        if(kuantiti > 10)
        {
            $("#tambah_marhun").prop('disabled', false);
            $("#terima_marhun").prop('disabled', false);

            Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Kuantiti tidak boleh melebihi 10'
            });

            event.preventDefault();
            return false;
        }

        if(nota_array != null){
            var nota = nota_array.toString();
        }else{
            var nota = '';
        }

        if(marhun == null && karat == null && berat_emas == ''){
            $('#daftar_marhun').modal('hide');
        }
        else{
            if(marhun == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Pilih Marhun'
                });
                event.preventDefault();
                return false;
            }else{
                if(karat == null){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran!',
                        text: 'Sila Pilih Karat'
                    });
                    event.preventDefault();
                    return false;
                }else{
                    if($.isNumeric(berat_emas) == false){
                        Swal.fire({
                            icon: 'error',
                            title: 'Amaran!',
                            text: 'Sila Masukkan Berat Marhun'
                        });
                        event.preventDefault();
                        return false;
                    }else{
                        var resultValidation = validateBatuPermata(tag_permata, berat_permata);
                        if(resultValidation == false) {
                            return false;
                        }

                        if(bilangan_marhun_daftar<10){
                            $.ajax({
                                method:'POST',
                                url: api_url + '/api/marhun/'+kodcaw,
                                dataType:'json',
                                data: {
                                    'norujukan': norujukan,
                                    'marhun' : marhun,
                                    'nota':nota,
                                    'tag_permata':tag_permata,
                                    'berat_batu_permata':berat_permata,
                                    'karat' : karat,
                                    'berat_emas' :berat_emas,
                                    'harga' : harga,
                                    'nilai_marhun' : nilai_marhun,
                                    'teller' : "{{ Auth::user()->name }}",
                                    'kuantiti' : (kuantiti) ? kuantiti : 1
                                },
                                success:function(data){
                                    $('#nota').val('').trigger("change");
                                    $('#beratpermata').val("");
                                    $('#marhun').val(0);
                                    $('#karat').val(0);
                                    $('#berat_emas').val("");
                                    $('#harga').val("");
                                    $('#nilai_marhun').val("");
                                    $('#daftar_marhun').modal('hide');
                                    $("#col_right").css("display", "none");
                                    $('#tagpermata').prop('checked', false);
                                    $('#beratpermata').val("");
                                    $("#divanggaran").css("visibility", "hidden");

                                    $('#kuantiti').val("");
                                    $('#kuantiti').attr('disabled', true);

                                    jumlah_marhun += 1;
                                    jumlah_nilai_marhun += Number(nilai_marhun);
                                    $('#bilangan_marhun').val(formatter.format(jumlah_marhun));
                                    $('#jumlah_nilai_marhun').val(formatter.format(jumlah_nilai_marhun));
                                    getMarhun(norujukan);
                                },
                                error: function(xhRequest, ErrorText, thrownError){
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Amaran!',
                                        text: 'Tambah Marhun Tidak Berjaya'
                                    });
                                    console.log(xhRequest);
                                }
                            });
                        }else{
                            Swal.fire({
                                icon: 'error',
                                title: 'Amaran!',
                                text: 'Hanya 10 Marhun dibenarkan dalam 1 SAG'
                            });
                            $('#daftar_marhun').modal('hide');
                        }   
                    }
                }
            }
        }
    });

    $('#tambah_marhun').click(function(){
        var kodcaw = $('#kodcaw').val();
        var norujukan = $('#norujukan').val();
        var marhun = $('#marhun').val();
        var karat = $('#karat').val();
        var berat_emas = $('#berat_emas').val();
        var harga = $('#harga').val();
        var nilaimarhun = $('#nilai_marhun').val();
        var bilangan_marhun_daftar = Number($('#bilangan_marhun').val());
        var nilai_marhun = Number(nilaimarhun.replace(/[^0-9.-]+/g,""));
        var nota_array = $('#nota').val();
        var beratpermata = $('#beratpermata').val();
        var tag_permata = $('input[id=tagpermata]').is(':checked') ? 1 : 0;
        var kuantiti = $('#kuantiti').val();

        if(kuantiti > 10)
        {
            $("#tambah_marhun").prop('disabled', false);
            $("#terima_marhun").prop('disabled', false);

            Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Kuantiti tidak boleh melebihi 10'
            });

            event.preventDefault();
            return false;
}

        if(nota_array != null){
            var nota = nota_array.toString();
        }else{
            var nota = '';
        }

        if(marhun == null){
            Swal.fire({
                icon: 'error',
                title: 'Amaran!',
                text: 'Sila Pilih Marhun'
            });
            event.preventDefault();
            return false;
        }else{
            if(karat == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Pilih Karat'
                });
                event.preventDefault();
                return false;
            }else{
                if($.isNumeric(berat_emas) == false){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran!',
                        text: 'Sila Masukkan Berat Marhun'
                    });
                    event.preventDefault();
                    return false;
                }else{
                    var resultValidation = validateBatuPermata(tag_permata, beratpermata);
                    if(resultValidation == false) {
                        return false;
                    }

                    if(bilangan_marhun_daftar < 10){
                        $.ajax({
                            method:'POST',
                            url: api_url + '/api/marhun/'+kodcaw,
                            dataType:'json',
                            data: {
                                'norujukan': norujukan,
                                'marhun' : marhun,
                                'nota':nota,
                                'tag_permata':tag_permata,
                                'berat_batu_permata':beratpermata,
                                'karat' : karat,
                                'berat_emas' :berat_emas,
                                'harga' : harga,
                                'nilai_marhun' : nilai_marhun,
                                'teller' : "{{ Auth::user()->name }}",
                                'kuantiti' : (kuantiti) ? kuantiti : 1
                            },
                            success:function(data){
                                $('#nota').val('').trigger("change");
                                $('#batupermata').val('').trigger("change");
                                $('#beratpermata').val("");
                                $('#marhun').val(0);
                                $('#karat').val(0);
                                $('#berat_emas').val("");
                                $('#harga').val("");
                                $('#nilai_marhun').val("");
                                $("#col_right").css("display", "none");
                                $('#tagpermata').prop('checked', false);
                                $('#beratpermata').val("");
                                $("#divanggaran").css("visibility", "hidden");  
                                $('#kuantiti').val("");
                                $('#kuantiti').attr('disabled', true);

                                jumlah_marhun += 1;
                                jumlah_nilai_marhun += Number(nilai_marhun);
                                $('#bilangan_marhun').val(formatter.format(jumlah_marhun));
                                $('#jumlah_nilai_marhun').val(formatter.format(jumlah_nilai_marhun));
                                getMarhun(norujukan);
                            },
                            error: function(xhRequest, ErrorText, thrownError){
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Amaran!',
                                    text: 'Tambah Marhun Tidak Berjaya'
                                });
                                console.log(xhRequest);
                            }
                        });
                    }else{
                        Swal.fire({
                            icon: 'error',
                            title: 'Amaran!',
                            text: 'Hanya 10 Marhun dibenarkan dalam 1 SAG'
                        });
                    }
                }
            }
        }
    });

    function validateBatuPermata(tag, berat) {
        function countDecimalPlaces(value) {
            const match = value.match(/(?:\.(\d+))?$/);
            if (!match || !match[1]) {
                return 0;
            }
            return match[1].length;
        }

        function validateInput(inputValue) {
            const decimalPlaces = countDecimalPlaces(inputValue);
            return decimalPlaces <= 2;
        }

        if(tag == 1) {
            if(berat == '') {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Isi Anggaran Berat Permata'
                });
                event.preventDefault();
                return false;
            } else if($.isNumeric(berat) == false) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Semak Semula Berat Permata'
                });
                event.preventDefault();
                return false;
            } else if(berat <= 0) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Nilai berat permata mesti lebih besar daripada ' + berat,
                });
                event.preventDefault();
                return false;
            } else if(!validateInput(berat)) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Hanya 2 titik perpuluhan dibenarkan untuk berat batu permata'
                });
                event.preventDefault();
                return false;
            }else {
                return true;
            }
        } else if(berat != '') {
            if($.isNumeric(berat) == false) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Semak Semula Berat Permata'
                });
                event.preventDefault();
                return false;
            }

            if(berat <= 0) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Nilai berat permata ' + berat + ' tidak dibenarkan'
                });
                event.preventDefault();
                return false;
            }

            if(!validateInput(berat)) {
                $("#tambah_marhun").prop('disabled', false);
                $("#terima_marhun").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Hanya 2 titik perpuluhan dibenarkan untuk berat batu permata'
                });
                event.preventDefault();
                return false;
            }
        } else {
            return true;
        }
    }

    function verifyGadai(func){
        $("#terima_gadai").prop('disabled', true);
        var kodcaw = $('#kodcaw').val();
        var nokp = $('#nokp').val();
        var nopelanggan = $('#nopelanggan').val();
        var norujukan = $('#norujukan').val();
        var pinjaman = Number($('#pinjaman').val());
        var total_nilai_marhun = $('#total_nilai_marhun').val();
        var nilai_marhun_total = Number(total_nilai_marhun.replace(/[^0-9.-]+/g,""));
        var pinjaman_asal = "{{ $gadaiannorujukan['pinjaman']}}";

        var pembiayaan_max_teller = $('#pembiayaan_max_teller').val();
        var pembiayaan_max_teller = Number(pembiayaan_max_teller.replace(/[^0-9.-]+/g,""));
        var pembiyaan_max_pelulus = $('#pembiyaan_max_pelulus').val();
        var pembiyaan_max_pelulus = Number(pembiyaan_max_pelulus.replace(/[^0-9.-]+/g,""));
        var min_pinjaman = nilai_marhun_total * 0.10;
        var max_pinjaman = pembiyaan_max_pelulus;

        let teller = "{{ Auth::user()->name }}";
        let bakiakhir = 0;
        var kodcaw = $('#kodcaw').val();

        $.ajax({
            method: 'get',
            url: api_url + '/api/GetCurrentTunai/' + kodcaw,
            async: false,
            dataType:'json',
            data:{
                'kodlaluan': teller
            },
            success:function(data){
                bakiakhir = data.baki + pinjaman_asal;
            }
        });

        if(bakiakhir < pinjaman){
            $("#terima_gadai").prop('disabled', false);
            Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Baki Akhir Tunai Lebih Rendah Daripada Nilai Marhun Yang Ingin Digadaikan. Sila Tambah Pendahuluan di Laman Aliran Tunai Segera. '
            });

            event.preventDefault();
            return false;
        }else{

            if($.isNumeric(pinjaman) == false){
            $("#terima_gadai").prop('disabled', false);
            Swal.fire({
                icon: 'error',
                title: 'Amaran!',
                text: 'Sila Masukkan Nombor Sahaja'
            });
            event.preventDefault();
            return false;
            }
            if(pinjaman < min_pinjaman){
                $("#terima_gadai").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Sila Masukan Pembiayaan, Minimal Pembiayaan ialah RM '+ formatter.format(min_pinjaman)
                });
                event.preventDefault();
                return false;
            }
            else if(pinjaman > max_pinjaman){
                $("#terima_gadai").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran!',
                    text: 'Pinjaman Melebihi Margin Yang Dibenarkan'
                });
                event.preventDefault();
                return false;
            }
            else{
                if(pinjaman >=10000 && pinjaman <= Number(pembiyaan_max_pelulus)){
                    const swalWithBootstrapButtons = Swal.mixin({
                        customClass: {
                            confirmButton: 'btn btn-success',
                            cancelButton: 'btn btn-danger'
                        },
                        buttonsStyling: false
                    })

                    if(pinjaman > Number(pembiyaan_max_pelulus)+10){
                        var errortext = "Tetapan margin melebihi 75% untuk Operasi!";
                    }
                    if(pinjaman >= 10000){
                        var errortext = "Pinjaman Melebihi 10,000";
                    }

                    swalWithBootstrapButtons.fire({
                        title: 'Dapatkan Pengesahan Operasi',
                        text: errortext,
                        icon: 'info',
                        showCancelButton: true,
                        confirmButtonText: 'Hantar',
                        cancelButtonText: 'Batal',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            
                            let norujukan = $('#norujukan').val();
                            let nm = parseFloat($('#total_nilai_marhun').val().replace(/[^0-9.-]+/g,""));let ber = $('#total_berat').val();let marg = $('.span-pinjaman').text();
                            // let komen = "Pembiayaan Melebihi Margin 75%|" + nm + "|" + ber +  "|" + marg + "|";
                            let status = errortext;
                            let jumpinjam = $('#pinjaman').val();
                            let teller = "{{ Auth::user()->name }}";

                            Swal.fire({
                                title: 'Tunggu Pengesahan Daripada Khazanah-Operasi.',
                                icon: 'info',
                                width: 600,
                                padding: '3em',
                                background: '#fffff',
                                showCancelButton: false,
                                showConfirmButton: false,
                                allowOutsideClick: false,
                                allowEscapeKey: false,
                                allowEnterKey: false
                            })
                            let siricreated = 0;
                            $.ajax({
                                method:'post',
                                url: "{{ route('operasi.createkelulusan') }}",
                                data: {
                                    "_token": "{{ csrf_token() }}",
                                    "norujukan" : norujukan,
                                    "komen" : '',
                                    "margin" : marg,
                                    "berat" : ber,
                                    "nilaimarhun" : nm,
                                    "status" : status,
                                    "jumpinjam" : jumpinjam,
                                    "teller" : teller

                                },
                                success:function(data){
                                    siricreated = data;
                                },error: function(xhr, status, error) {
                                var err = eval("(" + xhr.responseText + ")");
                                alert(xhr.responseText);
                                }
                            });    

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

                            var channel = pusher.subscribe('notice-kelulusan');
                            channel.bind('my-kelulusan', function(data) {
                            

                                if(data.norujukan == norujukan && data.siri == siricreated && data.teller == teller)
                                {
                                    if(data.kelulusan == 'lulus')
                                    {
                                        Swal.fire({
                                                    icon: 'success',
                                                    title: 'Telah Disahkan',
                                                    text: `Komen : ${data.komen}`
                                        }).then(function(){
                                            $(func).attr("onSubmit","return true;");
                                            $(func).submit();
                                            return true;
                                        });
                                    }
                                    else if(data.kelulusan == 'batal')
                                    {
                                        Swal.fire({
                                            icon: 'warning',
                                            title: 'Telah Dibatalkan',
                                            text: `Komen : ${data.komen}`
                                        }).then(function(){
                                            $("#terima_gadai").prop('disabled', false);
                                            return false;
                                        });
                                    }
                                }
                            });
                        } else if (result.dismiss === Swal.DismissReason.cancel){
                            swalWithBootstrapButtons.fire(
                                'Batal',
                                'Malumat Pembiayaan Tidak Berjaya Disimpan',
                                'error'
                            )
                        }
                    });
                
                    event.preventDefault();
                    return false;

                }else if(pinjaman > Number(pembiayaan_max_teller)){
                    const swalWithBootstrapButtons = Swal.mixin({
                        customClass: {
                            confirmButton: 'btn btn-success',
                            cancelButton: 'btn btn-danger'
                        },
                        buttonsStyling: false
                    })

                    swalWithBootstrapButtons.fire({
                        title: 'Dapatkan Pengesahan Daripada Khazanah?',
                        text: "Tetapan margin melebihi" + pinjaman_teller + "% untuk Khazanah!",
                        icon: 'info',
                        showCancelButton: true,
                        confirmButtonText: 'Hantar',
                        cancelButtonText: 'Batal',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                        
                            let norujukan = $('#norujukan').val();
                            let nm = parseFloat($('#total_nilai_marhun').val().replace(/[^0-9.-]+/g,""));let ber = $('#total_berat').val();let marg = $('.span-pinjaman').text();
                            // let komen = "Pembiayaan Melebihi Margin 70%|" + nm + "|" + ber +  "|" + marg + "|";
                            let status = "Pembiayaan Melebihi Margin " + pinjaman_teller + "%";
                            let jumpinjam = $('#pinjaman').val();
                            let teller = "{{ Auth::user()->name }}";

                            Swal.fire({
                                title: 'Tunggu Pengesahan Daripada Khazanah.',
                                icon: 'info',
                                width: 600,
                                padding: '3em',
                                background: '#fffff',
                                showCancelButton: false,
                                showConfirmButton: false,
                                allowOutsideClick: false,
                                allowEscapeKey: false,
                                allowEnterKey: false
                            })
                            let siricreated = 0;
                            $.ajax({
                                method:'post',
                                url: "{{ route('khazanah.createkelulusan') }}",
                                data: {
                                    "_token": "{{ csrf_token() }}",
                                    "norujukan" : norujukan,
                                    "komen" : '',
                                    "margin" : marg,
                                    "berat" : ber,
                                    "nilaimarhun" : nm,
                                    "status" : status,
                                    "jumpinjam" : jumpinjam,
                                    "teller" : teller
                                },
                                success:function(data){
                                    siricreated = data;
                                },error: function(xhr, status, error) {
                                var err = eval("(" + xhr.responseText + ")");
                                alert(xhr.responseText);
                                }
                            });    

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

                            var channel = pusher.subscribe('notice-kelulusan');
                            channel.bind('my-kelulusan', function(data) {
                            // let message = JSON.stringify(data);

                                // console.log(message);

                                if(data.norujukan == norujukan && data.siri == siricreated && data.teller == teller)
                                {
                                    if(data.kelulusan == 'lulus')
                                    {
                                        Swal.fire({
                                            icon: 'success',
                                            title: 'Telah Disahkan'
                                        }).then(function(){

                                            $(func).attr("onSubmit","return true;");
                                            $(func).submit();
                                            return true;

                                        });
                                    }
                                    else if(data.kelulusan == 'batal')
                                    {
                                        Swal.fire({
                                            icon: 'warning',
                                            title: 'Telah Dibatalkan'
                                        }).then(function(){
                                            $("#terima_gadai").prop('disabled', false);
                                            return false;
                                        });
                                    }
                                }



                            });
                        
                        } else if (result.dismiss === Swal.DismissReason.cancel) {
                            swalWithBootstrapButtons.fire(
                                'Batal',
                                'Maklumat Pembiayaan Tidak Berjaya Disimpan',
                                'error'
                            )
                        }
                    });
                
                    event.preventDefault();
                    return false; 
                }
                else if(pinjaman < 10000  && pinjaman <= Number(pembiayaan_max_teller)){
                    Swal.fire({
                        icon: 'success',
                        title: 'Berjaya!',
                        text: 'Pembiayaan Berjaya Disimpan'
                    });
                    return true;
                }
            }
        }
    }
</script>
@endsection
