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


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

            <nav aria-label="breadcrumb" id="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" id="infopelanggan">
                <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>TEMPOH</b>
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['tempoh'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>

                {{-- <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <button class="btn btn-primary" onclick="funcTU()">Maklumat Keuntungan</button>
                        </div>
                    </div>

                </div> --}}

            </div>

            <div class="form-group row col-12" id="jenistebus">
                <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['tagbaru'] == 1)
                                        @if(!in_array(Auth::user()->cawangan, config('redeemoption.cawangan_block', [])))
                                            <option value="A" {{ $gadai['tempoh'] >= 12 ? 'disabled' : '' }}>A = Ansuran Pembiayaan</option>
                                        @endif
                                        @if(config('redeemoption.enable_separuh') == 1)
                                            @if(!in_array(Auth::user()->cawangan, config('redeemoption.cawangan_block', [])))
                                            <option value="S">S = Sebahagian</option>
                                            @endif
                                        @endif
                                        @if(config('redeemoption.enable_tambahpinjam') == 1)
                                            @if(!in_array(Auth::user()->cawangan, config('redeemoption.cawangan_block', [])))
                                            <option value="P">P = Tambah Pembiayaan</option>
                                            @endif
                                        @endif
                                    @endif
                                    @if(config('redeemoption.enable_pembiayaansemula') == 1)
                                        @if(!in_array(Auth::user()->cawangan, config('redeemoption.cawangan_block', [])))
                                        <option value="AT">PS = Pembiayaan Semula</option>
                                        @endif
                                    @endif
                                    <option value="" disabled hidden>Pilih Jenis Penyelesaian Pembiayaan</option>
                              </select>
                        </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" id="infomarhun">
                <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>Nota</th>
                                <th>Harga</th>
                                <th>Harga Semasa</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>@if($m['tag_permata']) (P) @endif{{ $m['nota'] }}</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>
                            </tr>
                            @php $count++; @endphp
                            @endforeach
                        </tbody>
                        <tr>
                            <td colspan="2"><b>JUMLAH</b></td>
                            <td id="nilai_marhun_total_fix">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="4"></td>
                          </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            <div class="card" id="infotransaksi">
                <div class="card-body infotransaksi">
                    

                    <div id="jenisT" class="col-12 form-group row">
                        <div class="col-6">
                            
                            <div 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" style="font-weight:bold;" onkeyup="bayarkey(this)" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>

                            <div>
                                <fieldset class="scheduler-border">
                                    <div class="form-group row" id="divduitPelanggan">
                                        <div class="col-4">
                                        <span>DUIT PELANGGAN (RM)</span>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="duitPelanggan" onkeyup="bayaranPelanggan(this)"  onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" placeholder="0.00" class="form-control"/>
                                        </div>
                                    </div>
                                    <div class="form-group row" id="divbakiPelanggan">
                                        <div class="col-4">
                                            <b>BAKI (RM)</b>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="bakiPelanggan" class="form-control" value="0.00" readonly/>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>
                        <div class="col-6" id="divbakihargajualan">
                             
                            <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 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>

                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrah" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercent" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebet" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebet" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlahupah" class="form-control" readonly/>
                                </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>
                    <div id="jenisS" class="col-12 form-group row">
                        <div class="col-6">
                            <div 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" style="font-weight:bold;" onchange="bayarkey(this)" onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" class="form-control" readonly/>
                                    </div>
                                </div>
                            </div>


                            <div>
                                <fieldset class="scheduler-border">
                                    <div class="form-group row" id="divduitPelanggan">
                                        <div class="col-4">
                                        <span>DUIT PELANGGAN (RM)</span>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="duitPelanggan" onkeyup="bayaranPelanggan(this)"  onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" placeholder="0.00" class="form-control"/>
                                        </div>
                                    </div>
                                    <div class="form-group row" id="divbakiPelanggan">
                                        <div class="col-4">
                                            <b>BAKI (RM)</b>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="bakiPelanggan" class="form-control" value="0.00" readonly/>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>


                        <div class="col-6">

                            <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 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>
                           
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrah" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercent" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebet" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebet" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlahupah" class="form-control" readonly/>
                                </div>
                            </div>

                            <div 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>
                    </div>
                    <div id="jenisA" class="col-12 form-group row">
                        <div class="col-6">
                            <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 class="form-group row" id="divbayaran">
                                <div class="col-4">
                                    <b>BAYARAN PELANGGAN (RM)</b>
                                </div>
                                <div class="col-8">
                                    <input type="text" id="bayaran" onkeyup="bayartambahan(this)" onkeypress="return validateFloatKeyPressAnsuran(this,event);" placeholder="0.00" class="form-control" disabled/>
                                </div>
                            </div>

                            <div>
                                <fieldset class="scheduler-border">
                                    <div class="form-group row" id="divduitPelanggan">
                                        <div class="col-4">
                                        <span>DUIT PELANGGAN (RM)</span>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="duitPelanggan" onkeyup="bayaranPelanggan(this)"  onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" placeholder="0.00" class="form-control"/>
                                        </div>
                                    </div>
                                    <div class="form-group row" id="divbakiPelanggan">
                                        <div class="col-4">
                                            <b>BAKI (RM)</b>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="bakiPelanggan" class="form-control" value="0.00" readonly/>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>

                        </div>

                        <div class="col-6" id="divbakihargajualan">
                                                
                            <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 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>

                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrah" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercent" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebet" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebet" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlahupah" class="form-control" readonly/>
                                </div>
                            </div>

                        </div>

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

                        <!-- baki hargajualan -->

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

                            <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)" onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" 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 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>
                                <fieldset class="scheduler-border">
                                    <div class="form-group row" id="divduitPelanggan">
                                        <div class="col-4">
                                        <span>DUIT PELANGGAN (RM)</span>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="duitPelanggan" onkeyup="bayaranPelanggan(this)"  onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" placeholder="0.00" class="form-control"/>
                                        </div>
                                    </div>
                                    <div class="form-group row" id="divbakiPelanggan">
                                        <div class="col-4">
                                            <b>BAKI (RM)</b>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="bakiPelanggan" class="form-control" value="0.00" readonly/>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>

                        <div class="col-6">

                            <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 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>

                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrah" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercent" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebet" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebet" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </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
                                    if($gadai['bakipjm'] != 0){
                                        $bakipjm = $gadai['bakipjm'];
                                    }else{
                                        $bakipjm = $gadai['pinjaman'];
                                    }
                                    $percent_asal = ($bakipjm / $gadai['nilaimarhun']) * 100;
                                @endphp
                                <div class="col-8 input-group mb-2">
                                    <input type="text" id="hargapembiayaansemasa" class="form-control" value="{{ number_format($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="divpinjamanbaru">

                                    <div class="col-4">
                                        <span>PEMBIAYAAN BARU (RM)</span>
                                    </div>
                                    @php
                                        if($gadai['bakipjm'] != 0){
                                            $bakipjm = $gadai['bakipjm'];
                                        }else{
                                            $bakipjm = $gadai['pinjaman'];
                                        }
                                        $percent_hargaemassemasa = ($bakipjm / $nilaihargasemasa) * 100;

                                        $percentage = 80 / 100;
                                        $pembiayaanbaru = $nilaihargasemasa * (80/100);
                                        $rounded_value = round($nilaihargasemasa * $percentage, 1, PHP_ROUND_HALF_UP);
                                        $rounded_value = (($rounded_value-$pembiayaanbaru) > 0) ? $rounded_value - 0.1 : $rounded_value;
                                        $pembiayaanbaru = min($pembiayaanbaru, $rounded_value);
                                        $bayaranlebihan = $bakipjm - $pembiayaanbaru;

                                        $pembiayaanbaru = ($percent_hargaemassemasa > 80) ? $pembiayaanbaru : $bakipjm;
                                    @endphp
                                    <div class="col-8 input-group mb-3">
                                        <input type="text" id="pinjamanbaru" value="{{ number_format($pembiayaanbaru ,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>
                                            @if($percent_hargaemassemasa > 80)
                                                <span class="input-group-text" id="basic-addon3">{{ number_format($percent_hargaemassemasa,2) }}</span>
                                            @endif
                                        </div>
                                    </div>

                                    @if($percent_hargaemassemasa > 80)
                                    <div class="divlebihanmargin">
                                        <div class="col-4">
                                            <span>BAYARAN LEBIHAN MARGIN</span>
                                        </div>
                                        <div class="col-8 input-group mb-3">
                                            <input type="text" id="txtlebihanmargin" value="{{ number_format($bayaranlebihan,2)}}" class="form-control" aria-describedby="txtlebihanmargin" readonly/>
                                            <div class="input-group-append">
                                            <span class="input-group-text" id="txtlebihanmargin">{{ round($percent_hargaemassemasa - 80,2) }}</span>
                                                </div>
                                        </div>
                                    </div>
                                @endif
                            </div>

                        </div>



                    </div>
                    <div id="jenisAT" class="col-12 form-group row">
                        <div class="col-6">
                            <div class="form-group row" id="divhargaemassemasa">
                                <div class="col-4">
                                    PEMBIAYAAN H. ASAL (RM)
                                </div>
                                @php
                                    if($gadai['bakipjm'] != 0){
                                        $bakipjm = $gadai['bakipjm'];
                                    }else{
                                        $bakipjm = $gadai['pinjaman'];
                                    }
                                    $percent_asal = ($bakipjm / $gadai['nilaimarhun']) * 100;
                                @endphp
                                <div class="col-8 input-group mb-2">
                                    <input type="text" id="hargapembiayaansemasa" class="form-control" value="{{ number_format($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="divpinjamanbaru">

                                    <div class="col-4">
                                        <span>PEMBIAYAAN BARU (RM)</span>
                                    </div>
                                    @php
                                        if($gadai['bakipjm'] != 0){
                                            $bakipjm = $gadai['bakipjm'];
                                        }else{
                                            $bakipjm = $gadai['pinjaman'];
                                        }
                                        $percent_hargaemassemasa = ($bakipjm / $nilaihargasemasa) * 100;

                                        $percentage = 80 / 100;
                                        $pembiayaanbaru = $nilaihargasemasa * (80/100);
                                        $rounded_value = round($nilaihargasemasa * $percentage, 1, PHP_ROUND_HALF_UP);
                                        $rounded_value = (($rounded_value-$pembiayaanbaru) > 0) ? $rounded_value - 0.1 : $rounded_value;
                                        $pembiayaanbaru = min($pembiayaanbaru, $rounded_value);
                                        $bayaranlebihan = $bakipjm - $pembiayaanbaru;

                                        $pembiayaanbaru = ($percent_hargaemassemasa > 80) ? $pembiayaanbaru : $bakipjm;
                                    @endphp
                                    <div class="col-8 input-group mb-3">
                                        <input type="text" id="pinjamanbaru" value="{{ number_format($pembiayaanbaru ,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>
                                            @if($percent_hargaemassemasa > 80)
                                                <span class="input-group-text" id="basic-addon3">{{ number_format($percent_hargaemassemasa,2) }}</span>
                                            @endif
                                        </div>
                                    </div>

                                    @if($percent_hargaemassemasa > 80)
                                    <div class="divlebihanmargin">
                                        <div class="col-4">
                                            <span>BAYARAN LEBIHAN MARGIN</span>
                                        </div>
                                        <div class="col-8 input-group mb-3">
                                            <input type="text" id="txtlebihanmargin" value="{{ number_format($bayaranlebihan,2)}}" class="form-control" aria-describedby="txtlebihanmargin" readonly/>
                                            <div class="input-group-append">
                                            <span class="input-group-text" id="txtlebihanmargin">{{ round($percent_hargaemassemasa - 80,2) }}</span>
                                                </div>
                                        </div>
                                    </div>
                                @endif
                            </div>

                            <div class="form-group row" id="divperludibayarAT">
                                <div class="col-4">
                                    <b>BAYARAN PELANGGAN (RM)</b>
                                </div>
                                <div class="col-8">
                                    <input type="text" id="perludibayarAT" style="font-weight:bold;" class="form-control" onselectstart="return false;" onpaste="return false;" ondrop="return false;" onkeyup="bayaranATfunc(this)" onkeypress="return validateFloatKeyPressAT(this,event);" onchange="blockbayaranAT(this)" readonly/>
                                </div>
                            </div>

                            <div>
                                <fieldset class="scheduler-border">
                                    <div class="form-group row" id="divduitPelanggan">
                                        <div class="col-4">
                                        <span>DUIT PELANGGAN (RM)</span>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="duitPelanggan" onkeyup="bayaranPelanggan(this)"  onpaste="return false;" ondrop="return false;" onkeypress="return validateKeyPress(this,event);" placeholder="0.00" class="form-control"/>
                                        </div>
                                    </div>
                                    <div class="form-group row" id="divbakiPelanggan">
                                        <div class="col-4">
                                            <b>BAKI (RM)</b>
                                        </div>
                                        <div class="col-8">
                                            <input type="text" id="bakiPelanggan" class="form-control" value="0.00" readonly/>
                                        </div>
                                    </div>
                                </fieldset>
                            </div>
                        </div>

                        <div class="col-6" id="divbakihargajualan">
                                                
                            <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 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>

                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrah" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercent" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebet" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebet" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlahupah" class="form-control" readonly/>
                                </div>
                            </div>

                        </div>





                    </div>

                    <div id="jenisTU" class="col-12 form-group row">
                        <div class="col-12 mb-4"> <h2 class="center m-auto text-center text-primary">MAKLUMAT KEUNTUNGAN</h2></div>
                        <div class="col-6" id="date">
                            <div class="form-group row">
                            <div class="col-4">
                                TARIKH
                            </div>
                            <div class="col-8">
                                <input class="form-control" type="text" onchange="getUpahByDate(this)" name="datetarikh" id="datetarikh" placeholder="Tekan Untuk Pilih Tarikh"/>
                            </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-4">
                                    TEMPOH PEMBIAYAAN
                                </div>
                                <div class="col-8">
                                    <input type="text" id="tempohjanaan" name="tempohjanaan" class="form-control" readonly/>
                                </div>
                            </div>
                        </div>

                        <div class="col-6">

                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        SEBENAR
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahTU" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentTU" class="form-control" readonly/>
                                    </div>
                            </div>
                            @endif
                            @if($gadai['tagbaru'] == 1)
                            <div class="form-group row">
                                    <div class="col-4">
                                    </div>
                                    <div class="col-4">
                                        <span>LAIN-LAIN CAJ</span>
                                    </div>
                                    <div class="col-4">
                                        <span>KEUNTUNGAN</span>
                                    </div>

                                    <div class="col-4">
                                        REBAT
                                    </div>

                                    <div class="col-4">
                                        <input type="text" id="jumujrahrebetTU" class="form-control" readonly/>
                                    </div>
                                    <div class="col-4">
                                        <input type="text" id="jumonepercentrebetTU" class="form-control" readonly/>
                                    </div>
                            </div>


                            @endif

                            <div class="form-group row">
                                <div class="col-4">
                                    @if($gadai['tagbaru'] == 1) JUM UNTUNG DAN LAIN-LAIN CAJ @else JUMLAH KEUNTUNGAN @endif
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlahupahTU" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    HARGA TEBUS
                                </div>
                                <div class="col-8">
                                    <input type="text" id="hargatebus" name="hargatebus" class="form-control" readonly/>
                                </div>
                            </div>

                        
                        </div>

                    </div>
                </div>

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

                        <div class="col-12 d-flex justify-content-between">
                            @if($gadai['tagbaru'] == 0)
                                <div class="col-6" id="divjenisAT">
                                    <button type="button" class="btn btn-danger" onclick="funcexcuse(false)">Batal</button>
                                </div>
                                @if($percent_hargaemassemasa > 80 && $gadai['taglel'] == 1)
                                    <div class="col-6 divlebihanmargin">
                                        <button type="button" class="btn btn-primary" onclick="funcexcuse(true)">EXCUSE</button>
                                    </div>
                                    <div class="col-1" id="divdummy">
                                    </div>
                                @else
                                    <div class="col-6">

                                    </div>
                                @endif
                            @else
                                <div class="col-6">

                                </div>
                            @endif
                            <div class="justify-content-end">
                                <input type="button" class="float-right btn btn-danger mr-2" value="BATAL" onclick="pembatalanbalik();">
                                @if(Auth::user()->roles == 'teller') <input type="button" id="terima_transaksi" class="float-right btn btn-primary mr-2" value="TERIMA" onclick="bayaransemua()"> @endif
                            </div>
                        </div>
                    </div>
            </div>

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

