@extends('layouts.app')

<style>
    #daftar_gadai{
        color:#fff !important;
    }
</style>

@section('content')
@include('modal.historytebus')
@include('modal.wakil')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 col-lg-12">

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

            <div class="form-group row col-md-12">
                <div class="col-md-6">
                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Nama</b>
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="name" id="name" readonly value="{{ $customer_info['nama'] }}">
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>No Kad Pengenalan</b>
                        </div>
                        <div class="col-md-8">
                            @php
                                if($customer_info['kpbaru'] != null){
                                    $noic = $customer_info['kpbaru'];
                                }else{
                                    $noic = $customer_info['kplama'];
                                }
                            @endphp
                            <input type="text" class="form-control" name="noic" id="noic" readonly value="{{ $noic }}">
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Pembiayaan </b>
                        </div>
                        <div class="col-md-8">
                            @php
                                if($customer_info['kpbaru'] != null){
                                    $noic = $customer_info['kpbaru'];
                                }else{
                                    $noic = $customer_info['kplama'];
                                }
                                $outstanding_semasa = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/gadai/customers/'. $noic .'/outstandingsemasa/'.$cawangan_info['kodcaw'])->json();
                            @endphp
                            <input type="text" class="form-control" name="outstanding_semasa" id="outstanding_semasa" readonly value="{{ number_format($outstanding_semasa,2) }}">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Baki Limit Pembiayaan </b>
                        </div>
                        <div class="col-md-8">
                            @php
                                $limit_pinjaman_semasa = 300000 - $outstanding_semasa;
                            @endphp
                            <input type="text" class="form-control" name="limit_pinjaman" id="limit_pinjaman" readonly value="{{ number_format($limit_pinjaman_semasa,2) }}">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Baki Lelong</b>
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="bakilelong" id="bakilelong" readonly value="{{ number_format($bakilelong,2) }}">
                        </div>
                    </div>

                </div>

                <div class="col-md-6">

                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>No Telefon</b>
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="cust_telefon" id="cust_telefon" readonly value="{{ $customer_info['telefon'] ? $customer_info['telefon'] : '' }}">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Nota</b>
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="nota_semasa" id="nota_semasa" readonly value="{{ $customer_info['nota'] }}">
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-md-4">
                            <b>Rugi Lelong</b>
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="rugilelong" id="rugilelong" readonly value="{{ number_format($rugilelong,2) }}">
                        </div>
                    </div>
                </div>

                <div class="col-md-12 mt-md-3 justify-content-between form-group row">
                    <div class="btn-group btn-group-toggle col-md-6" data-toggle="buttons">
                        <label class="btn btn-primary">
                            <input type="radio" name="options" id="option1" value="belum_tebus" autocomplete="off" checked>Pembiayaan Belum Selesai
                        </label>
                        <label class="btn btn-primary">
                            <input type="radio" name="options" id="option2" value="sudah_tebus" autocomplete="off">Pembiayaan Sudah Selesai
                        </label>
                        <label class="btn btn-primary">
                            <input type="radio" name="options" id="option3" value="lelong" autocomplete="off">Lelong
                        </label>
                    </div>
                    <div class='col-md-3'>
                        <button class='btn btn-primary' data-toggle="modal" data-target="#customer_detail">Maklumat Pelanggan</button>
                    </div>
                    <div class="col-md-3 text-right">
                        <a class="btn btn-primary" style="margin-right:-50px" id="daftar_gadai">Daftar P</a>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-body">
                    <nav class="mb-3">
                        <div class="nav nav-tabs" id="nav-tab" role="tablist">
                            <a class="nav-item nav-link active" id="nav-tawarruq-tab" data-toggle="tab" href="#nav-tawarruq" role="tab" aria-controls="nav-tawarruq" aria-selected="true">Tawarruq</a>
                            <a class="nav-item nav-link" id="nav-xtawarruq-tab" data-toggle="tab" href="#nav-xtawarruq" role="tab" aria-controls="nav-xtawarruq" aria-selected="false">Ar-Rahn</a>
                        </div>
                    </nav>
                    <div class="tab-content" id="navtawarruqdannottawarruq">
                        <div class="tab-pane fade show active" id="nav-tawarruq" role="tabpanel" aria-labelledby="nav-tawarruq-tab">
                            <table class="table table-striped table-hover" id="myTable">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Rujukan</th>
                                        <th>Tarikh Pembiayaan</th>
                                        <th>Tarikh Matang</th>
                                        <th>Baki Harga Jualan</th>
                                        <th>Baki Pembiayaan</th>
                                        <th>Margin</th>
                                        <th>Tempoh</th>
                                        <th>Keuntungan</th>
                                        <th>Lelong</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                        <div class="tab-pane fade" id="nav-xtawarruq" role="tabpanel" aria-labelledby="nav-xtawarruq-tab">
                            <table id="xtawarruq" class="table table-striped table-hover">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Rujukan</th>
                                        <th>Tarikh Pembiayaan</th>
                                        <th>Tarikh Matang</th>
                                        <th>Pembiayaan</th>
                                        <th>Margin</th>
                                        <th>Tempoh</th>
                                        <th>Lelong</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>

                    {{-- Sudah Tebus --}}

                    <table id="dahtebusTable" class="table table-striped table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th>Bil</th>
                                <th>No Rujukan</th>
                                <th>Tarikh Penyelesaian Pem.</th>
                                <th>Baki Pembiayaan</th>
                                <th>Margin</th>
                                <th>Tempoh</th>
                            </tr>
                        </thead>
                    </table>

                    <table id="lelongTable" class="table table-striped table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th>Bil</th>
                                <th>No Rujukan</th>
                                <th>Tarikh Lelong</th>
                                <th>Tarikh Tuntut</th>
                                <th>Pembiayaan</th>
                                <th>Harga Jual</th>
                                <th>Jum Tuntut/Bayar</th>
                                <th>Keuntungan</th>
                                <th>Caj Lelong</th>
                                <th>Status Tuntutan</th>
                                <th>Cetak</th>
                            </tr>
                        </thead>
                    </table>

                    <div class="text-center">
                        <button class="btn btn-primary" onclick="ubahfunc(this)">Ubah</button>
                        <button class="btn btn-primary" onclick="hapusfunc()">Hapus</button>
                        <button class="btn btn-primary" onclick="histfunc()">Rekod Pembiayaan</button>
                    </div>

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