<script>

    let elem_jenisAT = $('#jenisAT').remove();
    let elem_jenisA = $('#jenisA').remove();
    let elem_jenisT = $('#jenisT').remove();
    let elem_jenisS = $('#jenisS').remove();
    let elem_jenisP = $('#jenisP').remove();
    let elem_jenisTU = $('#jenisTU').remove();
    $('#divjenisAT').hide();


    let pertambahpinjaman = "{{ $pertambahpinjaman }}";
    var api = '<?php echo $api_url ?>';
    let nw = 0;
    let jenisAT = 'none';

    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 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 tagbaru = "{{ $gadai['tagbaru'] }}";


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

    var jumlahperlu = 0;
    var jumlahminima = 0;
    var percent_mora = 0;
    var pinjaman_teller = 0;
    var pinjaman_pelulus = 0;



    $( document ).ready(function() {



        $.ajax({
            method:'get',
            datatype:'json',
            url:api + '/api/moratorium/details',
            success:function(data){
                percent_mora = data['percent_mora'];
            }
        });

        $.ajax({
            method:'GET',
            url: api + '/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']);
                    }
                });
            }
        });


        elem_jenisT.prependTo(".infotransaksi");

        tebusan();


    });

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


        switch($(this).val()){
            case "T": 
                elem_jenisT.prependTo(".infotransaksi");
                $('#jenisAT').remove();
                $('#jenisA').remove();
                $('#jenisS').remove();
                $('#jenisP').remove();
                $('#jenisTU').remove();

                $("#terima_transaksi").prop('disabled', false);
                $('input[type="checkbox"]').hide();
                $('span.spannar').show();

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

                $('#calcbayar').val($('#perludibayar').val().replace(/[^0-9.-]+/g,""));

                tebusan();
            break;
            case "A": 
                var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
                // var jumupahrebet = parseFloat($('#bayaranditerima').val().replace(/[^0-9.-]+/g,""));

                elem_jenisA.prependTo(".infotransaksi");
                $('#jenisAT').remove();
                $('#jenisT').remove();
                $('#jenisS').remove();
                $('#jenisP').remove();
                $('#jenisTU').remove();

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

                $("#terima_transaksi").prop('disabled', false);

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

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

                $('#bayaran').val(formatter.format(jumupah));
                tebusan();

            break;    
            case "S":
                elem_jenisS.prependTo(".infotransaksi");
                $('#jenisAT').remove();
                $('#jenisA').remove();
                $('#jenisT').remove();
                $('#jenisP').remove(); 
                $('#jenisTU').remove();

                $("#terima_transaksi").prop('disabled', true);

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

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

                $('.button input').prop('checked', false);

                tebusan();
                $("#perludibayar").val(0);
                $("#basic-separuh").text('0.00');
                $("#bakipinjaman").val('0.00');
                $('input[type="checkbox"]').prop("checked", false);

            break;
            case "P":
                
            $('input[type="checkbox"]').hide();
            $('span.spannar').show();
            
            elem_jenisP.prependTo(".infotransaksi");
            $('#jenisAT').remove();
            $('#jenisA').remove();
            $('#jenisT').remove();
            $('#jenisS').remove();
            $('#jenisTU').remove();

            $("#terima_transaksi").prop('disabled', false);


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

            tebusan();

            var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));

            $('#bayaranditerima').val(jumupah);

            var pij = Number($('#tambahpinjamsebenar').val());
            if(pij < 0)
                $("#terima_transaksi").prop('disabled', true);

            break;
            case "AT": 
            elem_jenisAT.prependTo(".infotransaksi");
            $('#jenisA').remove();
            $('#jenisT').remove();
            $('#jenisS').remove();
            $('#jenisP').remove();  

            tebusan();

            var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
            let percenthargasemasa = parseFloat('{{ number_format($percent_hargaemassemasa,2) }}');
            let jumlebmargin = parseFloat('{{ ($percent_hargaemassemasa > 80) ? $bayaranlebihan : 0 }}');
            let totalbayaran = (percenthargasemasa > 80) ? (jumlebmargin + jumupah) : jumupah;
            $("#terima_transaksi").prop('disabled', false);

            /* this one is for show the numbering */
            $('input[type="checkbox"]').hide();
            $('span.spannar').show();

            $("#perludibayarAT").prop("readonly", false);

            $('#divbayaran').hide();
            $('#basic-addon2').text((percenthargasemasa > 80) ? '80.00' : percenthargasemasa);
            $('#perludibayarAT').val(formatter.format(totalbayaran));
            $('#calcbayar').val(totalbayaran);


            break;
        }
    });

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

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

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

            //Upah Tawarruq
            let jeniskeuntungan = (tagbaru == 1) ? 'onepercent' : 'asal';
            $.ajax({
                method:'GET',
                url: api + '/api/upahtawarruq/' + kodcaw + '/' + norujukan,
                async:false,
                data: {
                    'jeniskeuntungan' : jeniskeuntungan
                },
                dataType: 'json',
                success:function(data){
                    if(jeniskeuntungan == 'asal')
                    {
                        $('#jumlahupah').val(data);
                    }else{
                        $('#jumlahupah').val(data['pendapatan']);
                        $('#jumujrah').val(data['ujrah']);
                        $('#jumonepercent').val(data['keuntungan']);
                    }
                    
                }
            });

            $.ajax({
                method:'GET',
                url: api + '/api/upahrebettawarruq/' + kodcaw + '/' + norujukan,
                async:false,
                data: {
                    'jeniskeuntungan' : jeniskeuntungan
                },
                dataType: 'json',
                success:function(data){
                    if(jeniskeuntungan == 'asal'){
                        $('#bayaranditerima').val(data);
                    }else{
                        let ujrah = Number($('#jumujrah').val());
                        let onepercent = Number($('#jumonepercent').val());

                        let total = ujrah - data['ujrah']; 
                        let keuntotal = onepercent - data['keuntungan'];
                        $('#jumujrahrebet').val(formatter.format(total.toFixed(2)));
                        $('#jumonepercentrebet').val(keuntotal.toFixed(2));
                    }
                }
            });

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

            // Telah dibayar
            $.ajax({
                method:'GET',
                url: api + '/api/transaction/' + norujukan,
                dataType: 'json',
                async:false,
                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(totalCheckboxes == (totalCheckboxes - numbernotchecked)){
                return false;
            }


            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);
            });

            let jenisuntung = (tagbaru == 1) ? 'onepercent' : 'asal';

            if(numbernotchecked != totalCheckboxes){

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

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

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

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

                        if(totalcalculate > (pertambahpinjaman * 100)){
                            var max = bakinm * pertambahpinjaman;
                            var maxpjm = totalbakipinjam - max;

                            totalbakipinjam -= maxpjm;
                            bayaranseparuhasal += maxpjm;
                            totalcalculate = ((totalbakipinjam)/bakinm)*100;
                        }

                        let total = bayaranseparuhasal + upah - (upahujrah + upahonepercent);
                        total = getRoundedMethod(total);
                        totalbakipinjam = getRoundedMethod(totalbakipinjam);

                        $('#perludibayar').val(formatter.format(total.toFixed(2)));
                        $('#basic-separuh').text(formatter.format(Number(totalcalculate.toFixed(2))));
                        $('#bakipinjaman').val(formatter.format(totalbakipinjam.toFixed(2)));

                        $("#terima_transaksi").prop('disabled', false);

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

            }else{
                $("#terima_transaksi").prop('disabled', true);
                $('#perludibayar').val(0);
                $('#bakipinjaman').val(0);
                $('#basic-separuh').text(0)
                $('#bayaran').val(0);

            }
        });

    
    }

    function bayarkey(e){

        $('#bakiPelanggan').val('0.00');
        $('#duitPelanggan').val('');

        if($('#sltjenistebus').find(":selected").val() == 'S'){
            let byr = $(e).val().replace(/[^0-9.-]+/g,"");
            let total = 0;
            let pdbyr = 0;
            let totalseparuh = 0;
            let totalnilaimarhunseparuh = 0;
            var nmsemasa = parseFloat("{{ $nilaihargasemasa }}");
            let upah = parseFloat($('#jumlahupah').val());
            let ujrahrebet = parseFloat($('#jumujrahrebet').val().replace(/[^0-9.-]+/g,""));
            let onepercentrebet = parseFloat($('#jumonepercentrebet').val().replace(/[^0-9.-]+/g,""));

            let rebet = ujrahrebet + onepercentrebet;

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

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

            let bakinm = nmsemasa - totalnilaimarhunseparuh;

            let totalkurang = bayaranseparuhasal + (upah - rebet);
            let tenpercentmarhun = bakinm * 0.1;
            let tenpercentblock =  getRoundedMethod(tenpercentmarhun);


            var totalcalculate = ((total/bakinm)*100);

            if(byr < totalkurang){
                let test = totalkurang - (upah + rebet);

                let bakipjm = parseFloat($('#pinjaman').val().replace(/[^0-9.-]+/g,"")) - (bayaranseparuhasal);
                totalcalculate = ((bakipjm/bakinm) * 100);
                
                $(e).val(formatter.format(totalkurang.toFixed(2)));
                $('#bakipinjaman').val(formatter.format(bakipjm.toFixed(2)));
                $('#basic-separuh').text(formatter.format(Number(totalcalculate.toFixed(2))));
                return false;
            }

            if(total < tenpercentblock){
                let temptotal = totaldibayar - tenpercentblock;
                let tempbakipjm = $('#pinjaman').val().replace(/[^0-9.-]+/g,"") - (temptotal - upah + rebet);

                totalcalculate = ((tempbakipjm/bakinm) * 100);
                $(e).val(formatter.format(temptotal.toFixed(2)));
                $('#bakipinjaman').val(formatter.format(tempbakipjm.toFixed(2)));
                $('#basic-separuh').text(formatter.format(Number(totalcalculate.toFixed(2))));
                return false;
            }



            $('#bakipinjaman').val(total.toFixed(2));
            $('#basic-separuh').text(Number(totalcalculate.toFixed(2)));
        }
    }

    function bayartawarruq(e){
        var keuntungan = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
        var bayaran = parseFloat(e.value);
        var pinjamasal = parseFloat($('#pinjamanasal').val().replace(/[^0-9.-]+/g,""));


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

        // console.log(nm+' '+nmsemasa);

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

        if(e.value != ''){
            var bayaran = parseFloat(e.value);
        }else{
            var bayaran = 0;
        }

        var totalbayaran = keuntungan + bayaran;

        var pinjaman_baru = pinjamasal - bayaran;

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

        $('#perludibayartawarruq').val(totalbayaran.toFixed(2));
        $('#hargapembiayaansemasa').val(pinjaman_baru.toFixed(2));
        $('#pinjamanbaru').val(pinjaman_baru.toFixed(2));
        $('#basic-addon2').text(totalsemasa.toFixed(2));
        $('#basic-hargaemas').text(total.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);
                }

            }
        }

        $('#bakiPelanggan').val('0.00');
        $('#duitPelanggan').val('');
        
    }

    function bayaranPelanggan(e){
        let total = 0;
        let bayaran = $('#duitPelanggan').val();
        let perludibayar = 0;
        if ($('#sltjenistebus').find(":selected").val() == 'T'){
            perludibayar = parseFloat($('#perludibayar').val().replace(/[^0-9.-]+/g,""));
        }else if($('#sltjenistebus').find(":selected").val() == 'A'){
            perludibayar = parseFloat($('#bayaran').val().replace(/[^0-9.-]+/g,""));
        }else if($('#sltjenistebus').find(":selected").val() == 'AT'){
            perludibayar = parseFloat($('#perludibayarAT').val().replace(/[^0-9.-]+/g,""));
        }else if($('#sltjenistebus').find(":selected").val() == 'P'){
            perludibayar = parseFloat($('#bayaranditerima').val().replace(/[^0-9.-]+/g,""));
        }else if($('#sltjenistebus').find(":selected").val() == 'S'){
            perludibayar = parseFloat($('#perludibayar').val().replace(/[^0-9.-]+/g,""));
        }

        total = bayaran - perludibayar;
        $('#bakiPelanggan').val((total > 0) ? formatter.format(total.toFixed(2)) : '0.00');

    }


    function bayarpinjam(e){
        let maxgadaipembiayaanbaru = "{{ $maxgadaipemb = ($nilaihargasemasa * $pertambahpinjaman) - $gadai['bakipjm'] }}";

        var maxpinjam = getRoundedMethod(Number(maxgadaipembiayaanbaru).toFixed(2));
        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);

        var maxpinjaman = nmsemasa * pertambahpinjaman;

        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);

            let tot = parseFloat($(e).val()) - parseFloat(maxpinjam);
            let pinjbaru =  parseFloat(pinjam) + parseFloat(maxpinjam);
            $('#tambahpinjamsebenar').val(tot.toFixed(2));
            $('#pinjamanbaru').val(pinjbaru.toFixed(2));

            let percpinjtmbh = pinjbaru / nmsemasa * 100;

            $('#basic-addon2').text(percpinjtmbh.toFixed(2));

            Swal.fire('Amaran!',`Tambah Pembiayaan tidak boleh melebihi ${formatter.format(pertambahpinjaman * 100)}% !`,'error');


            return false;
            event.preventDefault();
        }

        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 bayaransemua()
    {
        $("#terima_transaksi").prop('disabled', true);
        // Swal.fire({
        //     title: 'Memuatkan...',
        //     allowEscapeKey : false,
        //     allowOutsideClick: false,
        //     didOpen: function () {
        //         Swal.showLoading();
        //     }
        // });

        var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));

        if($('#sltjenistebus').find(":selected").val() == 'T'){

            var adadah = false;
            var adaonline = false;

            $.ajax({
            method:'get',
            datatype: 'json',
            url: api + '/api/listpenebusanhistory/' + kodcaw,
            async:false,
            data: { 'norujukan' : norujukan },
            success:function(success_data){
                var count = Object.keys(success_data).length;

                if(count > 0)
                {
                    Swal.close();
                    Swal.fire('Amaran!','Tebus sudah dibuat sila tekan butang batal!','error');
                    $("#terima_transaksi").prop('disabled', false);
                    adadah = true;
                }
            }
            });

            $.ajax({
            method:'get',
            datatype: 'json',
            url: api + '/portal/searchsagonline/',
            async:false,
            data: { 'norujukan' : norujukan },
            success:function(success_data){

                if(success_data == true)
                {
                    Swal.close();
                    Swal.fire('Amaran!','Bayaran online dalam proses!','error');
                    $("#terima_transaksi").prop('disabled', false);
                    adaonline = true;
                }

            }
            });

            if(adadah === true || adaonline === true)
            {
                return false;
                event.preventDefault();
            }

            let jenisbayarantebus = '';

            if(hargajualan == '')
            {
                jenisbayarantebus = "nottawarruq";
            }
            else if (hargajualan != ''){
                jenisbayarantebus = "tawarruq";
            }

            //tambahan untuk one percent
            let jeniskeuntungan = '';
            if(tagbaru == 1){
                jeniskeuntungan = "onepercent";
            }
            else{
                jeniskeuntungan = "asal";
            }

            var nopelanggan = "{{ $gadai['nopelanggan'] }}";
            var jenistebus = $('#sltjenistebus').find(":selected").val();
            var jbg = "{{ $gadai['tempoh'] }}";
            var kadarupah = "{{ $gadai['kadarupah'] }}";
            var nilai_marhun = "{{ $gadai['nilaimarhun']}}";
            var pinjaman = "{{ $gadai['pinjaman']}}";
            var ansuran = 0;
            var addpinjaman = 0;
            var bakipinjaman = $('#perludibayar').val().replace(/[^0-9.-]+/g,"");
            var bakiupah = $('#jumlahupah').val().replace(/[^0-9.-]+/g,"");
            var historygadaian = 0;
            var marhun = "{{ $gadai['marhun'] }}";
            var nowakil = nw;
            var duitpelanggan = $('#duitPelanggan').val().replace(/[^0-9.-]+/g,"");
            var bakipelanggan =  $('#bakiPelanggan').val().replace(/[^0-9.-]+/g,"");


            if(Number(duitpelanggan) < Number(bakipinjaman)){
                Swal.close();
                Swal.fire('Amaran!','Duit Pelanggan haruslah diisi melebihi perlu dibayar!','error');
                $("#terima_transaksi").prop('disabled', false);

                event.preventDefault();
                return false;
            }

            $.ajax({
                method:'get',
                datatype: 'json',
                url: "{{ route('tebus.penuh') }}",
                data:{
                    "kodcaw" : kodcaw,
                    "norujukan" : norujukan,
                    "nopelanggan" : nopelanggan,
                    "jenistebus" : jenistebus,
                    "jbg" : jbg,
                    "kadarupah" : kadarupah,
                    "nilai_marhun" : nilai_marhun,
                    "pinjaman" : pinjaman,
                    "ansuran" : ansuran,
                    "addpinjaman" : addpinjaman,
                    "bakipinjaman" : bakipinjaman,
                    "bakiupah" : bakiupah,
                    "historygadaian" : historygadaian,
                    "marhun" : marhun,
                    "nowakil" : nowakil,
                    "jenisbayarantebus" : jenisbayarantebus,
                    "jeniskeuntungan" : jeniskeuntungan,
                    "teller" : teller,
                    "duitpelanggan" : duitpelanggan,
                    "bakipelanggan" : bakipelanggan,
                },
                success:function(success_data){


                    if(success_data == 'success')
                    {
                        if(jenisbayarantebus == "tawarruq")
                        {
                            var urlroute = '{{ route("resit.tebus", ":id") }}';
                            urlroute = urlroute.replace(':id', norujukan);

                        }else{
                            var urlroute = '{{ route("resit.belumtebus", ":id") }}';
                            urlroute = urlroute.replace(':id', norujukan);
                        }

                        $.ajax({
                            method: 'put',
                            url: "{{ route('alirantunai.tebus') }}",
                            async:false,
                            data:{
                                'norujukan' : norujukan,
                                "_token": "{{ csrf_token() }}"
                            },
                            success:function(data){
                                console.log(data);
                            }, error: function(xhr, status, error) {
                                        var err = eval("(" + xhr.responseText + ")");
                                        alert(xhr.responseText);
                            }
                        });

                        Swal.close();
                        Swal.fire({
                            icon: 'success',
                            title: 'Berjaya!',
                            text: 'Penebusan Berjaya',
                        }).then(function() {
                            window.open(urlroute, '_blank');
                            window.location.replace("{{  route('customer_info') }}");
                        })
                    }
                    else{
                        Swal.close();
                        Swal.fire({
                            icon: 'error',
                            title: 'Amaran!',
                            text: 'norujukan Sudah ditebus di dalam table gadai!',
                        });
                    }
                }
            });


            /////////////
            //End File//
            ///////////

        }else if($('#sltjenistebus').find(":selected").val() == 'A'){
            let adadah = false;

            $.ajax({
                method:'get',
                datatype: 'json',
                url: api + '/api/listpenebusanhistory/' + kodcaw,
                async:false,
                data: { 'norujukan' : norujukan },
                success:function(success_data){
                    var count = Object.keys(success_data).length;

                    if(count > 0)
                    {
                        Swal.close();
                        Swal.fire('Amaran!','Tebus sudah dibuat sila tekan butang batal!','error');
                        $("#terima_transaksi").prop('disabled', false);

                        adadah = true;
                    }
                }
            });

            if(adadah == true)
            {
                return false;
                event.preventDefault();
            }


            let jenisbayarantebus = '';
            let jeniskeuntungan = (tagbaru == 1) ? 'onepercent' : 'asal';

            let hadbayaransuran = (parseFloat("{{ $gadai['nilaimarhun']}}") * 0.1);

            var bayar = Number(parseFloat($('#bayaran').val().replace(/[^0-9.-]+/g,"")).toFixed(2));
            var bakipinjam = parseFloat("{{ $gadai['bakipjm'] }}") - hadbayaransuran + jumupah;
            var duitpelanggan = parseFloat($('#duitPelanggan').val().replace(/[^0-9.-]+/g,""));
            var bakipelanggan = parseFloat($('#bakiPelanggan').val().replace(/[^0-9.-]+/g,""));

            if(isNaN(duitpelanggan)) duitpelanggan = 0;

            if(Number(duitpelanggan) < Number(bayar)){
                Swal.close();
                Swal.fire('Amaran!','Duit Pelanggan haruslah diisi melebihi perlu dibayar!','error');
                $("#terima_transaksi").prop('disabled', false);

                event.preventDefault();
                return false;
            }

            if(bayar < jumupah){
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    'Bayaran tidak boleh kurang dari kos keuntungan semasa',
                    'error'
                )
                return false;
            }

            if(bayar >  bakipinjam){
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    'Bayaran tidak boleh melebihi 10% nilai marhun!',
                    'error'
                )
                return false;
            }

            $.ajax({
                method:'get',
                url: "{{ route('bayaran.ansuranstawarruq') }}",
                data:{
                    "bayaran" : bayar,
                    "kodcaw" : kodcaw,
                    "norujukan" : norujukan,
                    "teller" : teller,
                    "nowakil" : nw,
                    "duitpelanggan" : duitpelanggan,
                    "bakipelanggan" : bakipelanggan,
                    "jeniskeuntungan" : jeniskeuntungan
                },
                success:function(success_data){

                    if(success_data == 'success'){
                        var urlroute = '{{ route("resit.ansurans", ":id") }}';
                        urlroute = urlroute.replace(':id', norujukan);

                        Swal.fire(
                            'Berjaya!',
                            'Bayaran Ansuran Berjaya',
                            'success'
                        ).then(function() {
                            window.open(urlroute, '_blank');
                            window.location.replace("{{  route('customer_info') }}");
                        })
                    }else{
                        Swal.fire(
                            'Tidak Berjaya!',
                            'Bayaran ansuran tidak berjaya!',
                            'error'
                        );
                    }
                    
                }
            });

        }else if($('#sltjenistebus').find(":selected").val() == 'S'){

            let adadah = false;

            let komuditiblock = false;
            $.ajax({
                method:'get',
                url: api + '/api/komuditi/check',
                async:false,
                success:function(komoditi){
                    var check_komuditi = Object.keys(komoditi).length;
                    if(check_komuditi == 0){
                        $("#terima_transaksi").prop('disabled', false);
                        Swal.fire({
                            icon: 'error',
                            title: 'Unit Komuditi Berbaki Minumum',
                            text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                        });
                        komuditiblock = true;
                        event.preventDefault();
                        return false;
                    }else{
                        if(Number(komoditi['unit_komuditi']) < pinjaman_baru){
                            $("#terima_transaksi").prop('disabled', false);
                            Swal.fire({
                                icon: 'error',
                                title: 'Baki Unit Komuditi Tidak Mencukupi',
                                text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                            });
                            komuditiblock = true;
                            event.preventDefault();
                            return false;
                        }
                    }
                }
            });
            if(komuditiblock){
                event.preventDefault();
                return false;
            }

            $.ajax({
                method:'get',
                datatype: 'json',
                url: api + '/api/listpenebusanhistory/' + kodcaw,
                async:false,
                data: { 'norujukan' : norujukan },
                success:function(success_data){
                    var count = Object.keys(success_data).length;

                    if(count > 0)
                    {
                        Swal.fire('Amaran!','Tebus sudah dibuat sila tekan butang batal!','error');
                        $("#terima_transaksi").prop('disabled', false);

                        adadah = true;
                    }
                }
            });

            if(adadah == true)
            {
                return false;
                event.preventDefault();
            }

            let separuhla = parseFloat($('#basic-separuh').text());
            let pinjamanbaru = $('#bakipinjaman').val();

            if(separuhla <= 10)
            {
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire('Amaran!','Margin Pembiayaan kurang daripada 10%!','error');
                return false;
            }

            if(separuhla >= 80)
            {
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire('Amaran!','Margin Pembiayaan lebih daripada 80%!','error');
                return false;
            }

            if($('#perludibayar').val() < (parseFloat($('#bayaran').val()) + parseFloat($('#jumlahupah').val())))
            {
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire('Amaran!','Jumlah bayaran kurang daripada jumlah yang perlu dibayar!','error');
                return false;
            }


            let maxbayaran = totalmarhun * 0.1;

            if($('#bakipinjaman').val() < maxbayaran || $('#bakipinjaman').val() < 50){
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    `Baki margin pinjaman tidak boleh kurang 10% daripada nilai marhun \n [ RM ${totalmarhun.toFixed(2)} x 10% = RM ${maxbayaran.toFixed(2)} ]`,
                    'error'
                )
                return false;
            }

            //checked box
            var checkboxes = document.querySelectorAll('input[type="checkbox"]');
            var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
            if (checkedOne == false) {
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    'Sila tick salah satu marhun!',
                    'error'
                )
                return false;
            }

            if(separuhla > 75 && separuhla <= 80){

                const swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                    buttonsStyling: false
                });

                swalWithBootstrapButtons.fire({
                    title: 'Dapatkan Pengesahan Khazanah',
                    text: "Tetapan margin melebihi 75% untuk Khazanah!",
                    icon: 'info',
                    showCancelButton: true,
                    confirmButtonText: 'Hantar',
                    cancelButtonText: 'Batal',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {

                        let nm = parseFloat($('#nilai_marhun_total_fix').text().replace(/[^0-9.-]+/g,""));let ber = $('#berat_marhun_total').text();let marg = separuhla;
                        // let komen = "Pembiayaan Melebihi Margin 70%|" + nm + "|" + ber +  "|" + marg + "| Tebus Separuh";
                        let status = "[Tebus Separuh] Pembiayaan Melebihi Margin " + pinjaman_teller + "%";
                        let jumpinjam = $('#bakipinjaman').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) {
                            console.log(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(){
                                        gadaiseparuhfunc();
                                    });

                                }
                                else if(data.kelulusan == 'batal')
                                {
                                    Swal.fire({
                                        icon: 'warning',
                                        title: 'Telah Dibatalkan',
                                        text: `Komen : ${data.komen}`
                                    }).then(function(){
                                        return false;
                                    });
                                }
                            }



                        });


                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                        $("#terima_transaksi").prop('disabled', false);
                        swalWithBootstrapButtons.fire(
                            'Gagal',
                            'Gagal mendapatkan kelulusan khazanah',
                            'error'
                        )
                    }
                });
                event.preventDefault();
                return false;

            }else if(pinjamanbaru >= 10000){

                    const swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                    buttonsStyling: false
                    });

                    let text = '';
                    if(pinjamanbaru >= 10000)
                    {
                        text  = 'Pembiayaan melebihi RM 10,000!';
                    }


                    swalWithBootstrapButtons.fire({
                    title: 'Dapatkan Pengesahan Operasi',
                    text: text,
                    icon: 'info',
                    showCancelButton: true,
                    confirmButtonText: 'Hantar',
                    cancelButtonText: 'Batal',
                    reverseButtons: true
                    }).then((result) => {
                    if (result.isConfirmed) {

                        let nm = parseFloat($('#nilai_marhun_total_fix').text().replace(/[^0-9.-]+/g,""));let ber = $('#berat_marhun_total').text();let marg = separuhla;
                        let komen = '';
                        if(pinjamanbaru >= 10000)
                        {
                            komen = "[Tebus Separuh] Pembiayaan Melebihi RM 10,000";
                        }

                        let jumpinjam = $('#bakipinjaman').val();
                        let status = komen;
                        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(){
                                        gadaiseparuhfunc();
                                        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){
                        $("#terima_transaksi").prop('disabled', false);
                        swalWithBootstrapButtons.fire(
                            'Gagal',
                            'Gagal mendapatkan kelulusan operasi',
                            'error'
                        )
                    }
                    });
                    event.preventDefault();
                    return false;

                }else if(separuhla > 80){
                    $("#terima_transaksi").prop('disabled', false);
                    Swal.fire(
                        'Amaran!',
                        'Pinjaman Haruslah Dalam Lingkungan 80%!',
                        'error'
                    )
                    return false;
                }


                gadaiseparuhfunc();

            /////////////
            //End File//
            ///////////

        }else if($('#sltjenistebus').find(":selected").val() == 'P'){
            let pinjamanbaru = $('#hargapembiayaansemasa').val();
            let jenisbayarantebus = '';
            if(hargajualan == ''){
                jenisbayarantebus = "nottawarruq";
            }else if (hargajualan != ''){
                jenisbayarantebus = "tawarruq";
            }

            let adadah = false;
            let komuditiblock = false;
            $.ajax({
                method:'get',
                url: api + '/api/komuditi/check',
                async:false,
                success:function(komoditi){
                    var check_komuditi = Object.keys(komoditi).length;
                    if(check_komuditi == 0){
                        $("#terima_transaksi").prop('disabled', false);
                        Swal.close();
                        Swal.fire({
                            icon: 'error',
                            title: 'Unit Komuditi Berbaki Minumum',
                            text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                        });
                        komuditiblock = true;
                        event.preventDefault();
                        return false;
                    }else{
                        if(Number(komoditi['unit_komuditi']) < pinjaman_baru){
                            $("#terima_transaksi").prop('disabled', false);
                            Swal.close();
                            Swal.fire({
                                icon: 'error',
                                title: 'Baki Unit Komuditi Tidak Mencukupi',
                                text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                            });
                            komuditiblock = true;
                            event.preventDefault();
                            return false;
                        }
                    }
                }
            });
            if(komuditiblock){
                event.preventDefault();
                return false;
            }

            $.ajax({
                method:'get',
                datatype: 'json',
                url: api + '/api/listpenebusanhistory/' + kodcaw,
                async:false,
                data: { 'norujukan' : norujukan },
                success:function(success_data){
                    var count = Object.keys(success_data).length;

                    if(count > 0)
                    {
                        Swal.fire('Amaran!','Tebus sudah dibuat sila tekan butang batal!','error');
                        $("#terima_transaksi").prop('disabled', false);

                        adadah = true;
                    }
                }
            });

            if(adadah == true)
            {
                return false;
                event.preventDefault();
            }


            if( $('#tambahpinjam').val() <=  0 || $('#tambahpinjam').val() === ''){
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    'Amaun hendaklah melebihi daripada 0',
                    'error'
                )
                return false;
            }


            if(parseFloat($('#basic-addon2').text()) > 75 && parseFloat($('#basic-addon2').text()) <= 80){
                const swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                    buttonsStyling: false,
                });

                swalWithBootstrapButtons.fire({
                    title: 'Dapatkan Pengesahan Khazanah',
                    text: "Tetapan margin melebihi 75% untuk Khazanah!",
                    icon: 'info',
                    showCancelButton: true,
                    confirmButtonText: 'Hantar',
                    cancelButtonText: 'Batal',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {

                        let nm = parseFloat($('#nilai_marhun_total_fix').text().replace(/[^0-9.-]+/g,""));let ber = $('#berat_marhun_total').text();let marg = $('#basic-hargaemas').text();
                        // let komen = "Pembiayaan Melebihi Margin 70%|" + nm + "|" + ber +  "|" + marg + "| Tambah Pinjaman";
                        let status = "[Tambah Pinjaman] Pembiayaan Melebihi Margin " + pinjaman_teller + "%";
                        let jumpinjam = $('#hargapembiayaansemasa').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) {

                            console.log(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(){
                                        tambahpinjamanfunc();
                                    });

                                }
                                else if(data.kelulusan == 'batal')
                                {
                                    Swal.fire({
                                        icon: 'warning',
                                        title: 'Telah Dibatalkan',
                                        text: `Komen : ${data.komen}`
                                    }).then(function(){
                                        return false;
                                    });
                                }
                            }



                        });


                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                        $("#terima_transaksi").prop('disabled', false);
                        swalWithBootstrapButtons.fire(
                            'Gagal',
                            'Gagal mendapatkan kelulusan khazanah',
                            'error'
                        )
                    }
                });
                event.preventDefault();
                return false;

            }else if( pinjamanbaru >= 10000){

                const swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                    buttonsStyling: false
                });

                let text = '';
                if(pinjamanbaru >= 10000)
                {
                    text  = 'Pembiayaan melebihi RM 10,000!';
                }


                swalWithBootstrapButtons.fire({
                    title: 'Dapatkan Pengesahan Operasi',
                    text: text,
                    icon: 'info',
                    showCancelButton: true,
                    confirmButtonText: 'Hantar',
                    cancelButtonText: 'Batal',
                    reverseButtons: true
                }).then((result) => {
                    if (result.isConfirmed) {

                        let nm = parseFloat($('#nilai_marhun_total_fix').text().replace(/[^0-9.-]+/g,""));let ber = $('#berat_marhun_total').text();let marg = $('#basic-hargaemas').text();
                        let komen = '';
                        if(pinjamanbaru >= 10000)
                        {
                            komen = "[Tambah Pinjaman] Pembiayaan Melebihi RM 10,000";
                        }

                        let status = komen;
                        let jumpinjam = $('#hargapembiayaansemasa').val().replace(/[^0-9.-]+/g,"");
                        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(){
                                        tambahpinjamanfunc();
                                        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){
                        $("#terima_transaksi").prop('disabled', false);
                        swalWithBootstrapButtons.fire(
                            'Gagal',
                            'Gagal mendapatkan kelulusan operasi',
                            'error'
                        )
                    }
                });
                event.preventDefault();
                return false;

            }else if(parseFloat($('#basic-addon2').text()) > 80){
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire(
                    'Amaran!',
                    'Pinjaman Haruslah Dalam Lingkungan 80%!',
                    'error'
                )
                return false;

            }

            tambahpinjamanfunc();
        }else if($('#sltjenistebus').find(":selected").val() == 'U'){

            var urlroute = '{{ route("resit.advansur", ":id") }}';
            urlroute = urlroute.replace(':id', norujukan);

            var nopelanggan = "{{ $gadai['nopelanggan'] }}";
            var prkod = "{{ $gadai['prkod'] }}";
            var jenistebus = $('#sltjenistebus').find(":selected").val();
            var jbg = "{{ $gadai['tempoh'] }}";
            var kadarupah = "{{ $gadai['kadarupah'] }}";
            var nilai_marhun = "{{ $gadai['nilaimarhun']}}";
            var pinjaman = "{{ $gadai['pinjaman']}}";
            var ansuran = 0;
            var addpinjaman = 0;
            var bakipinjaman = Number(parseFloat($('#perludibayar').val().replace(/[^0-9.-]+/g,"")).toFixed(2));
            var bakiupah = Number(parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,"")).toFixed(2));
            var historygadaian = 0;
            var marhun = "{{ $gadai['marhun'] }}";
            var nowakil = nw;

            var minimum_bayaran = (percent_mora/100)*bakiupah;
            if(bakipinjaman >= minimum_bayaran){
                if(bakipinjaman > bakiupah){
                    $("#terima_transaksi").prop('disabled', false);
                    Swal.fire({
                        icon: 'error',
                        title: 'Bayaran Melebihi Dari Maksima',
                        text: 'Bayaran Maksima Adalah Upah Semasa'
                    });
                    event.preventDefault();
                    return false;
                }else{
                    $.ajax({
                        method:'post',
                        url: api + '/api/ansuran/create/' + kodcaw,
                        datatype: 'json',
                        data:{
                            'norujukan' : norujukan,
                            'nopelanggan' : nopelanggan,
                            'nilaimarhun' : nilai_marhun,
                            'pinjaman' : pinjaman,
                            'kadarupah' : kadarupah,
                            'glcode' : "1000/010",
                            'upahsebenar' : bakiupah,
                            'upahdibayar' : bakipinjaman,
                            'teller' : teller,
                            'prkod' : prkod,
                            'jbg' : jbg,
                            'nowakil' : 0,
                            'hubungan' : 0,
                            'historygadaian' : norujukan
                        },
                        success:function(data){
                            $.ajax({
                                method: 'put',
                                url: "{{ route('alirantunai.advansur') }}",
                                async:false,
                                data:{
                                    'norujukan' : norujukan,
                                    "_token": "{{ csrf_token() }}"
                                },
                                success:function(data){
                                    console.log(data);
                                }, error: function(xhr, status, error) {
                                            var err = eval("(" + xhr.responseText + ")");
                                            alert(xhr.responseText);
                                }
                            });

                            Swal.fire({
                                icon: 'success',
                                title: 'Berjaya!',
                                text: 'Pembayaran Upah Berjaya',
                            }).then(function() {
                                window.open(urlroute, '_blank');
                                window.location.replace("{{  route('customer_info') }}");
                            })
                        }
                    })
                }
            }else{
                $("#terima_transaksi").prop('disabled', false);
                Swal.fire({
                    icon: 'error',
                    title: 'Bayaran Kurang Dari Minimum',
                    text: 'Bayaran minimum adalah '+percent_mora+' %'
                });
                event.preventDefault();
                return false;
            }


        }else if($('#sltjenistebus').find(":selected").val() == 'AT'){

            let nilaimargin = $('#txtlebihanmargin').val();
            var keuntungan = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
            // var pinjamasal = parseFloat($('#pinjamanasal').val().replace(/[^0-9.-]+/g,""));

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

            var pinjaman_baru = parseFloat($('#pinjamanbaru').val().replace(/[^0-9.-]+/g,""));

            let lebihanmargin = parseFloat((nilaimargin) ? nilaimargin : 0);
            total = (jenisAT != 'hargalama') ? (keuntungan + lebihanmargin) : keuntungan;

            var marginsemasa = (jenisAT == 'hargalama') ? pinjaman_baru/nm * 100 : pinjaman_baru/nmsemasa * 100;
            
            let texting = (jenisAT != 'hargalama') ? 'Bayaran harus melebihi keuntungan dan jumlah lebihan margin' : 'Bayaran harus melebihi keuntungan';

            if(parseFloat($('#perludibayarAT').val().replace(/[^0-9.-]+/g,"")) < parseFloat(total.toFixed(2))){
                Swal.fire({
                    icon: 'error',
                    title: 'Ralat Bayaran!',
                    text: texting
                });
                event.preventDefault();
                return false;
            }

            var duitpelanggan = parseFloat($('#duitPelanggan').val().replace(/[^0-9.-]+/g,""));
            if(isNaN(duitpelanggan)) duitpelanggan = 0;

            if(Number(duitpelanggan) < parseFloat($('#perludibayarAT').val())){
                Swal.fire('Amaran!','Duit Pelanggan haruslah diisi melebihi perlu dibayar!','error');
                $("#terima_transaksi").prop('disabled', false);

                event.preventDefault();
                return false;
            }

            $.ajax({
                method:'get',
                url: api + '/api/komuditi/check',
                success:function(komoditi){
                    var check_komuditi = Object.keys(komoditi).length;
                    if(check_komuditi == 0){
                        $("#terima_transaksi").prop('disabled', false);
                        Swal.fire({
                            icon: 'error',
                            title: 'Unit Komuditi Berbaki Minumum',
                            text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                        });
                        event.preventDefault();
                        return false;
                    }else{
                        if(Number(komoditi['unit_komuditi']) < pinjaman_baru){
                            $("#terima_transaksi").prop('disabled', false);
                            Swal.fire({
                                icon: 'error',
                                title: 'Baki Unit Komuditi Tidak Mencukupi',
                                text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komuditi'
                            });
                            event.preventDefault();
                            return false;
                        }else{
                            if(marginsemasa < 10)
                            {
                                $("#terima_transaksi").prop('disabled', false);
                                Swal.fire('Amaran!','Margin Pembiayaan kurang daripada 10%!','error');
                                return false;
                            }

                            // if(marginsemasa > 80)
                            // {
                            //     $("#terima_transaksi").prop('disabled', false);
                            //     Swal.fire('Amaran!','Margin Pembiayaan lebih daripada 80%!','error');
                            //     return false;
                            // }

                            if((marginsemasa > 75 && marginsemasa <= 80) && jenisAT != 'hargalama'){

                                const swalWithBootstrapButtons = Swal.mixin({
                                    customClass: {
                                        confirmButton: 'btn btn-success',
                                        cancelButton: 'btn btn-danger'
                                    },
                                    buttonsStyling: false
                                });

                                swalWithBootstrapButtons.fire({
                                    title: 'Dapatkan Pengesahan Khazanah',
                                    text: "Tetapan margin melebihi 75% untuk Khazanah!",
                                    icon: 'info',
                                    showCancelButton: true,
                                    confirmButtonText: 'Hantar',
                                    cancelButtonText: 'Batal',
                                    reverseButtons: true
                                }).then((result) => {
                                    if (result.isConfirmed) {

                                        let nm = nmsemasa;let ber = $('#berat_marhun_total').text();let marg = marginsemasa;
                                        // let komen = "Pembiayaan Melebihi Margin 70%|" + nmsemasa + "|" + ber +  "|" + marg + "| Pembiayaan Semula";
                                        let status = "[Pembiayaan Semula] Pembiayaan Melebihi Margin " + pinjaman_teller + "%";
                                        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" : pinjaman_baru,
                                                "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(){
                                                        gadaiautotawarruq();
                                                    });

                                                }
                                                else if(data.kelulusan == 'batal')
                                                {
                                                    Swal.fire({
                                                        icon: 'warning',
                                                        title: 'Telah Dibatalkan',
                                                        text: `Komen : ${data.komen}`
                                                    }).then(function(){
                                                        return false;
                                                    });
                                                }
                                            }



                                        });


                                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                                        $("#terima_transaksi").prop('disabled', false);
                                        swalWithBootstrapButtons.fire(
                                            'Gagal',
                                            'Gagal mendapatkan kelulusan khazanah',
                                            'error'
                                        )
                                    }
                                });
                                event.preventDefault();
                                return false;

                            }else if(pinjaman_baru >= 10000){

                                const swalWithBootstrapButtons = Swal.mixin({
                                customClass: {
                                    confirmButton: 'btn btn-success',
                                    cancelButton: 'btn btn-danger'
                                },
                                buttonsStyling: false
                                });

                                let text = '';
                                if(pinjaman_baru >= 10000)
                                {
                                    text  = 'Pembiayaan melebihi RM 10,000!';
                                }


                                swalWithBootstrapButtons.fire({
                                title: 'Dapatkan Pengesahan Operasi',
                                text: text,
                                icon: 'info',
                                showCancelButton: true,
                                confirmButtonText: 'Hantar',
                                cancelButtonText: 'Batal',
                                reverseButtons: true
                                }).then((result) => {
                                    if (result.isConfirmed) {

                                        let nm = parseFloat($('#nilai_marhun_total_fix').text().replace(/[^0-9.-]+/g,""));let ber = $('#berat_marhun_total').text();let marg = marginsemasa;
                                        let komen = '';
                                        if(pinjaman_baru >= 10000)
                                        {
                                            komen = "[Pembiayaan Semula] Pembiayaan Melebihi RM 10,000";
                                        }
                                        let status = komen;

                                        let jumpinjam = $('#bakipinjaman').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" : pinjaman_baru,
                                                "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(){
                                                        gadaiautotawarruq();
                                                        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){
                                        $("#terima_transaksi").prop('disabled', false);
                                        swalWithBootstrapButtons.fire(
                                            'Gagal',
                                            'Gagal mendapatkan kelulusan operasi',
                                            'error'
                                        )
                                    }
                                });
                                event.preventDefault();
                                return false;

                            }else if(marginsemasa > 80){

                                
                                // $("#terima_transaksi").prop('disabled', false);
                                // Swal.fire(
                                //     'Amaran!',
                                //     'Pinjaman Haruslah Dalam Lingkungan 80%!',
                                //     'error'
                                // )
                                // return false;
                            }

                            gadaiautotawarruq(jenisAT);
                        }
                    }
                }
            });

            /////////////
            //End File//
            ///////////
        }

    //Bayaran Semua function end file
    }

    function gadaiautotawarruq()
    {
        var jenisbayarantebus = '';
        if(hargajualan == '')
        {
            jenisbayarantebus = "nottawarruq";
        }
        else if (hargajualan != ''){
            jenisbayarantebus = "tawarruq";
        }

        let jeniskeuntungan = (tagbaru == 1) ? 'onepercent' : 'asal';
        var nopelanggan = "{{ $gadai['nopelanggan'] }}";
        var jenistebus = 'AT';
        var jbg = "{{ $gadai['tempoh'] }}";
        var kadarupah = "{{ $gadai['kadarupah'] }}";
        var nilai_marhun_lama = parseFloat("{{ $gadai['nilaimarhun'] }}");
        var nilai_marhun = parseFloat("{{ $nilaihargasemasa }}");
        var pinjamanbaru = $('#pinjamanbaru').val().replace(/[^0-9.-]+/g,"");
        var ansuran = 0;
        var addpinjaman = 0;
        var bakiupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
        var bakipinjaman = parseFloat($('#hargapembiayaansemasa').val().replace(/[^0-9.-]+/g,"")) + bakiupah;

        var historygadaian = "{{ $gadai['norujukan'] }}";
        var marhun = "{{ $gadai['marhun'] }}";
        var noic = "{{ $gadai['nokp'] }}";
        var total_berat = parseFloat("{{ $gadai['berat'] }}");
        var pinjaman = parseFloat("{{ $gadai['pinjaman']}}");
        var kuantiti_marhun = Number("{{sizeof($marhun)}}");
        var nowakil = nw;
        var perludibayar = parseFloat($('#perludibayarAT').val().replace(/[^0-9.-]+/g,""));
        var bayaranpelanggan = parseFloat($('#duitPelanggan').val());
        var bakipelanggan = parseFloat($('#bakiPelanggan').val().replace(/[^0-9.-]+/g,""));

        var kadarupahbaru = 0;
        // if(nilai_marhun > 0 && nilai_marhun < 400.99){
        //     kadarupahbaru = 1.20/100;
        // }else if(nilai_marhun >= 401 && nilai_marhun < 2000.99){
        //     kadarupahbaru = 1.50/100;
        // }else if(nilai_marhun >= 2001 ){
        //     kadarupahbaru = 1.70/100;
        // }

        let nilaibaru = (jenisAT == 'hargalama') ? nilai_marhun_lama : nilai_marhun;

        $.ajax({
            method:'GET',
            url: api + '/api/kadarujrah',
            async:false,
            data:{
                'nilaimarhun' : nilaibaru,
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            success:function(data){
                kadarupahbaru = data;
            }
        });


        // var keuntungan_sebulan = pinjamanbaru * kadarupahbaru;
        // var keuntungan_6bln = keuntungan_sebulan * 6;
        // console.log('pelangagan:', bayaranpelanggan,bakipelanggan);
        // console.log(nilaibaru,noic,pinjamanbaru,kadarupahbaru,total_berat,marhun,kuantiti_marhun,perludibayar,jenisAT);
        // return;
        $.ajax({
            method:"GET",
            url: "{{ route('tebus.autotawarruq') }}",
            data:{
                //yang lama
                "norujukan" : norujukan,
                "nopelanggan" : nopelanggan,
                "jenistebus" : jenistebus,
                "jbg" : jbg,
                "kadarupah" : kadarupah,
                "nilai_marhun" : nilai_marhun_lama,
                "pinjaman_lama" : pinjaman,
                "ansuran" : ansuran,
                "addpinjaman" : addpinjaman,
                "bakipinjaman" : bakipinjaman,
                "bakiupah" : bakiupah,
                "historygadaian" : historygadaian,
                "marhun" : marhun,
                "nowakil" : nowakil,
                "jenisbayarantebus" : jenisbayarantebus,
                "teller" : teller,
                "jeniskeuntungan" : jeniskeuntungan,

                //yang baru
                "noic" : noic,
                "total_nilai_marhun" : nilaibaru,
                "pinjaman" : pinjamanbaru,
                "kadarkeuntungan" : kadarupahbaru,
                // "keuntungan_6bln" : keuntungan_6bln,
                // "keuntungan_sebulan" : keuntungan_sebulan,
                "total_berat" : total_berat,
                "marhun_detail" : marhun,
                "kuantiti_marhun" : kuantiti_marhun,
                "jenisAT" : jenisAT,
                "totalbayaran" : perludibayar,
                "bayaran" : bayaranpelanggan,
                "bakipelanggan" : bakipelanggan,

            },
            success:function(success_data){

                var urlroute = '{{ route("resit.autotawarruq", ":id") }}';
                urlroute = urlroute.replace(':id', norujukan);
                if(success_data == 'success'){
                    Swal.fire(
                        'Berjaya!',
                        'Penyelesaian Pembiayaan Semula Berjaya',
                        'success'
                    ) .then(function() {
                        window.open(urlroute, '_blank');
                        window.location.replace("{{  route('customer_info') }}");
                    })
                }else{
                    Swal.fire(
                        'Tidak Berjaya!',
                        'Penyelesaian Pembiayaan Semula Tidak Berjaya!',
                        'error'
                    ).then(function(){
                        window.location.replace("{{  route('customer_info') }}");
                    });
                }

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

    function gadaiseparuhfunc()
    {
        let jenisbayarantebus = '';

        if(hargajualan == '')
        {
            jenisbayarantebus = "nottawarruq";
        }
        else if (hargajualan != ''){
            jenisbayarantebus = "tawarruq";
        }


        var sumnilaimarhun = 0;
        var sumberat = 0;
        var marhun = "{{ $gadai['marhun'] }}";

        var test = marhun.split(",");

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

        let countArrayError = 0;

        for (let i = test.length - 1; i >= 0; i--) {
            let shouldRemove = false;

            for (let j = 0; j < array_marhun.length; j++) {
                if (test[i].includes(array_marhun[j])) {
                    shouldRemove = true;
                    break;
                }
            }

            if (shouldRemove) {
                test.splice(i, 1);
                countArrayError++;

                if (countArrayError === array_marhun.length) {
                    break;
                }
            }
        }



        var marhun_baru = test.join(", ");

        $.each( array_berat, function( index, value ) {
            sumberat += parseFloat(value);
        });

        var jenistebus = $('#sltjenistebus').find(":selected").val();
        var nopelanggan = "{{ $gadai['nopelanggan'] }}";
        var jbg = "{{ $gadai['tempoh'] }}";
        var kadarupah = "{{ $gadai['kadarupah'] }}";
        var nilai_marhun_lama = parseFloat("{{ $gadai['nilaimarhun'] }}");
        var nilai_marhun = parseFloat("{{ $nilaihargasemasa }}") - sumnilaimarhun;
        var pinjamanbaru = $('#bakipinjaman').val().replace(/[^0-9.-]+/g,"");
        var ansuran = 0;
        var addpinjaman = 0;
        var bakipinjaman = $('#perludibayar').val().replace(/[^0-9.-]+/g,"");
        var bakiupah = $('#jumlahupah').val().replace(/[^0-9.-]+/g,"");
        var historygadaian = "{{ $gadai['norujukan'] }}";
        var marhun = "{{ $gadai['marhun'] }}";
        var noic = "{{ $gadai['nokp'] }}";
        var total_berat = parseFloat("{{ $gadai['berat'] }}") - sumberat;
        var pinjaman = parseFloat("{{ $gadai['pinjaman']}}");
        var marhun_detail = marhun_baru;
        var kuantiti_marhun = Number("{{sizeof($marhun)}}") - array_recno.length;
        var nowakil = nw;


        var duitpelanggan = $('#duitPelanggan').val().replace(/[^0-9.-]+/g,"");
        var bakipelanggan =  $('#bakiPelanggan').val().replace(/[^0-9.-]+/g,"");


        if(Number(duitpelanggan) < Number(bakipinjaman)){
            Swal.fire('Amaran!','Duit Pelanggan haruslah diisi melebihi perlu dibayar!','error');
            $("#terima_transaksi").prop('disabled', false);

            event.preventDefault();
            return false;
        }

        var kadarupahbaru = 0;

        // if(nilai_marhun > 0 && nilai_marhun < 400.99){
        //     kadarupahbaru = 1.2/100;
        // }else if(nilai_marhun >= 401 && nilai_marhun < 2000.99){
        //     kadarupahbaru = 1.50/100;
        // }else if(nilai_marhun >= 2001 ){
        //     kadarupahbaru = 1.70/100;
        // }

        let nilaibaru = (jenisAT == 'hargalama') ? nilai_marhun_lama : nilai_marhun;

        $.ajax({
            method:'GET',
            url: api + '/api/kadarujrah',
            async:false,
            data:{
                'nilaimarhun' : nilaibaru,
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            success:function(data){
                kadarupahbaru = data;
            }
        });


        $.ajax({
            method:"GET",
            url: "{{ route('tebus.separuh') }}",
            data:{
                //yang lama
                "norujukan" : norujukan,
                "nopelanggan" : nopelanggan,
                "jenistebus" : jenistebus,
                "jbg" : jbg,
                "kadarupah" : kadarupah,
                "nilai_marhun" : nilai_marhun_lama,
                "pinjaman_lama" : pinjaman,
                "ansuran" : ansuran,
                "addpinjaman" : addpinjaman,
                "bakipinjaman" : bakipinjaman,
                "bakiupah" : bakiupah,
                "historygadaian" : historygadaian,
                "marhun" : marhun,
                "nowakil" : nowakil,
                "arrayrecno" : array_recno,
                "jenisbayarantebus" : jenisbayarantebus,
                "jeniskeuntungan" : 'onepercent',
                "teller" : teller,
                "bayaran" : duitpelanggan,
                "bakipelanggan" : bakipelanggan,


                //yang baru
                "noic" : noic,
                "total_nilai_marhun" : nilai_marhun,
                "pinjaman" : pinjamanbaru,
                "kadarkeuntungan" : kadarupahbaru,
                "total_berat" : total_berat,
                "marhun_detail" : marhun_detail,
                "kuantiti_marhun" : kuantiti_marhun

            },
            success:function(success_data){

                var urlroute = '{{ route("resit.tebusseparuh", ":id") }}';
                urlroute = urlroute.replace(':id', norujukan);
                Swal.fire(
                    'Berjaya!',
                    'Tebus Sebahagian Berjaya',
                    'success'
                ) .then(function() {
                    window.open(urlroute, '_blank');
                    window.location.replace("{{  route('customer_info') }}");
                })
            },error: function (request, status, error) {
                console.log(request.responseText);
            }
        });
    }

    function tambahpinjamanfunc()
    {
        let jenisbayarantebus = '';
        if(hargajualan == ''){
            jenisbayarantebus = "nottawarruq";
        }else if (hargajualan != ''){
            jenisbayarantebus = "tawarruq";
        }

        var nopelanggan = "{{ $gadai['nopelanggan'] }}";
        var jenistebus = $('#sltjenistebus').find(":selected").val();
        var jbg = "{{ $gadai['tempoh'] }}";
        var kadarupah = "{{ $gadai['kadarupah'] }}";
        var nilai_marhun = "{{ $nilaihargasemasa }}";
        var pinjaman_lama = "{{ $gadai['bakipjm'] }}";
        var pinjaman = parseFloat($('#pinjamanbaru').val().replace(/[^0-9.-]+/g,""));
        var ansuran = 0;
        var addpinjaman = $('#tambahpinjam').val() == '' ? 0 : parseFloat($('#tambahpinjam').val().replace(/[^0-9.-]+/g,""));
        var maxpinjaman = parseFloat($('#tambahpinjamsebenar').val().replace(/[^0-9.-]+/g,""));
        // var bakipinjaman = maxpinjaman - parseFloat($('#tambahpinjam').val());
        var bakiupah = $('#bayaranditerima').val().replace(/[^0-9.-]+/g,"");
        var bakipinjaman = parseFloat(pinjaman_lama) + parseFloat(bakiupah);
        var historygadaian = "{{ $gadai['norujukan'] }}";
        var marhun = "{{ $gadai['marhun'] }}";
        var total_berat = parseFloat("{{ $gadai['berat'] }}");
        var kuantiti_marhun = Number("{{sizeof($marhun)}}");
        var noic = "{{ $gadai['nokp'] }}";
        var nowakil = nw;
        
        var duitpelanggan = $('#duitPelanggan').val().replace(/[^0-9.-]+/g,"");
        var bakipelanggan =  $('#bakiPelanggan').val().replace(/[^0-9.-]+/g,"");


        if(Number(duitpelanggan) < Number(bakiupah)){
            Swal.fire('Amaran!','Duit Pelanggan haruslah diisi melebihi perlu dibayar!','error');
            $("#terima_transaksi").prop('disabled', false);

            event.preventDefault();
            return false;
        }

        var kadarupahbaru = 0;

        let nilaibaru = (jenisAT == 'hargalama') ? nilai_marhun_lama : nilai_marhun;

        $.ajax({
            method:'GET',
            url: api + '/api/kadarujrah',
            async:false,
            data:{
                'nilaimarhun' : nilaibaru,
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
            },
            success:function(data){
                kadarupahbaru = data;
            }
        });

        var keuntungan_sebulan = pinjaman * kadarupahbaru;
        var keuntungan_6bln = keuntungan_sebulan * 6;

        $.ajax({
            method:'GET',
            url: "{{ route('tambah.pinjaman') }}",
            data:{
                "nopelanggan" : nopelanggan,
                "jenistebus" : jenistebus,
                "jbg" : jbg,
                "kadarupah" : kadarupah,
                "nilai_marhun" : nilai_marhun,
                "pinjaman" : pinjaman,
                "pinjaman_lama" : pinjaman_lama,
                "ansuran" : ansuran,
                "addpinjaman" : addpinjaman,
                "bakipinjaman" : bakipinjaman,
                "bakiupah" : bakiupah,
                "historygadaian" : historygadaian,
                "marhun" : marhun,
                "kuantiti_marhun" : kuantiti_marhun,
                "total_berat" : total_berat,
                "kadarkeuntungan" : kadarupahbaru,
                "keuntungan_6bln" : keuntungan_6bln,
                "keuntungan_sebulan" : keuntungan_sebulan,
                "noic" : noic,
                "norujukan" : norujukan,
                "jenisbayarantebus" : jenisbayarantebus,
                "jeniskeuntungan" : 'onepercent',
                "teller" : teller,
                "bayaran" : duitpelanggan,
                "bakipelanggan" : bakipelanggan,
                "nowakil" : nowakil,

            },
            success:function(success_data){

                var urlroute = '{{ route("resit.tambahpinjam", ":id") }}';
                urlroute = urlroute.replace(':id', norujukan);

                Swal.fire(
                    'Berjaya!',
                    'Tambah Pinjaman Berjaya!',
                    'success'
                ).then(function() {
                    window.open(urlroute, '_blank');
                    window.location.replace("{{  route('customer_info') }}");
                })
            },error: function (request, status, error) {
            console.log(request.responseText);
            }
        });

    /////////////
    //End File//
    ///////////
    }

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

if(wakil === null || wakil === '')
{
    Swal.fire(
        'Amaran!',
        'Sila masukkan nilai di dalam kotak wakil!',
        'error'
    )

    return false;
}

var patternregex = /\s+|[-,\/]/g;

wakil = wakil.replace(patternregex,"").toUpperCase();

if(wakil.length <= 12 || (wakil.substr(-1) == '*' && wakil.length == 13))
{
    $.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: 'Daftar',
                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 dan Passport',
        text: 'mestilah tidak melebihi dan kurang daripada 13 patah perkataan termasuk (*)'
    });
}

}

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();

let boolnowakil = false;let boolnama = false;let boolalamat = false;let booltelefon = false;let boolnota = false;let boolnokp = false;

if(nowakil === null || nowakil === '')
{
    $("[name='errornowakil']").show();
    $("[name='errornowakil']").text("*No wakil tidak dijana lagi!");
    $("[name='nowakil']").addClass('is-invalid');

    boolnowakil = true;
}else{
    $("[name='errornowakil']").hide();
    $("[name='nowakil']").removeClass('is-invalid');

    boolnowakil = false;
}

if(nama === null || nama === '')
{
    $("[name='errornamawakil']").show();
    $("[name='errornamawakil']").text("*Isikan nama dalam kotak!");
    $("[name='namawakil']").addClass('is-invalid');

    boolnama = true;
}else{
    $("[name='errornamawakil']").hide();
    $("[name='namawakil']").removeClass('is-invalid');

    boolnama = false;
}

if(alamat === null || alamat === '')
{
    $("[name='erroralamatwakil']").show();
    $("[name='erroralamatwakil']").text("*Isikan alamat dalam kotak!");
    $("[name='alamatwakil']").addClass('is-invalid');

    boolalamat = true;
}else{
    $("[name='erroralamatwakil']").hide();
    $("[name='alamatwakil']").removeClass('is-invalid');

    boolalamat = false;
}

if(telefon === null || telefon === '')
{
    $("[name='errornotelwakil']").show();
    $("[name='errornotelwakil']").text("*Isikan telefon dalam kotak!");
    $("[name='notelwakil']").addClass('is-invalid');

    booltelefon = true;
}else{
    $("[name='errornotelwakil']").hide();
    $("[name='notelwakil']").removeClass('is-invalid');

    booltelefon = false;
}

if(nota === null || nota === '')
{
    $("[name='errornotawakil']").show();
    $("[name='errornotawakil']").text("*Isikan nota dalam kotak!");
    $("[name='notawakil']").addClass('is-invalid');

    boolnota = true;
}else{
    $("[name='errornotawakil']").hide();
    $("[name='notawakil']").removeClass('is-invalid');

    boolnota = false;
}

if(nokp === null || nokp === '')
{
    $("[name='errornokpwakil']").show();
    $("[name='errornokpwakil']").text("*Isikan nokp dalam kotak!");
    $("[name='nokpwakil']").addClass('is-invalid');

    boolnokp = true;
}else{
    $("[name='errornokpwakil']").hide();
    $("[name='nokpwakil']").removeClass('is-invalid');

    boolnokp = false;
}


if(boolnowakil == false && boolnama == false && boolalamat == false && booltelefon == false && boolnota == false && boolnokp == false)
{
    $.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);
        }
    });

    return true;

}else{
    return false;
}


}