<!-- Modal -->
<div class="modal fade" id="customer_detail" tabindex="-1" aria-labelledby="customer_detailLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="customer_detailLabel">Maklumat Pelanggan</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="kemaskiniform">
                    <div class='row form-group'>
                        <div class='col-md-6'>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    Nama
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='nama' id='nama' value="{{ $customer_info['nama'] }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    No KP
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='icno' id='icno' value="{{ $customer_info['kpbaru'] ? $customer_info['kpbaru'] : $customer_info['kplama'] }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    No Pelanggan
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='nopelanggan' id='nopelanggan' value="{{ $customer_info['nopelanggan'] }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    No Telefon 1
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='' id='telefon' value="{{ $customer_info['telefon'] ? $customer_info['telefon'] : '' }}" class='form-control'>
                                    <span id="errortelefon" style="color:red;"></span>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    No Telefon 2
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='telefon2' id='telefon2' value="{{ $customer_info['telefon2'] ? $customer_info['telefon2'] : '' }}" class='form-control'>
                                    <span id="errortelefon2" style="color:red;"></span>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    Bank
                                </div>
                                <div class='col-md-7'>
                                    @php
                                        $bank = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/bank')->json();
                                    @endphp
                                    <select class="form-control" name="kodbank" data-placeholder="Pilih Bank" id="kodbank" disabled="true">
                                        <option value="-" selected disabled>-</option>
                                        @foreach($bank as $banks)
                                            <option value="{{ $banks['abbreviation'] }}" {{ $banks['abbreviation'] == $customer_info['kodbank'] ? 'selected' : ''}}>{{ $banks['name'] }}</option>
                                        @endforeach
                                    </select>
                                    <span id="errorkodbank" style="color:red;"></span>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-5'>
                                    No Akaun
                                </div>
                                <div class='col-md-7'>
                                    <input type="text" readonly name='noakaun' id='noakaun' value="{{ $customer_info['noakaun'] }}" class='form-control'>
                                    <span id="errornoakaun" style="color:red;"></span>
                                </div>
                            </div>
                        </div>
                        <div class='col-md-6'>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-4'>
                                    Alamat
                                </div>
                                <div class='col-md-8'>
                                    <textarea style="resize:none" name="alamat" id="alamat" cols="30" rows="3" readonly class='form-control'>{{ $customer_info['alamat1'] ? $customer_info['alamat1'] : 'NIL' }}</textarea>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-4'>
                                    Poskod
                                </div>
                                <div class='col-md-8'>
                                    <input type="text" readonly name='poskod' id='poskod' value="{{ $customer_info['poskod'] ? $customer_info['poskod'] : 'NIL' }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-4'>
                                    Daerah
                                </div>
                                <div class='col-md-8'>
                                    @php
                                        $poskod = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/poskod/'. $customer_info['poskod'])->json();
                                        if(empty($poskod)){
                                            $poskod = array('koddaerah'=>'NIL','kodnegeri' => 'NIL');
                                        }
                                        $daerah = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/daerah/' . $poskod['koddaerah'])->json();
                                    @endphp
                                    <input type="text" readonly name='koddaerah' id='koddaerah' value="{{ $daerah ? $daerah['namadaerah'] : 'NIL' }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-4'>
                                    Negeri
                                </div>
                                <div class='col-md-8'>
                                    @php
                                        $negeri = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/negeri/' . $poskod['kodnegeri'])->json();
                                    @endphp
                                    <input type="text" readonly name='kodnegeri' id='kodnegeri' value="{{ $negeri ? $negeri['negeri'] : 'NIL' }}" class='form-control'>
                                </div>
                            </div>
                            <div class='form-group row col-md-12'>
                                <div class='col-md-4'>
                                    Nota
                                </div>
                                <div class='col-md-8'>
                                    <textarea style="resize:none" name="nota" id="nota" cols="30" rows="3" readonly class='form-control'>{{ $customer_info['nota'] }}</textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <div class="mr-5 form-group float-right">
                    <button type="button" class="btn btn-primary" onclick="kemaskinifunc()" id="btnkemaskini">Ubah</button>
                    <button type="button" class="btn btn-primary" onclick="kemaskinipelanggan()" id="btnsave">Terima</button>
                    {{-- <button type="button" class="btn btn-primary" id="btnotp">Daftar Akaun Online</button> --}}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="opt_modal" tabindex="-1" aria-labelledby="opt_modalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="opt_modalLabel">Daftar Akaun Online</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center">
                    <div class="row justify-content-center">
                        <div class="col-md-7">
                            <div class="input-group my-3" id="otp_form">
                                <input type="text" class="form-control" name="noic_otp" readonly placeholder="No Kad Pengenalan Pelanggan" id="noic_otp" aria-label="No Kad Pengenalan Pelanggan" autocomplete="off" value="" aria-describedby="button-addon2">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-primary" type="button" id="jana_otp">Jana OTP</button>
                                </div>
                            </div>
                            <div id="otp_generate" style="display:none;">
                                <div class="row form-group">
                                    <div class="col-md-4">
                                        OTP Token :
                                    </div>
                                    <div class="col-md-4">
                                        <span id="otp_number"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    var api_arrahnbid = "<?php echo config('app.api_arrahnbid') ?>";
    var api_url = "<?php echo $api_url ?>";
    var kodcaw = "{{ $cawangan_info['kodcaw'] }}";
    var tagarrahnbid = "{{ $cawangan_info['tagarrahnbid'] }}";
    var min_komoditi = "{{ $min_komoditi }}";
    $('#daftar_gadai').on('click',function(){
        $("#daftar_gadai").prop('disabled', true);
        var noic = $('#noic').val();
        var iclama = "{{ $customer_info['kplama'] }}";
        var icbaru = "{{ $customer_info['kpbaru'] }}";
        var outstanding_semasa = "{{ $outstanding_semasa }}";
        event.preventDefault();
        if(outstanding_semasa >= 300000){
            Swal.fire({
                icon: 'error',
                title: 'Had Pembiayaan',
                text: 'Outstanding Pembiayaan Pelanggan Telah Melebihi Had'
            });
            $("#daftar_gadai").prop('disabled', false);
            event.preventDefault();
            return false;
        }else{
            $.ajax({
                method:'get',
                url: api_url + '/api/komuditi/check',
                success:function(data){
                    var check_komuditi = Object.keys(data).length;
                    if(check_komuditi == 0){
                        Swal.fire({
                            icon: 'error',
                            title: 'Unit Komoditi Berbaki Minima',
                            text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komoditi'
                        });
                        $("#daftar_gadai").prop('disabled', false);
                        event.preventDefault();
                        return false;
                    }else{
                        if(Number(data['unit_komuditi']) <= min_komoditi){
                            $("#daftar_gadai").prop('disabled', false);
                            Swal.fire({
                                icon: 'error',
                                title: 'Unit Komoditi Berbaki Minima',
                                text: 'Sila Hubungi Operasi Untuk Membuat Pembelian Komoditi'
                            });
                            event.preventDefault();
                            return false;
                        }
                        else{
                            if(icbaru.length > 0){
                                window.location.href = "{{ route('gadaian',['noic'=>$customer_info['kpbaru'] ]) }}";
                            }else{
                                window.location.href = "{{ route('gadaian',['noic'=>$customer_info['kplama'] ]) }}";
                            }
                        }
                    }
                }
            });
        }

    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        // here is the new selected tab id
        var selectedTabId = e.target.id;

    });

    var tablegadai = $('#myTable').DataTable({
        "scrollX": false,
        order: [[1,'desc']]
    });

    var xtawarruq = $('#xtawarruq').DataTable({
        "scrollX": false
    });

    var tabledahtebus = $('#dahtebusTable').DataTable({
    });

    var tablelelong = $('#lelongTable').DataTable({
        "scrollX": false
    });

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

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

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

    function checkserah(data){
        var urlpenebusan = $(data).data("url");
        var norujukan = $(data).data("norujukan");
        var pinjaman = $(data).data("pinjaman");
        var hargajualan = $(data).data("hargajualan");

        if(hargajualan == pinjaman){
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Pembiayaan Mengalami Masalah Sila Hubungi IT'
            });
            return false;
        }
        $.ajax({
            method:'get',
            url: api_url + '/api/check/serah/lelong',
            datatype:'json',
            data:{
                'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                'norujukan': norujukan
            },
            success:function(data){
                if(data == 0){
                    $.ajax({
                        method:'get',
                        url: api_url + '/api/polis/get',
                        datatype:'json',
                        data:{
                            'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                            'norujukan': norujukan
                        },
                        success:function(data){

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

                            if(count > 0)
                            {
                                if(data[0].tebus === 0)
                                {
                                    const swalWithBootstrapButtons = Swal.mixin({
                                        customClass: {
                                            confirmButton: 'btn btn-success',
                                            cancelButton: 'btn btn-danger mr-1'
                                        },
                                        buttonsStyling: false
                                    });

                                    swalWithBootstrapButtons.fire({
                                        title: 'Dapatkan Pengesahan Khazanah',
                                        text: "Surat Akuan Gadai Hilang!",
                                        icon: 'info',
                                        showCancelButton: true,
                                        confirmButtonText: 'Hantar',
                                        cancelButtonText: 'Batal',
                                        reverseButtons: true
                                    }).then((result) => {
                                        if (result.isConfirmed) {

                                            // let komen = "Surat Akuan Gadaian Hilang|" + '-' + "|" + '-' +  "|" + '-';
                                            let status = "Surat Akuan Gadai Hilang";
                                            let marg = 0;
                                            let ber = 0;
                                            let nm = 0;
                                            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" : '0.00',
                                                    "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'
                                                        }).then(function(){
                                                            $.ajax({
                                                                method:'put',
                                                                url: api_url + '/api/polis/put/',
                                                                data: {
                                                                    'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                                                                    'norujukan': norujukan,
                                                                    'tebus' : 1
                                                                },
                                                                success:function(data){
                                                                    location.reload();

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

                                                    }
                                                    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) {
                                            swalWithBootstrapButtons.fire(
                                                'Gagal',
                                                'Gagal mendapatkan kelulusan khazanah',
                                                'error'
                                            )
                                        }
                                    });
                                }
                                else
                                {
                                    $.ajax({
                                        method:'get',
                                        url: api_url + '/api/check/serah/gadai',
                                        datatype:'json',
                                        data:{
                                            'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                                            'norujukan': norujukan
                                        },
                                        success:function(data){
                                            if(data == 'true'){
                                                window.location = urlpenebusan;
                                            }else if(data == 'false'){
                                                Swal.fire({
                                                    icon: 'error',
                                                    title: 'Amaran',
                                                    text: 'Pembiayaan Belum Scan Barcode'
                                                });
                                            }
                                        }
                                    });
                                }
                            }else{
                                $.ajax({
                                    method:'get',
                                    url: api_url + '/api/check/serah/gadai',
                                    datatype:'json',
                                    data:{
                                        'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                                        'norujukan': norujukan
                                    },
                                    success:function(data){
                                        if(data == 'true'){
                                            window.location = urlpenebusan;
                                        }else if(data == 'false'){
                                            Swal.fire({
                                                icon: 'error',
                                                title: 'Amaran',
                                                text: 'Pembiayaan Belum Scan Barcode'
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });
                }else if(data == 1){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran',
                        text: 'Pembiayaan Sedang Dilelong..'
                    });
                }
            }
        });

    }

    function gadaiTable(data,jenistebus){

        var counter = 1;
        tablegadai.clear().draw();
        tabledahtebus.clear().draw();
        tablelelong.clear().draw();
        xtawarruq.clear().draw();
        $.each(data,function(index,gadai_detail){
            $.ajax({
                method:'get',
                url:api_url + '/api/upahtawarruq/'+ gadai_detail['kodcaw'] +'/' + gadai_detail['norujukan'],
                success:function(upahsemasa){
                    if(jenistebus == "belum_tebus"){
                        var urlroute = '{{ route("penebusan", ":id") }}';
                        urlroute = urlroute.replace(':id', gadai_detail["norujukan"]);
                        if(gadai_detail["bakihargajualan"] == null){
                            if(gadai_detail['taglel'] == 1){
                                var taglel = '<b class="text-danger">Akan Dilelong</b>';
                            }else{
                                var taglel = '';
                            }

                            xtawarruq.row.add([
                                '<input type="radio" value='+ gadai_detail["norujukan"] +' name="belum"/>',
                                '<a href="#" onclick="checkserah(this)" data-pinjaman='+ gadai_detail['pinjaman'] +' data-hargajualan='+ gadai_detail['hargajualan'] +' data-norujukan='+ gadai_detail['norujukan'] +' data-url=' + urlroute +'>' + gadai_detail['norujukan'] + '</a>',
                                gadai_detail['t_gadai'],
                                gadai_detail['t_matang'],
                                'RM '+formatter.format(gadai_detail['pinjaman']),
                                (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                                gadai_detail['tempoh'],
                                taglel,
                            ]).draw();
                        }else{
                            var taglel = '';
                            if(gadai_detail['taglel'] == 1){
                                if(tagarrahnbid == 1){
                                    $.ajax({
                                        method:"GET",
                                        async:false,                                       
                                        url:api_arrahnbid + 'portalApi?norujukan=' + gadai_detail['norujukan'],

                                        success: function(data){
                                            taglel = data.lelong.t_lelong;
                                        }
                                    });
                                } else {
                                    $.ajax({
                                        method:"GET",
                                        async:false,
                                        url:api_url + '/api/check/taglelong',
                                        data: {
                                            'kodcaw': "{{ $cawangan_info['kodcaw'] }}",
                                            'norujukan': gadai_detail['norujukan'],
                                        },
                                        success: function(v){
                                            taglel = v.t_lelong;
                                        }
                                    });
                                }
                            }

                            if(gadai_detail['lelong_tawarruq'] == 0){
                                var tarikh_matang = gadai_detail['t_matang1'];
                            }else{
                                var tarikh_matang = gadai_detail['t_matang'];
                            }

                            if(gadai_detail['tagbaru'] == 0)
                            tablegadai.row.add([
                                '<input type="radio" value='+ gadai_detail["norujukan"] +' name="belum"/>',
                                '<a href="#" onclick="checkserah(this)" data-pinjaman='+ gadai_detail['pinjaman'] +' data-hargajualan='+ gadai_detail['hargajualan'] +' data-norujukan='+ gadai_detail['norujukan'] +' data-url=' + urlroute +'>' + gadai_detail['norujukan'] + '</a>',
                                gadai_detail['t_gadai'],
                                tarikh_matang,
                                'RM '+ formatter.format(gadai_detail['bakihargajualan']),
                                'RM '+formatter.format(gadai_detail['bakipjm']),
                                (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                                gadai_detail['tempoh'],
                                'RM '+ upahsemasa,
                                '<div style="white-space: nowrap; color:red; font-weight: bolder">' + taglel + '</div>',
                            ]).draw();
                        }
                    }else if(jenistebus == "sudah_tebus"){

                        tabledahtebus.row.add([
                                '<input type="radio" value='+ gadai_detail["norujukan"] +' name="sudahtebus"/>',
                            gadai_detail['norujukan'],
                            gadai_detail['t_update'],
                            'RM '+formatter.format(gadai_detail['bakipjm']),
                            (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                            gadai_detail['tempoh']
                        ]).draw();
                    }else if(jenistebus == "lelong"){
                        var urlroute = '{{ route("lelongan", ":id") }}';
                        urlroute = urlroute.replace(':id', gadai_detail["norujukan"]);

                        var tuntutan = 'Pelanggan';

                        $.ajax({
                            method:"GET",
                            async:false,
                            url: api_url + "/api/check/customer/",
                            data:{
                                "norujukan" : gadai_detail['norujukan'],
                                "kodcaw" : kodcaw
                            },
                            success: function(response){
                                if(response[0].teller == 'DM')
                                {
                                    tuntutan = 'WTD';
                                }
                            }
                        });

                        if(gadai_detail['trkhtuntut'] == null){
                            tablelelong.row.add([
                                counter,
                                '<a href="#" onclick="checktuntutbaki(this)" data-norujukan=' + gadai_detail['norujukan'] + ' data-tarikhtuntut=' + gadai_detail['trkhtuntut'] + '>' + gadai_detail['norujukan'] + '</a>',
                                gadai_detail['t_lelong'],
                                gadai_detail['trkhtuntut'],
                                'RM '+ formatter.format(gadai_detail['pinjaman']),
                                'RM '+formatter.format(gadai_detail['hargajual']),
                                'RM '+formatter.format(gadai_detail['baki']),
                                'RM '+formatter.format(gadai_detail['bakiupah']),
                                'RM '+formatter.format(gadai_detail['cajlelong']),
                                '',
                                '<button class="btn btn-info" disabled>Cetak</button>'
                            ]).draw();
                        }else{
                            tablelelong.row.add([
                                counter,
                                '<a href="#" onclick="checktuntutbaki(this)" data-norujukan=' + gadai_detail['norujukan'] + ' data-tarikhtuntut=' + gadai_detail['trkhtuntut'] + '>' + gadai_detail['norujukan'] + '</a>',
                                gadai_detail['t_lelong'],
                                gadai_detail['trkhtuntut'],
                                'RM '+ formatter.format(gadai_detail['pinjaman']),
                                'RM '+formatter.format(gadai_detail['hargajual']),
                                'RM '+formatter.format(gadai_detail['baki']),
                                'RM '+formatter.format(gadai_detail['bakiupah']),
                                'RM '+formatter.format(gadai_detail['cajlelong']),
                                tuntutan,
                                '<button class="btn btn-info" onclick="cetaktuntutbaki(this)" data-norujukan=' + gadai_detail['norujukan'] +'>Cetak</button>'
                            ]).draw();
                        }
                    }
                    counter = counter + 1;
                }
            });
        });
    }

    function cetaktuntutbaki(e)
    {
        let norujukan = $(e).data('norujukan');

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

        swalWithBootstrapButtons.fire({
        title: 'Dapatkan Pengesahan PC/PPC',
        text: "Kelulusan Ulang Cetak Tuntut Baki Lelong",
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Hantar',
        cancelButtonText: 'Batal',
        reverseButtons: true
        }).then((result) => {
            if(result.isConfirmed) {
                Swal.fire({
                    title: 'Tunggu Pengesahan Daripada PC/PPC.',
                    icon: 'info',
                    width: 600,
                    padding: '3em',
                    background: '#fffff',
                    showCancelButton: false,
                    showConfirmButton: false,
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    allowEnterKey: false
                })

                let mohon = "Ulang Cetak Tuntut Baki";

                $.ajax({
                    method:'post',
                    url: '{{ route("teller.createkelulusan") }}',
                    data: {
                        "_token": "{{ csrf_token() }}",
                        "norujukan" : norujukan,
                        "mohon" : mohon
                    },
                    success:function(data){
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });

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

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

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

                    if(data.norujukan == norujukan && data.teller == teller)
                    {
                        if(data.kelulusan == 'lulus')
                        {
                            Swal.fire({
                                    icon: 'success',
                                    title: 'Telah Disahkan'
                            }).then(function(){
                                let urlroute = '{{ route("resit.tuntutbaki", ":id") }}';
                                urlroute = urlroute.replace(':id', norujukan);
                                window.open(urlroute, '_blank');
                            });

                        }
                        else if(data.kelulusan == 'batal')
                        {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Telah Dibatalkan',
                                text: `Komen : ${data.komen}`
                            }).then(function(){
                                location.reload();
                                return false;
                            });
                        }
                    }
                });
            }else if (result.dismiss === Swal.DismissReason.cancel){
                swalWithBootstrapButtons.fire(
                    'Batal',
                    'Tidak Berjaya Mendapatkan Pengesahan Khazanah',
                    'error'
                )
            }

        });
        return;
    }

    function checktuntutbaki(e)
    {
        let tarikhtuntut = $(e).data('tarikhtuntut');
        let norujukan = $(e).data('norujukan');

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

        if (tarikhtuntut == null)
        {
            $.ajax({
                method: 'GET',
                url : api_url + '/api/check/wtd',
                data:{
                    'norujukan' : norujukan
                },
                success:function(data){
                    if(data == 'yes'){
                        Swal.fire({
                            icon: 'error',
                            title: 'Amaran',
                            text: 'Lelongan dalam process WTD'
                        });
                    }else{

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

                        swalWithBootstrapButtons.fire({
                        title: 'Dapatkan Pengesahan PC/PPC',
                        text: "Kelulusan Tuntut Baki Lelong",
                        icon: 'info',
                        showCancelButton: true,
                        confirmButtonText: 'Hantar',
                        cancelButtonText: 'Batal',
                        reverseButtons: true
                        }).then((result) => {
                            if(result.isConfirmed) {
                                Swal.fire({
                                    title: 'Tunggu Pengesahan Daripada PC/PPC.',
                                    icon: 'info',
                                    width: 600,
                                    padding: '3em',
                                    background: '#fffff',
                                    showCancelButton: false,
                                    showConfirmButton: false,
                                    allowOutsideClick: false,
                                    allowEscapeKey: false,
                                    allowEnterKey: false
                                })

                                let mohon = "Tuntut Baki";

                                $.ajax({
                                    method:'post',
                                    url: '{{ route("teller.createkelulusan") }}',
                                    data: {
                                        "_token": "{{ csrf_token() }}",
                                        "norujukan" : norujukan,
                                        "mohon" : mohon
                                    },
                                    success:function(data){
                                    },error: function(xhr, status, error) {
                                        var err = eval("(" + xhr.responseText + ")");
                                        alert(xhr.responseText);
                                    }
                                });

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

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

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

                                    if(data.norujukan == norujukan && data.teller == teller)
                                    {
                                        if(data.kelulusan == 'lulus')
                                        {
                                            Swal.fire({
                                                    icon: 'success',
                                                    title: 'Telah Disahkan'
                                            }).then(function(){
                                                window.location.href = urlroute;
                                            });
                                        }
                                        else if(data.kelulusan == 'batal')
                                        {
                                            Swal.fire({
                                                icon: 'warning',
                                                title: 'Telah Dibatalkan',
                                                text: `Komen : ${data.komen}`
                                            }).then(function(){
                                                location.reload();
                                                return false;
                                            });
                                        }
                                    }
                                });
                            }else if (result.dismiss === Swal.DismissReason.cancel){
                                swalWithBootstrapButtons.fire(
                                    'Batal',
                                    'Tidak Berjaya Mendapatkan Pengesahan Khazanah',
                                    'error'
                                )
                            }

                        });

                    }
                }
            });
        }else{
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Lelongan telah Dituntut!'
            });
        }

        return false;
    }



    $(document).ready( function () {

        $('#myTable').parents('div.dataTables_wrapper').first().hide();
        $('#dahtebusTable').parents('div.dataTables_wrapper').first().hide();
        $('#lelongTable').parents('div.dataTables_wrapper').first().hide();
        $('#btnsave').css('display','none');

        var noic = $("#noic").val();

        $.ajax({
            method:"GET",
            url: api_url + "/api/customers/"+noic+"/gadai/belum_tebus/"+kodcaw,
            success: function(data){
                $('#myTable').parents('div.dataTables_wrapper').first().show();
                gadaiTable(data,"belum_tebus");
            }
        });

        $('#myTable td').click( function () {
            alert('dasdsa');
        });

        $("input[name='options']").click(function(){
            gadaiOptionButton(noic);
        });
    });

    function histfunc(){
        if($("input[name='options']:checked").val() == 'belum_tebus'){
            let histid = $('input[name="belum"]:checked').val();
            if(histid == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Sila pilih salah satu SAG'
                });
            }else{

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

                $.ajax({
                    method:'get',
                    url:'{{ route("gadai.history") }}',
                    data:{ "norujukan" : histid},
                    success:function(data)
                    {

                        historytebustable(data);
                        $.ajax({
                            method: 'get',
                            url: api_url + '/api/transaction/' + histid,
                            success: function(data){
                                historybayarantable(data);

                                $.ajax({
                                    method:'get',
                                    url: api_url + '/api/gadai/norujukan/'+histid,
                                    success:function(gadai){
                                        rekodasal(gadai);

                                        $.ajax({
                                            method:'get',
                                            url: api_url + '/api/ansuran/' + "{{ $cawangan_info['kodcaw'] }}" + '/' + histid,
                                            success:function(ansuran){
                                                rekodansuran(ansuran);

                                                Swal.close();
                                                $('#historytebusModal').modal();
                                            }
                                        });
                                    }
                                });

                            }
                        });
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });
            }
        }else if($("input[name='options']:checked").val() == 'sudah_tebus'){
            let histid = $('input[name="sudahtebus"]:checked').val();

            if(histid == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Sila pilih salah satu SAG'
                });
            }else{

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

                $.ajax({
                    method:'get',
                    url:'{{ route("gadai.history") }}',
                    data:{ "norujukan" : histid},
                    success:function(data){
                        historytebustable(data);

                        $.ajax({
                            method: 'get',
                            url: api_url + '/api/transaction/' + histid,
                            success: function(data){
                                historybayarantable(data);
                            }
                        });
                        $.ajax({
                            method:'get',
                            url:api_url + '/api/gadai/norujukan/'+histid,
                            success:function(gadai){
                                rekodasal(gadai);
                            }
                        });
                        $.ajax({
                            method:'get',
                            url: api_url + '/api/ansuran/' + "{{ $cawangan_info['kodcaw'] }}" + '/' + histid,
                            success:function(ansuran){
                                rekodansuran(ansuran);
                            }
                        });

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

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

    function rekodasal(gadaian){
        $('#hargajualanmodal').text('RM ' + formatter.format(gadaian[0][0]['hargajualan']));
        $('#pembiayaanmodal').text('RM ' + formatter.format(gadaian[0][0]['pinjaman']));
        $('#nilaimarhunmodal').text('RM ' + formatter.format(gadaian[0][0]['nilaimarhun']));
    }

    function rekodansuran(data){
        var counter = 1;

        bayaranupah.clear().draw();
        $.each(data,function(index,bayaran){

            var urlroute = '{{ route("resit.advansur", ":id") }}';
            urlroute = urlroute.replace(':id', bayaran['norujukan']);
            bayaranupah.row.add([
                    counter,
                    bayaran['tarikh'],
                    "RM " + bayaran['upahDibayar'],
                    '<a class="btn btn-info" target="_blank" href='+ urlroute +'>Cetak</a>'
                ]).draw();
                counter = counter + 1;
        });
    }

    function historybayarantable(data){
        var counter = 1;

        historybayarandatatable.clear().draw();
        $.each(data,function(index,bayaran){

            var urlroute = '{{ route("resit.ansuran", ":id") }}';
            urlroute = urlroute.replace(':id', bayaran['id']);
            historybayarandatatable.row.add([
                    counter,
                    bayaran['created_at'],
                    "RM " + bayaran['duit_masuk'],
                    '<a class="btn btn-info" target="_blank" href='+ urlroute +'>Cetak</a>'
                ]).draw();
                counter = counter + 1;
        });
    }

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

    function historytebustable(data){

        var counter = 1;
        historytebusbayaran.clear().draw();

        $.each(data,function(index,tebusaz){

            switch(tebusaz['jenistebus']) {
                case 'P':
                    var urlroute = '{{ route("resit.tambahpinjam", ":id") }}';
                    urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                    break;
                case 'T':

                    if(tebusaz['hargajualan'] === '')
                    {
                        var urlroute = '{{ route("resit.belumtebus", ":id") }}';
                        urlroute = urlroute.replace(':id', tebusaz['norujukan']);

                    }else{
                        var urlroute = '{{ route("resit.tebus", ":id") }}';
                        urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                    }

                    break;
                case 'A':
                    var urlroute = '{{ route("resit.belumansurans", ":id") }}';
                    urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                    break;
                case 'S':
                var urlroute = '{{ route("resit.tebusseparuh", ":id") }}';
                urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                break;
                }

            historytebusbayaran.row.add([
                counter,
                tebusaz['norujukan'],
                tebusaz['jenistebus'],
                tebusaz['pinjaman'],
                tebusaz['jbg'],
                tebusaz['t_tebus'],
                '<a class="btn btn-info" target="_blank" href='+ urlroute +'>Cetak</a>'
            ]).draw();
            counter = counter + 1;
        });
    }

    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 norujukan = $('#norujukanwakil').val();


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

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

                        $.ajax({
                            method:'put',
                            url: api_url + '/api/ubahwakil/' + kodcaw,
                            data:{ 'nowakil' : nw,
                                'norujukan' : norujukan},
                            success:function(data){

                                if(data === 1)
                                {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Berjaya!',
                                        text: 'Penukaran Wakil berjaya'
                                    }).then(async function(){
                                        return true;
                                        location.reload();
                                        });
                                }else{
                                    Swal.fire({
                                        icon: 'info',
                                        title: 'Pemberitahuan!',
                                        text: 'Wakil telah didaftarkan dengan IC tersebut!'
                                    }).then(async function(){
                                        return true;
                                        location.reload();
                                    });
                                }

                            }
                        });
                    });
                }

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

    function daftarwakilfunction(nokp,norujukan)
    {
        $('#nokpwakil').val(nokp);
        $('#norujukanwakil').val(norujukan);

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

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

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

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

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


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

        });
    }


    function ubahfunc(e){

        let ubahid = $('input[name="belum"]:checked').val();
        let harini = new Date();harini.setHours(0, 0, 0, 0);

        if($("input[name='options']:checked").val() == 'belum_tebus'){
            let test1 = $('input[name="belum"]:checked').closest('tr').children('td:eq(2)').text();
            let tarikhgadai2 = new Date(test1);tarikhgadai2.setHours(0, 0, 0, 0);
            if(+harini !== +tarikhgadai2){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Ubah Pembiayaan Tidak Dibenarkan'
                });
                return false;
            }
        }else if($("input[name='options']:checked").val() == 'sudah_tebus'){

            let test = $('input[name="sudahtebus"]:checked').closest('tr').children('td:eq(2)').text();
            let tarikhgadai1 = new Date(test);tarikhgadai1.setHours(0, 0, 0, 0);

            if(+harini !== +tarikhgadai1){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Ubah Pembiayaan Tidak Dibenarkan'
                });
                return false;
            }
        }

        if(ubahid == null && $("input[name='options']:checked").val() == 'belum_tebus'){
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Sila pilih salah satu SAG!'
            });

            return false;
        }

        if($("input[name='options']:checked").val() == 'sudah_tebus'){

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

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

                        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 mohon = "Ubah Wakil";
                        let norujukan = $('input[name="sudahtebus"]:checked').val();

                        $.ajax({
                            method:'post',
                            url: '{{ route("teller.createkelulusan") }}',
                            data: {
                                "_token": "{{ csrf_token() }}",
                                "norujukan" : norujukan,
                                "mohon" : mohon
                            },
                            success:function(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
                                        });

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

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

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

                                        const { value: amaun } = await Swal.fire({
                                        title: 'Kad Pengenalan Wakil',
                                        input: 'text',
                                        inputPlaceholder: 'Kad Pengenalan',
                                        confirmButtonText: 'Terima',
                                        showCancelButton:true,
                                        cancelButtonText:'Batal',
                                        allowOutsideClick: true,
                                        inputValidator: (value) => {
                                            if (!value) {
                                                return 'Isikan tempat kosong diatas!'
                                            }

                                            if(value <= 0){
                                                return 'Masukkan No Kad Pengenalan yang betul!';
                                            }

                                           // if(isNaN(value))
                                           // {
                                           //     return 'Kad Pengenalan hendaklah dalam bentuk nombor!'
                                           // }
                                        }
                                    });

                                        if(amaun)
                                        {
                                            $.ajax({
                                                method:'get',
                                                url: api_url + '/api/getwakil/' + kodcaw + '/' + amaun,
                                                success:function(data){

                                                        if(data.length > 0)
                                                        {
                                                            let namawakilsedia = data[0]['nama'];
                                                            let nokpwakilsedia = data[0]['nokp'];
                                                            let nowakilsedia = data[0]['nowakil'];

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

                                                            PengesahanAkhirWakil.fire({
                                                            title: 'Pengesahan Akhir Wakil!',
                                                            html: '<b class="text-danger">' + namawakilsedia + '</b><br><b class="text-danger">' + nokpwakilsedia + '</b>',
                                                            icon: 'info',
                                                            showCancelButton: true,
                                                            confirmButtonText: 'Benar',
                                                            cancelButtonText: 'Salah',
                                                            reverseButtons: true
                                                            }).then((result) => {
                                                                if (result.isConfirmed) {

                                                                    $.ajax({
                                                                        method:'put',
                                                                        async:false,
                                                                        url: api_url + '/api/ubahwakil/' + kodcaw,
                                                                        data:{ 'nowakil' : nowakilsedia,
                                                                            'norujukan' : norujukan},
                                                                        success:function(data){

                                                                            if(data === 1)
                                                                            {
                                                                                Swal.fire({
                                                                                    icon: 'success',
                                                                                    title: 'Berjaya!',
                                                                                    text: 'Penukaran Wakil berjaya'
                                                                                }).then(async function(){
                                                                                    return true;
                                                                                    location.reload();
                                                                                    });
                                                                            }else{
                                                                                Swal.fire({
                                                                                    icon: 'info',
                                                                                    title: 'Pemberitahuan!',
                                                                                    text: 'Wakil telah didaftarkan dengan IC tersebut!'
                                                                                }).then(async function(){
                                                                                    return true;
                                                                                    location.reload();
                                                                                });
                                                                            }

                                                                        }
                                                                    });

                                                                }else if (result.dismiss === Swal.DismissReason.cancel){
                                                                    PengesahanAkhirWakil.fire(
                                                                        'Batal',
                                                                        'Tidak Berjaya Mengesahkan Wakil!',
                                                                        'error'
                                                                    )
                                                                }
                                                            });

                                                        }else{
                                                            Swal.fire({
                                                                allowOutsideClick: false,
                                                                allowEscapeKey: false,
                                                                allowEnterKey: false,
                                                                confirmButtonText: '<i class="fa fa-thumbs-up"></i> Daftar Wakil!',
                                                                icon: 'info',
                                                                title: 'Maklumat anda tiada dalam senarai wakil! Tekan button Daftar untuk mendaftar!'
                                                                }).then(function(){
                                                                    daftarwakilfunction(amaun,norujukan);
                                                            });
                                                        }
                                                    },error: function(xhr, status, error) {
                                                        var err = eval("(" + xhr.responseText + ")");
                                                        alert(xhr.responseText);
                                                    }
                                            });
                                        }
                                    });
                                }
                                else if(data.kelulusan == 'batal')
                                {
                                    Swal.fire({
                                        icon: 'warning',
                                        title: 'Telah Dibatalkan',
                                        text: `Komen : ${data.komen}`
                                    }).then(function(){
                                        // $("#terima_gadai").prop('disabled', false);
                                        return false;
                                    });
                                }
                            }

                        });


                    }else if (result.dismiss === Swal.DismissReason.cancel){
                        swalWithBootstrapButtons.fire(
                            'Batal',
                            'Tidak Berjaya Mendapatkan Pengesahan Khazanah',
                            'error'
                        )
                    }

                });

            return false;
        }

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

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

                    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 mohon = "Ubah Gadai";

                    $.ajax({
                        method:'post',
                        url: '{{ route("teller.createkelulusan") }}',
                        data: {
                            "_token": "{{ csrf_token() }}",
                            "norujukan" : ubahid,
                            "mohon" : mohon
                        },
                        success:function(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
                                        });

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

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

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

                                    var urlroute = '{{ route("gadaian.edit", ":id") }}';
                                    urlroute = urlroute.replace(':id', ubahid);
                                    window.location.replace(urlroute);
                                    return true;
                                });
                            }
                            else if(data.kelulusan == 'batal')
                            {
                                Swal.fire({
                                    icon: 'warning',
                                    title: 'Telah Dibatalkan',
                                    text: `Komen : ${data.komen}`
                                }).then(function(){
                                    // $("#terima_gadai").prop('disabled', false);
                                    return false;
                                });
                            }
                        }



                    });


            }else if (result.dismiss === Swal.DismissReason.cancel){
                swalWithBootstrapButtons.fire(
                    'Batal',
                    'Tidak Berjaya Mendapatkan Pengesahan Khazanah',
                    'error'
                )
            }
        });
    }

    function hapusfunc(){

        let kodcaw = "{{ $cawangan_info['kodcaw'] }}";
        let hapusid = $('input[name="belum"]:checked').val();
        let hapusidsudah = $('input[name="sudahtebus"]:checked').val();
        let harini = new Date();harini.setHours(0, 0, 0, 0);
        if(hapusid == null && $("input[name='options']:checked").val() == 'belum_tebus'){
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Sila pilih salah satu SAG!'
            });
            return false;
        }else if(hapusidsudah == null && $("input[name='options']:checked").val() == 'sudah_tebus'){
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Sila pilih salah satu SAG!'
            });
            return false;
        }

        if($("input[name='options']:checked").val() == 'belum_tebus'){
            let test1 = $('input[name="belum"]:checked').closest('tr').children('td:eq(2)').text();
            let tarikhgadai2 = new Date(test1);tarikhgadai2.setHours(0, 0, 0, 0);

            // var id = $('.tab-content .active').attr('id');

            var activeTab = $("#navtawarruqdannottawarruq.tab-content").find(".active");
            var id = activeTab.attr('id');

            if(id == "nav-tawarruq") {
                if(+harini !== +tarikhgadai2){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran',
                        text: 'Hapus Gadai Tidak Dibenarkan'
                    });
                    return false;
                }
            }
            else {


                $.ajax({
                    method:'get',
                    url: api_url + '/api/upahlamatoday/' + kodcaw + '/' + hapusid,
                    success:function(data){
                        if(data == 1){

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

                            swalWithBootstrapButtons.fire({
                                title: 'Dapatkan Pengesahan Khazanah',
                                text: "Hapus Upah Lama!",
                                icon: 'info',
                                showCancelButton: true,
                                confirmButtonText: 'Hantar',
                                cancelButtonText: 'Batal',
                                reverseButtons: true
                            }).then((result) => {
                                if(result.isConfirmed) {
                                    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 mohon = "Hapus Upah Lama";
                                    let id = hapusid;

                                    $.ajax({
                                        method:'post',
                                        url: '{{ route("teller.createkelulusan") }}',
                                        data: {
                                            "_token": "{{ csrf_token() }}",
                                            "norujukan" : id,
                                            "mohon" : mohon
                                        },
                                        success:function(data){
                                        },error: function(xhr, status, error) {
                                            var err = eval("(" + xhr.responseText + ")");
                                            alert(xhr.responseText);
                                        }
                                    });

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

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

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

                                        if(data.norujukan == id && data.teller == teller)
                                        {
                                            if(data.kelulusan == 'lulus')
                                            {

                                                Swal.fire({
                                                        icon: 'success',
                                                        title: 'Telah Disahkan'
                                                }).then(function(){

                                                        $.ajax({
                                                            method:'post',
                                                            url: api_url + '/api/removeupahlamatoday/' + kodcaw + '/' + id,
                                                            data:{
                                                                "teller" : "{{ Auth::user()->name }}"
                                                            },
                                                            success:function(data){

                                                                if(data == 1)
                                                                {
                                                                    swalWithBootstrapButtons.fire(
                                                                            'Hapus!',
                                                                            'Maklumat upah lama telah dihapuskan.',
                                                                            'success'
                                                                    ).then(function(){
                                                                        location.reload();
                                                                    });
                                                                }else{
                                                                    swalWithBootstrapButtons.fire(
                                                                            'Hapus!',
                                                                            'Maklumat Upah lama tidak berjaya untuk dihapuskan.',
                                                                            'error'
                                                                    ).then(function(){
                                                                        location.reload();
                                                                    });
                                                                }


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


                            return false;
                        }
                        else{
                            Swal.fire({
                                icon: 'error',
                                title: 'Amaran',
                                text: 'Hapus Upah Tidak Dibenarkan'
                            });
                            return false;
                        }
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });

                return false;
            }


            // return false;

        }else if($("input[name='options']:checked").val() == 'sudah_tebus'){
            let test = $('input[name="sudahtebus"]:checked').closest('tr').children('td:eq(2)').text();
            let tarikhgadai1 = new Date(test);tarikhgadai1.setHours(0, 0, 0, 0);

            if(+harini !== +tarikhgadai1){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Hapus Tebus Tidak Dibenarkan'
                });
                return false;
            }
        }

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

        swalWithBootstrapButtons.fire({
            title: 'Dapatkan Pengesahan Khazanah',
            text: "Hapus Rekod!",
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'Hantar',
            cancelButtonText: 'Batal',
            reverseButtons: true
        }).then((result) => {
            if(result.isConfirmed) {
                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 mohon = "";
                let id = 0;

                if($("input[name='options']:checked").val() == 'belum_tebus'){
                    id = hapusid;
                    mohon = "Hapus Gadai";
                }
                else if($("input[name='options']:checked").val() == 'sudah_tebus'){
                    id = hapusidsudah;
                    mohon = "Hapus Tebus";
                }

                $.ajax({
                    method:'post',
                    url: '{{ route("teller.createkelulusan") }}',
                    data: {
                        "_token": "{{ csrf_token() }}",
                        "norujukan" : id,
                        "mohon" : mohon
                    },
                    success:function(data){
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });

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

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

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

                    if(data.norujukan == id && data.teller == teller)
                    {
                        if(data.kelulusan == 'lulus')
                        {

                            Swal.fire({
                                    icon: 'success',
                                    title: 'Telah Disahkan'
                            }).then(function(){


                                if($("input[name='options']:checked").val() == 'belum_tebus'){
                                    $.ajax({
                                        method:'put',
                                        url: api_url + '/api/gadai/hapus/' + kodcaw + '/' + id,
                                        data: { 'kodlaluan' : teller },
                                        success:function(data){
                                            $.ajax({
                                                method:'put',
                                                url: api_url + '/api/komuditi/batal',
                                                dataType:'json',
                                                data:{
                                                    norujukan: hapusid
                                                },
                                                success:function(batalkomuditi){
                                                    swalWithBootstrapButtons.fire(
                                                        'Hapus!',
                                                        'Maklumat Pembiayaan telah dihapuskan.',
                                                        'success'
                                                    ).then(function(){
                                                        location.reload();
                                                    });
                                                }
                                            })
                                        },error: function(xhr, status, error) {
                                            var err = eval("(" + xhr.responseText + ")");
                                            alert(xhr.responseText);
                                        }
                                    });
                                }else if($("input[name='options']:checked").val() == 'sudah_tebus'){
                                    $.ajax({
                                        method:'put',
                                        url:api_url + '/api/tebus/hapus/' + kodcaw + '/' + id,
                                        data: { 'kodlaluan' : teller },
                                        success:function(data){
                                            if(data != "Bukan-Tebus"){
                                                swalWithBootstrapButtons.fire(
                                                    'Hapus!',
                                                    'Maklumat tebus telah dihapuskan.',
                                                    'success'
                                                ).then(function () {
                                                    location.reload();
                                                });
                                            }else{
                                                swalWithBootstrapButtons.fire(
                                                    'Amaran!',
                                                    'Hapus Tebus Tidak Dibenarkan, Hanya untuk tebus sahaja!',
                                                    'error'
                                                )
                                            }
                                        },error: function(xhr, status, error) {
                                            var err = eval("(" + xhr.responseText + ")");
                                            console.log(xhr.responseText);
                                        }
                                    });
                                }
                                return true;
                            });
                        }
                        else if(data.kelulusan == 'batal')
                        {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Telah Dibatalkan',
                                text: `Komen : ${data.komen}`
                            }).then(function(){
                                location.reload();
                                return false;
                            });
                        }
                    }



                });


            }else if (result.dismiss === Swal.DismissReason.cancel) {
                swalWithBootstrapButtons.fire(
                    'Batal',
                    'Maklumat Pembiayaan Tidak Berjaya Dihapuskan',
                    'error'
                )
            }
        });
    }

    function gadaiOptionButton(noic){
        tablegadai.clear().draw();
        if($("input[name='options']:checked").val() == 'belum_tebus'){
            $('#nav-tab').show();
            $('#myTable').parents('div.dataTables_wrapper').first().show();
            $('#xtawarruq').parents('div.dataTables_wrapper').first().show();
            $('#dahtebusTable').parents('div.dataTables_wrapper').first().hide();
            $('#lelongTable').parents('div.dataTables_wrapper').first().hide();

            $.ajax({
                method:"GET",
                url: api_url + "/api/customers/"+noic+"/gadai/belum_tebus/"+kodcaw,
                success: function(data){
                    gadaiTable(data,"belum_tebus");
                }
            });
        }
        if($("input[name='options']:checked").val() == 'sudah_tebus'){
            $('#nav-tab').hide();
            $('#myTable').parents('div.dataTables_wrapper').first().hide();
            $('#xtawarruq').parents('div.dataTables_wrapper').first().hide();
            $('#dahtebusTable').parents('div.dataTables_wrapper').first().show();
            $('#lelongTable').parents('div.dataTables_wrapper').first().hide();

            $.ajax({
                method:"GET",
                url: api_url + "/api/customers/"+noic+"/gadai/sudah_tebus/"+kodcaw,
                success: function(data){
                    gadaiTable(data,"sudah_tebus");
                }
            });
        }
        if($("input[name='options']:checked").val() == 'lelong'){
            $('#nav-tab').hide();
            $('#myTable').parents('div.dataTables_wrapper').first().hide();
            $('#xtawarruq').parents('div.dataTables_wrapper').first().hide();
            $('#dahtebusTable').parents('div.dataTables_wrapper').first().hide();
            $('#lelongTable').parents('div.dataTables_wrapper').first().show();

            $.ajax({
                method:"GET",
                url: api_url + "/api/customers/"+noic+"/gadai/lelong/"+kodcaw,
                success: function(data){
                    gadaiTable(data,"lelong");
                }
            });
        }
    }



    $('#poskod').change(function(){
        var poskod = this.value;
        $.ajax({
            method:'GET',
            url:api_url+'/api/poskod/'+poskod,
            success:function(poskod_detail){
                var koddaerah = poskod_detail['koddaerah'];
                var kodnegeri = poskod_detail['kodnegeri'];
                $.ajax({
                    url:api_url+'/api/negeri/'+kodnegeri,
                    method:'GET',
                    success:function(negeri){
                        $('#kodnegeri').val(negeri['negeri']);
                    }
                });
                $.ajax({
                    url:api_url+'/api/daerah/'+koddaerah,
                    method:'GET',
                    success:function(daerah){
                        $('#koddaerah').val(daerah['namadaerah']);
                    }
                });
            }
        });
    });

    function kemaskinifunc()
    {
        $('#btnkemaskini').addClass('btn-danger');
        $('#btnkemaskini').removeClass('btn-primary');
        $('#btnkemaskini').text('Batal');
        $('#btnkemaskini').attr('onclick','cancelbutton()');
        $('#btnsave').show();
        $('#btnotp').css('display','none');
        //attribute nak readonly false
        $('#telefon').attr('readonly', false);
        $('#telefon2').attr('readonly', false);
        $('#kodbank').attr('disabled', false);
        $('#noakaun').attr('readonly', false);
        $('#nota').attr('readonly', false);
        $('#alamat').attr('readonly', false);
        $('#poskod').attr('readonly', false);

    }

    function cancelbutton(){
        $('#btnkemaskini').removeClass('btn-danger');
        $('#btnkemaskini').addClass('btn-primary');
        $('#btnkemaskini').text('Ubah');
        $('#btnkemaskini').attr('onclick','kemaskinifunc()');
        $('#btnsave').css('display','none');
        $('#btnotp').show();

        document.getElementById("kemaskiniform").reset();

        //attribute nak readonly false
        $('#telefon').attr('readonly', true);
        $('#telefon2').attr('readonly', true);
        $('#kodbank').attr('disabled', true);
        $('#noakaun').attr('readonly', true);
        $('#nota').attr('readonly', true);
        $('#alamat').attr('readonly', true);
        $('#poskod').attr('readonly', true);
    }

    $("#kemaskiniform").submit(function(event) {
        event.preventDefault();

        var nokp = $('#icno').val();
        var telefon1 = $('#telefon').val();
        var telefon2 = $('#telefon2').val();
        var kodbank = $('#kodbank').val();
        var noakaun = $('#noakaun').val();
        var nota = $('#nota').val();
        var alamat = $('#alamat').val();
        var poskod = $('#poskod').val();

        $.ajax({
            method:"put",
            url: api_url + "/api/customers/update/kaunter/" + nokp,
            data:{
                "namateller" : "{{ Auth::user()->name }}",
                "telefon1": telefon1,
                "telefon2": telefon2,
                "kodbank":kodbank,
                "noakaun":noakaun,
                'nota':nota,
                'alamat':alamat,
                'poskod':poskod
            },
            success: function(success){
                $('#btnsave').css('display','none');
                $('#btnotp').show();
                if(success == 1){
                    Swal.fire({
                        icon: 'success',
                        title: 'Berjaya',
                        text: 'Berjaya mengemaskini maklumat pelanggan',
                        allowEscapeKey : false,
                        allowOutsideClick: false,
                    }).then((result) => {
                        if (result.isConfirmed) {
                            location.reload();
                        }
                    });
                }else{
                    Swal.fire({
                        icon: 'error',
                        title: 'Tidak Berjaya',
                        text: 'Tidak berjaya mengemaskini maklumat pelanggan',
                        allowEscapeKey : false,
                        allowOutsideClick: false,
                    });
                }
                
            },
            error: function (request, status, error) {
                alert(request.responseText);
            }

        });
    });

    function kemaskinipelanggan(){

        var errortelefon1 = 0;
        var errortelefon2 = 0;

        if(!($('#telefon').val().length >= 9 && $('#telefon').val().length < 12)){
            $('#errortelefon').show();
            $('#errortelefon').text("*lebih kecil dari 10 dan lebih besar dari 12");
            $('#telefon').addClass('is-invalid');
            errortelefon1++;
        }else{
            $('#errortelefon').hide();
            $('#telefon').removeClass('is-invalid');
            errortelefon1--;
        }

        if($('#telefon2').val() != ''){
            if(!($('#telefon2').val().length >= 9 && $('#telefon2').val().length < 12)){
                $('#errortelefon2').show();
                $('#errortelefon2').text("*lebih kecil dari 10 dan lebih besar dari 12");
                $('#telefon2').addClass('is-invalid');
                errortelefon2++;
            }else{
                $('#errortelefon2').hide();
                $('#telefon2').removeClass('is-invalid');
                errortelefon2--;
            }
        }else{
            $('#errortelefon2').hide();
            $('#telefon2').removeClass('is-invalid');
            errortelefon2--;
        }

        if(errortelefon1 <= 0 && errortelefon2 <= 0){
            $('#btnkemaskini').removeClass('btn-danger');
            $('#btnkemaskini').addClass('btn-primary');
            $('#btnkemaskini').text('Ubah');
            $('#btnkemaskini').attr('onclick','kemaskinifunc()');
            $('#btnotp').text('Daftar Akuan Online');
            $('#btnotp').attr('onclick','#');

            //attribute nak readonly false
            $('#telefon').attr('readonly', true);
            $('#telefon2').attr('readonly', true);
            $('#noakaun').attr('readonly', true);
            $('#kodbank').attr('disabled', true);
            $('#nota').attr('readonly', true);
            $('#alamat').attr('readonly', true);
            $('#poskod').attr('readonly', true);

            $('#kemaskiniform').trigger('submit');
        }
    }

    $('#btnotp').click(function(){
        $('#customer_detail').modal('hide');
        var noic = $('#noic').val();
        $('#noic_otp').val(noic);
        $('#opt_modal').modal('show');
    });

    $('#jana_otp').click(function(){
        var noic = $('#noic_otp').val();

        $.ajax({
            method:'get',
            url: "{{ route('customer.otp') }}",
            data:{
                'noic_otp' : noic
            },
            dataType:'json',
            success: function(otp_token){
                if(otp_token['error']){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran!',
                        text: otp_token['error']
                    });
                }else if(otp_token['otp']){
                    $('#otp_form').hide();
                    $('#otp_generate').show();
                    $('#otp_number').text(otp_token['otp']);
                }
            },
            error: function(xhRequest, ErrorText, thrownError){
                console.log(xhRequest);
            }
        });
    });
</script>
@endsection