$('#WakilModal').on('hidden.bs.modal', function (e) {

$("[name='errornowakil']").hide();
$("[name='nowakil']").removeClass('is-invalid');

$("[name='errornamawakil']").hide();
$("[name='namawakil']").removeClass('is-invalid');

$("[name='erroralamatwakil']").hide();
$("[name='alamatwakil']").removeClass('is-invalid');

$("[name='errornotelwakil']").hide();
$("[name='notelwakil']").removeClass('is-invalid');

$("[name='errornotawakil']").hide();
$("[name='notawakil']").removeClass('is-invalid');

$("[name='errornokpwakil']").hide();
$("[name='nokpwakil']").removeClass('is-invalid');

$(this).find(".invalid-feedback").hide();

});


function daftarfunction(id)
{
let kodcaw = "{{ Auth::user()->cawangan }}";

$('#nokpwakil').val(id);

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

        $('#namawakil').val('');
        $('#alamatwakil').val('');
        $('#notelwakil').val('');

        var size =  Object.keys(data).length;

        if(size > 0)
        {
            $('#namawakil').val(data['nama']);
            $('#alamatwakil').val(data['alamat1']);
            $('#notelwakil').val(data['telefon']);
            $('#nopelangganwakil').val(data['nopelanggan']);
        }

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

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

                Swal.close();
                $('#WakilModal').modal();

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

                Swal.fire({
                    title: 'Punyai Ralat dalam API wakil...',
                    icon: 'error'
                });

            }
        })

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

Swal.fire({
title: 'Memuatkan...',
allowEscapeKey : false,
allowOutsideClick: false,
didOpen: function () {
    Swal.showLoading()
}
});
}

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

function pembatalanbalik()
{
$.ajax({
    method:'get',
    url: api + '/api/polis/get',
    datatype:'json',
    data:{
        'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
        'norujukan': norujukan
    },
    success:function(data){

        var count = Object.keys(data).length;

        if(count > 0 && data[0].tebus === 1)
        {
            $.ajax({
                method:'put',
                url: api + '/api/polis/put/',
                data: {
                    'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                    'norujukan': norujukan,
                    'tebus' : 0
                },
                success:function(data){
                    window.location.replace("{{  (Auth::user()->roles == 'pc' || Auth::user()->roles == 'ppc') ? route('khazanah.customer_info') : route('customer_info') }}");

                },
                error: function(xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(xhr.responseText);
                }
            });
        }else{
            window.location.replace("{{  (Auth::user()->roles == 'pc' || Auth::user()->roles == 'ppc') ? route('khazanah.customer_info') : route('customer_info') }}");
        }

    }
});
}

function funcexcuse(toggle){

    if(toggle){   
    let pembiayaan = parseFloat($('#hargapembiayaansemasa').val().replace(/[^0-9.-]+/g,""));
    var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
    let percentasal = parseFloat('{{ number_format($percent_asal,2) }}');
    var nilai_marhun_lama = parseFloat("{{ $gadai['nilaimarhun'] }}");
    var bakipjm = parseFloat("{{ $gadai['bakipjm'] }}");

    const swalWithBootstrapButtons = Swal.mixin({
    customClass: {
        confirmButton: 'btn btn-success',
        cancelButton: 'btn btn-danger'
    },
    buttonsStyling: false
    });

    var errortext = "[Pembiayaan Semula] Menggunakan Harga Lama & Margin Lama";

    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 = '{{ $gadai["norujukan"] }}';
            let nm = parseFloat($('#nilai_marhun_total').text().replace(/[^0-9.-]+/g,""));
            let ber = parseFloat($('#berat_marhun_total').text());
            let marg = parseFloat($('#basic-addon2').text());
            let status = errortext;
            let jumpinjam = parseFloat($('#pinjamanbaru').val().replace(/[^0-9.-]+/g,""));
            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" : nilai_marhun_lama,
                    "status" : status,
                    "jumpinjam" : bakipjm,
                    "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(){

                            jenisAT = 'hargalama';
                            $('#basic-addon2').text(percentasal);
                            $('.divlebihanmargin').hide();
                            $('#divjenisAT').show();
                            $('#perludibayarAT').val(formatter.format(jumupah));
                            // $('#divbayaranAT').hide();
                            $('#calcbayar').val(jumupah);
                            $("#perludibayarAT").prop("readonly", true);
                            $('#pinjamanbaru').val(formatter.format(pembiayaan));

                            // $(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{
    let pembiayaan = parseFloat("{{ $pembiayaanbaru }}");
    let percenthargasemasa = parseFloat('{{ number_format($percent_hargaemassemasa,2) }}');
    var jumupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
    let jumlebmargin = parseFloat('{{ ($percent_hargaemassemasa > 80) ? $bayaranlebihan : 0 }}');
    let totalbayaran = jumlebmargin + jumupah;
    $('#basic-addon2').text((percenthargasemasa > 80) ? '80.00' : percenthargasemasa);
    $('#pinjamanbaru').val(formatter.format(pembiayaan));

    jenisAT = 'none';
    $('.divlebihanmargin').show();
    $('#divjenisAT').hide();
    $('#perludibayarAT').val(formatter.format(totalbayaran));
    $('#calcbayar').val(totalbayaran);
    $("#perludibayarAT").prop("readonly", false);
    }

    return false;
}

function validateFloatKeyPressAnsuran(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value;
let keypress = evt.key;

// Split the current value by dot to check the number of decimal places
var numberParts = number.split('.');

// Check if the pressed key is a valid character for a floating-point number
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}

// Check if there is already a dot, and the pressed key is another dot
if (numberParts.length > 1 && charCode == 46) {
return false;
}

// Get the caret position in the input field
var caratPos = getSelectionStart(el);

// Get the position of the existing dot
var dotPos = el.value.indexOf(".");

// Check if the caret is after the existing dot, and there are more than 2 digits after the dot
if (caratPos > dotPos && dotPos > -1 && (numberParts[1] && numberParts[1].length > 1)) {
return false;
}

// If the last digit is not 5 or 0, disallow the input
if (numberParts[1] && numberParts[1].length === 1 && !['0', '5'].includes(keypress)) {
return false;
}

return true;
}

function validateFloatKeyPressAT(el, evt) {
let hargamarhun = parseFloat("{{ $nilaihargasemasa }}");
let tenpercent = hargamarhun * (10/100);
let pembiayaan = parseFloat($('#hargapembiayaansemasa').val().replace(/[^0-9.-]+/g,""));
let bakiupah = parseFloat($('#jumlahupah').val().replace(/[^0-9.-]+/g,""));
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value;
let pembiayaanbaru = 0;
let keypress = evt.key;
let tot;


if(!isNaN(keypress)){
tot = number.toString().replace(/[^0-9.-]+/g,"") + keypress.toString();
}

var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot
if(number.length>1 && charCode == 46){
 return false;
}

let ansuranbaru = parseFloat(tot) - parseFloat(bakiupah);

//total pembiayaan baru
pembiayaanbaru = pembiayaan - ansuranbaru;

//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}

if(parseFloat(pembiayaanbaru) <= tenpercent){
Swal.fire('Amaran!','Pembiayaan baru < 10%','error');
return false;
}

// If the last digit is not 5 or 0, disallow the input
if (number[1] && number[1].length === 1 && !['0', '5'].includes(keypress)) {
return false;
}

return true;
}

    function validateKeyPress(el, evt) {

        var charCode = (evt.which) ? evt.which : event.keyCode;
        var number = el.value;
        let keypress = evt.key;

        // Split the current value by dot to check the number of decimal places
        var numberParts = number.split('.');

        // Check if the pressed key is a valid character for a floating-point number
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        // Check if there is already a dot, and the pressed key is another dot
        if (numberParts.length > 1 && charCode == 46) {
            return false;
        }

        // Get the caret position in the input field
        var caratPos = getSelectionStart(el);

        // Get the position of the existing dot
        var dotPos = el.value.indexOf(".");

        // Check if the caret is after the existing dot, and there are more than 2 digits after the dot
        if (caratPos > dotPos && dotPos > -1 && (numberParts[1] && numberParts[1].length > 1)) {
            return false;
        }

        // If the last digit is not 5 or 0, disallow the input
        if (numberParts[1] && numberParts[1].length === 1 && !['0', '5'].includes(keypress)) {
            return false;
        }

        return true;
    }

    function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
        } else return o.selectionStart
    }

    function bayaranATfunc(e){

        let byr = $(e).val().replace(/[^0-9.-]+/g,"");
        let total = 0;
        let pdbyr = 0;
        let pembiayaanbaru = 0;
        let upah = parseFloat($('#jumlahupah').val());
        let lebihanmargin = parseFloat(($('#txtlebihanmargin').val()) ? $('#txtlebihanmargin').val() : 0);
        total = upah + lebihanmargin;

        let hargamarhun = parseFloat("{{ $nilaihargasemasa }}");
        let pembiayaan = parseFloat("{{ $pembiayaanbaru }}");
        let percenthargasemasa = parseFloat("{{ $percent_hargaemassemasa }}");

        //algorithm untuk bayaran pelanggan dan baki
        let baki = parseFloat($('#bakiPelanggan').val());
        let bayaranpelanggan = parseFloat($('#duitPelanggan').val());

        let totalpercent = 0;
        if(byr == ''){
        // $('#perludibayarAT').val(total);
        $('#pinjamanbaru').val(formatter.format(pembiayaan));
        totalpercent = (pembiayaan / hargamarhun) * 100;
        $('#basic-addon2').text(formatter.format(totalpercent.toFixed(2)));

        //baki pelanggan
        // $('#bakiPelanggan').val((0.00) );
        }else{
        // pdbyr = parseFloat(byr) + parseFloat(total);
        // $('#perludibayarAT').val(pdbyr);
        let kumpul = parseFloat(byr) - total;
        pembiayaanbaru = pembiayaan - kumpul;
        totalpercent = (pembiayaanbaru / hargamarhun) * 100;

        if(kumpul > 0){
            $('#pinjamanbaru').val(formatter.format(pembiayaanbaru));
            $('#basic-addon2').text(formatter.format(totalpercent.toFixed(2)));
        }else{
            $('#pinjamanbaru').val(formatter.format(pembiayaan));
            totalpercent = (pembiayaan / hargamarhun) * 100;
            $('#basic-addon2').text(formatter.format(totalpercent.toFixed(2)));
        }

        $('#bakiPelanggan').val('0.00');
        $('#duitPelanggan').val('');
    }

    }

    function blockbayaranAT(event){
        let value = $(event).val().replace(/[^0-9.-]+/g,"");
        let upah = parseFloat($('#jumlahupah').val());
        let pembiayaan = parseFloat("{{ $pembiayaanbaru }}");
        let pembiayaanlama = parseFloat("{{ $bakipjm }}");
        let hargamarhun = parseFloat("{{ $nilaihargasemasa }}");
        let percentlama = parseFloat(" {{ $percent_asal }} ");

        totalpercent = (pembiayaan / hargamarhun) * 100;

        let nilaimargin = $('#txtlebihanmargin').val();
        let lebihanmargin = parseFloat((nilaimargin) ? nilaimargin : 0);
        total = (jenisAT != 'hargalama') ? (upah + lebihanmargin) : upah;

        if(value == '' || value <= 0 || value < total){
            if(value == '' || value <= 0){
                Swal.fire(
                    'Tidak Berjaya!',
                    'Bayaran Tidak boleh ditinggalkan Kosong!',
                    'error'
                );
            }else if(value < total){
                Swal.fire(
                    'Tidak Berjaya!',
                    'Bayaran Tidak boleh kurang daripada RM' + formatter.format(total) + '!',
                    'error'
                );
            }

            if(jenisAT != 'hargalama'){
                $('#perludibayarAT').val(formatter.format(total));
                $('#pinjamanbaru').val(formatter.format(pembiayaan));
                $('#basic-addon2').text(formatter.format(totalpercent.toFixed(2)));
            }else{
                $('#perludibayarAT').val(formatter.format(total));
                $('#pinjamanbaru').val(formatter.format(pembiayaanlama));
                $('#basic-addon2').text(formatter.format(percentlama.toFixed(2)));
            }
        }
    }

    function funcTU(){
        elem_jenisTU.prependTo(".infotransaksi");
        $('#jenisAT').remove();
        $('#jenisA').remove();
        $('#jenisT').remove();
        $('#jenisS').remove();
        $('#jenisP').remove();

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

        $("#sltjenistebus").val('');

        $("#terima_transaksi").prop('disabled', true);



        $('#datetarikh').datepicker({
            format: 'dd-mm-yyyy',
            startDate: '0d',
        });

        tebusan();

    }

    function getUpahByDate(e){

        let jeniskeuntungan = (tagbaru == 1) ? 'onepercent' : 'asal';
        let tarikh = $('#datetarikh').val();

        $.ajax({
            method:'get',
            datatype:'json',
            url:api + '/api/upahtawarruqbytarikh',
            async:false,
            data:{
                'kodcaw' : kodcaw,
                'norujukan' : norujukan,
                'tarikh' : tarikh,
                'jeniskeuntungan' : jeniskeuntungan,
            },
        success:function(data){

        if(jeniskeuntungan == 'asal'){
            $('#jumlahupahTU').val(formatter.format(data['upahsemasa']));
            $('#hargatebus').val(formatter.format(data['harga_tebus']));
        }else{
            $('#jumlahupahTU').val(formatter.format(data['pendapatan']));
            $('#jumujrahTU').val(formatter.format(data['ujrah']));
            $('#jumonepercentTU').val(formatter.format(data['keuntungan']));

            let rebetujrh = data['ujrah'] - data['ujrah_rebet'];
            let rebetonep = data['keuntungan'] - data['keuntungan_rebet'];
            $('#jumujrahrebetTU').val(formatter.format(rebetujrh));
            $('#jumonepercentrebetTU').val(formatter.format(rebetonep));
            $('#hargatebus').val(formatter.format(data['harga_tebus']));
        }
        $('#tempohjanaan').val(data['tempoh']);
        }
        });


    }

    function getRoundedMethod(number = 0.0) {
        const numberString = (Math.floor(number * 100) / 100).toFixed(2);
        let rounded = numberString.slice(0, -1);
        const lastDigit = parseInt(numberString.slice(-1), 10);

        if (lastDigit >= 0 && lastDigit <= 2) {
            rounded = rounded.replace(',', ''); // Remove commas
            return parseFloat(rounded);
        } else if (lastDigit >= 3 && lastDigit <= 7) {
            rounded += '5';
            rounded = rounded.replace(',', ''); // Remove commas
            return parseFloat(rounded);
        } else {
            return customRound(number);
        }
    }

    function customRound(number) {
        const precision = 1; // Round to one decimal place
        const factor = Math.pow(10, precision);
        return Math.ceil(number * factor) / factor;
    }

    // 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
