@extends('layouts.app')

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


@section('content')
@include('modal.historytebus')
@include('modal.wakil')
@include('modal.agh')


<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 col-lg-12">
        <div class="card">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb pb-3">
                  <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                  <li class="breadcrumb-item"><a href="{{ route('khazanah.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
                                $outstanding_semasa = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/gadai/customers/'. $customer_info['kpbaru'] .'/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>Limit Pembiayaan </b>
                        </div>
                        <div class="col-md-8">
                            @php
                                $limit_pinjaman_semasa = 0;
                            @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'] }}">
                        </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>

            <!-- footer card -->
            <div class="mr-4 form-group d-flex justify-content-end">
    <button class="btn btn-primary button-spacing" data-toggle="modal" data-target="#customer_detail">Maklumat Pelanggan</button>
</div>

</div>

</div>

    <!-- button -->

    <div class="col-md-10 mt-md-2 justify-content-between form-group row">

      <div class="btn-group btn-group-toggle d-flex flex-fill" data-toggle="buttons">
        <label class="btn btn-secondary flex-fill">
            <input type="radio" name="options" id="option1" value="belum_tebus" autocomplete="off" checked>Pembiayaan Belum Selesai
        </label>
        <label class="btn btn-secondary flex-fill">
            <input type="radio" name="options" id="option2" value="sudah_tebus" autocomplete="off">Pembiayaan Sudah Selesai
        </label>
        <label class="btn btn-secondary flex-fill">
            <input type="radio" name="options" id="option3" value="lelong" autocomplete="off">Lelong
        </label>
      </div>
    </div>
            </div>



            <div class="card">
                <div class="card-body">
                    <nav class="mb-3">
                        <div class="nav nav-tabs" id="nav-tab" role="tablist">
                            @php
                            $activate_tab = request()->session()->pull('activate_tab', 'SAG_lama');

                            $activate_tab_SAG_baru = $activate_tab === 'SAG_baru' ? 'active' : '';
                            $aria_selected_SAG_baru = $activate_tab === 'SAG_baru' ? 'true' : 'false';
                            $activate_pane_SAG_baru = $activate_tab === 'SAG_baru' ? 'active show' : '';

                            $activate_tab_SAG_lama = $activate_tab === 'SAG_lama' ? 'active' : '';
                            $aria_selected_SAG_lama = $activate_tab === 'SAG_lama' ? 'true' : 'false';
                            $activate_pane_SAG_lama = $activate_tab === 'SAG_lama' ? 'active show' : '';

                        @endphp
                            <a class="nav-item nav-link {{ $activate_tab_SAG_baru }}" id="nav-tawarruq-tab" data-toggle="tab" href="#nav-tawarruq" role="tab" aria-controls="nav-tawarruq" aria-selected="{{ $aria_selected_SAG_baru }}">SAG Baru</a>
                            <a class="nav-item nav-link {{ $activate_tab_SAG_lama }}" id="nav-xtawarruq-tab" data-toggle="tab" href="#nav-xtawarruq" role="tab" aria-controls="nav-xtawarruq" aria-selected="{{ $aria_selected_SAG_lama }}"><span id="textnavsag">SAG Lama</span></a>
                        </div>
                    </nav>
                    <div class="tab-content" id="navtawarruqdannottawarruq">
                        <div class="tab-pane fade {{ $activate_pane_SAG_baru }}" 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 {{ $activate_pane_SAG_lama }}" 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 Gadai</th>
                                        <th>Tarikh Matang</th>
                                        <th>Pembiayaan</th>
                                        <th>Margin</th>
                                        <th>Tempoh</th>
                                        <th>Lelong</th>
                                    </tr> --}}
                                    <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>

                    {{-- 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 Pembiayaan</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>
                            </tr>
                        </thead>
                    </table>

                    <div class="text-center">
                        <button class="btn btn-primary" onclick="histfunc()">Rekod Pembiayaan</button>
                        <button class="btn btn-primary" onclick="saghilangfunc()">Surat Akuan Hilang</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'] }}" 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'] }}" 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'>
                                    Pekerjaan
                                </div>
                                <div class='col-md-7'>
                                    @php
                                    $pekerjaan = Http::withOptions(['verify' => config('app.api_verify')])->get($api_url . '/api/pekerjaan')->json();
                                    @endphp
                                    <select class="form-control" name="kodkerja" data-placeholder="Pilih Pekerjaan" id="kodkerja" disabled="true">
                                        <option value="-" selected disabled>-</option>
                                        @foreach($pekerjaan as $kerja)
                                        <option value="{{ $kerja['kodkerja'] }}" {{ $kerja['kodkerja'] == $customer_info['kodkerja'] ? 'selected' : '' }}>
                                            {{ $kerja['keterangan'] }}
                                        </option>
                                        @endforeach
                                    </select>
                                    <div id="pekerjaan-lain-container" style="display: {{ $customer_info['kodkerja'] == '6' ? 'block' : 'none' }}; margin-top: 10px;" >
                                        <input type="text" class="form-control" id="nota_pekerjaan" name="nota_pekerjaan" placeholder="Sila Nyatakan" value="{{ $customer_info['nota_pekerjaan'] ?? '' }}" disabled="true"
                                        oninput="this.value = this.value.replace(/[^a-zA-Z ]/g, '');">
                                    </div>
                                </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'] }}</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'] }}" 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_url = "<?php echo $api_url ?>";
    var kodcaw = "{{ $cawangan_info['kodcaw'] }}";
    var ppc = "{{ Auth::user()->name }}";
    var tagarrahnbid = "{{ $cawangan_info['tagarrahnbid'] }}";
    var api_arrahnbid = "<?php echo config('app.api_arrahnbid') ?>";



    //Pusher for AGH

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

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

            if(data.kodcaw.toUpperCase() === kodcaw.toUpperCase() && data.pc.toUpperCase() === ppc.toUpperCase())
            {
                Swal.fire({
                    icon: data.typeerror,
                    title: data.message
                }).then(function(){
                    $('#AGHModal').hide();
                    location.reload();
                });
            }

        });


    //End Pusher for AGH



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

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

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

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

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

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

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

     async function checkPS(norujukan){
        let gadai_tawarruq = fetch(api_url + '/api/gadai/norujukan/' + norujukan );

        return response = await gadai_tawarruq
            .then(response => response.json())
            .then(response => response[0][0])
            .then(gadaian => {
                return { historygadaian: gadaian.historygadaian, tag_tebus: gadaian.tag_tebus };
            })
            .then(data => {
                if(data.historygadaian == '0' || data.historygadaian === null || data.historygadaian.length === 0) {
                    return false;
                }else{
                    if(data.tag_tebus == 'AT'){
                        return true;
                    }else{
                        return false;
                    }
                }

                return true;
            })
    }

    function checkserah(data){
        var urlpenebusan = $(data).data("url");
        var norujukan = $(data).data("norujukan");
        $.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'
                    });
                }
            }
        });
    }

    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){
    let jeniskeuntungan = (gadai_detail['tagbaru'] == 1) ? 'onepercent' : 'asal';
    $.ajax({
        method:'get',
        url:api_url + '/api/upahtawarruq/'+ gadai_detail['kodcaw'] +'/' + gadai_detail['norujukan'],
        data: {
            'jeniskeuntungan' : jeniskeuntungan
        },
        success:function(upahsemasa){
            if(jenistebus == "belum_tebus"){
                var urlroute = '{{ route("penebusan", ":id") }}';
                urlroute = urlroute.replace(':id', gadai_detail["norujukan"]);

                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){
                    $('#textnavsag').addClass('text-danger');
                    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;
                                        }
                                    });
                                }
                            }

                    let table_norujukan = gadai_detail["norujukan"];
                    // let radio_action = "onclick=checkCanChangeGadaianDetail(" + "'" + table_norujukan + "'" + ")";

                    if(gadai_detail["percentpinj"] != 0)
                    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'],
                        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{
                    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;
                                }
                            });
                        }
                    }

                    let table_norujukan = gadai_detail["norujukan"];
                    // let radio_action = "onclick=checkCanChangeGadaianDetail(" + "'" + table_norujukan + "'" + ")";
                    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['pendapatan'],
                        '<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([
                       '<input type="radio" value='+ gadai_detail["norujukan"] +' name="lelong"/>',
                        '<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([
                        '<input type="radio" value='+ gadai_detail["norujukan"] +' name="lelong"/>',
                        '<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 checkAGH()
    {
        $('#AGHModalEdit').modal('hide');
        var daerahagh = $('#daerahagh').val();

        if(daerahagh == 'No-Data')
        {
            $('#errordaerah').addClass('visible');
            $('#errordaerah').removeClass('invisible');
            return false;
        }else{
            $('#errordaerah').addClass('invisible');
            $('#errordaerah').removeClass('visible');
            return true;
        }

    }

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

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

        if (tarikhtuntut == null)
        {
            window.location.href = urlroute;
        }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);
        });
    });

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

                let checkps = await checkPS(histid);

                $.ajax({
                    method:'get',
                    url:'{{ route("gadai.history.khazanah") }}',
                    data:{ "norujukan" : histid},
                    success:function(data)
                    {
                        Swal.close();
                        $('#historytebusModal').modal();
                        historytebustable(data,checkps);
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });
                $.ajax({
                    method: 'get',
                    url: api_url + '/api/transaction/' + histid,
                    success: function(data){
                        historybayarantable(data,checkps);
                    }
                });
                $.ajax({
                    method:'get',
                    url: api_url + '/api/gadai/norujukan/'+histid,
                    success:function(gadai){
                        rekodasal(gadai);
                    }
                });
            }
        }else if($("input[name='options']:checked").val() == 'sudah_tebus'){
            let histid = $('input[name="sudahtebus"]:checked').val();

            let checkps = await checkPS(histid);

            if(histid == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Sila pilih salah satu SAG'
                });
            }else{
                $.ajax({
                    method:'get',
                    url:'{{ route("gadai.history.khazanah") }}',
                    datatype:'json',
                    data:{ "norujukan" : histid},
                    success:function(data){
                        $('#historytebusModal').modal();
                        historytebustable(data,checkps);
                    },error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(xhr.responseText);
                    }
                });
                $.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);
                    }
                });
            }
        }
    }

    function ulangcetakagh(e)
    {
        var kodnegeri = $(e).data('kodnegeri');
        var koddaerah = $(e).data('koddaerah');
        var noruj = $(e).data('histid');

        if(kodnegeri !== null && koddaerah !== null && kodnegeri !== '' && koddaerah !== '')
        {
            if($("input[name='options']:checked").val() == 'belum_tebus' || $("input[name='options']:checked").val() == 'lelong'){

                let histid = '';
                if($("input[name='options']:checked").val() == 'belum_tebus'){
                    histid = $('input[name="belum"]:checked').val();
                }
                else{
                    histid = $('input[name="lelong"]:checked').val();
                }

                if(histid == null){
                    Swal.fire({
                        icon: 'error',
                        title: 'Amaran',
                        text: 'Sila pilih salah satu SAG'
                    });
                }else{
                    let urlroute = '{{ route("agh.ulangcetak", ":id") }}';
                    urlroute = urlroute.replace(':id', histid);
                    window.open(urlroute, '_blank');
                    swal.close();
                }
            }
        }else{
            $('#AGHModalEdit').modal('show');
            $('#norujukanhiddenedit').val(noruj);
            swal.close();
        }

        return;
    }

    function saghilangfunc()
    {
        if($("input[name='options']:checked").val() == 'belum_tebus' || $("input[name='options']:checked").val() == 'lelong'){

            let histid = '';
            if($("input[name='options']:checked").val() == 'belum_tebus'){
                histid = $('input[name="belum"]:checked').val();
            }
            else{
                histid = $('input[name="lelong"]:checked').val();
            }

            if(histid == null){
                Swal.fire({
                    icon: 'error',
                    title: 'Amaran',
                    text: 'Sila pilih salah satu SAG'
                });
            }else{
                $.ajax({
                    method:'get',
                    url: api_url + '/api/polis/get',
                    data:{ "norujukan" : histid,"kodcaw" : kodcaw},
                    success:function(data)
                    {

                        var count = Object.keys(data).length;
                        if(count > 0)
                        {
                            Swal.fire({
                                allowOutsideClick: false,
                                allowEscapeKey: false,
                                allowEnterKey: false,
                                showConfirmButton: false,
                                html:   "<br>" +
                                        '<button type="button" role="button" tabindex="0" class="btn btn-primary mr-1" onclick="swal.close()">' + 'Okay' + '</button>' +
                                        '<button type="button" role="button" tabindex="0" class="btn btn-primary" data-histid="' + histid + '" onclick="ulangcetakagh(this)" data-koddaerah="' + data[0].koddaerah + '" data-kodnegeri="' + data[0].kodnegeri + '">' + 'Ulang Cetak' + '</button>',
                                icon: 'error',
                                title: 'Surat Akuan Gadai Hilang telah dikeluarkan!'
                            });
                        }else{
                            $('#AGHModal').modal('show');
                            $('#norujukanhidden').val(histid);
                        }


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

            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Cetakan Surat Akuan Hilang tidak dibenarkan'
            });
        }


//        }else if($("input[name='options']:checked").val() == 'lelong'){
//            let histid = $('input[name="sudahtebus"]:checked').val();
//
//            Swal.fire({
//                icon: 'error',
//                title: 'Amaran',
//                text: 'Cetakan Surat Akuan Hilang tidak dibenarkan'
//            });
//
//        }

    }

    $('#negeriagh').change(function(){

        var daerahselect = document.getElementById("daerahagh");

        $('#daerahagh').attr('disabled', false);
        $(daerahagh).empty();
        $.ajax({
            method:'get',
            url: api_url + '/api/daerahkodnegeri/' + this.value,
            success:function(data){
                $.each(data, function( index, daerah ){
                    addOption(daerah.koddaerah,daerah.namadaerah);
                });
            }
        });

    });

    $('#negeriaghedit').change(function(){

        var daerahselect = document.getElementById("daerahaghedit");

        $('#daerahaghedit').attr('disabled', false);
        $(daerahagh).empty();
        $.ajax({
            method:'get',
            url: api_url + '/api/daerahkodnegeri/' + this.value,
            success:function(data){
                $.each(data, function( index, daerah ){
                    addOptionEdit(daerah.koddaerah,daerah.namadaerah);
                });
            }
        });

    });

    function addOption(textopt,valueopt) {

        optionText = textopt;
        optionValue = valueopt;

        $('#daerahagh').append(`<option value='${optionText}'>${optionValue}</option>`);
    }

    function addOptionEdit(textopt,valueopt) {

        optionText = textopt;
        optionValue = valueopt;

        $('#daerahaghedit').append(`<option value='${optionText}'>${optionValue}</option>`);
    }



    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 historybayarantable(data){
        var counter = 1;

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

            var urlroute = '{{ route("resit.khazanah.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,checkps = false){

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

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

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

                    }else{

                        // if(tebusaz['historygadaian'] != '' || tebusaz['historygadaian'] != 0 || tebusaz['historygadaian'] != null){
                        //     var urlroute = '{{ route("resit.autotawarruq", ":id") }}';
                        //     urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                        // }else{
                        //     var urlroute = '{{ route("resit.khazanah.tebus", ":id") }}';
                        //     urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                        // }

                        if(checkps){
                            var urlroute = '{{ route("resit.autotawarruq", ":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.khazanah.belumansurans", ":id") }}';
                    urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                    break;
                case 'S':
                var urlroute = '{{ route("resit.khazanah.tebusseparuh", ":id") }}';
                urlroute = urlroute.replace(':id', tebusaz['norujukan']);
                break;
                }

            historytebusbayaran.row.add([
                counter,
                tebusaz['norujukan'],
                (checkps && tebusaz['jenistebus'] == 'A') ? 'PS' : (tebusaz['jenistebus'] == 'A') ? 'PS' : 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);
            }

        });
    }


    $('#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 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");
                }
            });
        }
    }

    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);
        $('#kodkerja').attr('disabled', false);
        $('#nota_pekerjaan').attr('disabled', false);
        $('#noakaun').attr('readonly', false);
        $('#nota').attr('readonly', false);
        $('#nama').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);
        $('#kodkerja').attr('disabled', true);
        $('#nota_pekerjaan').attr('disabled', true);
        $('#noakaun').attr('readonly', true);
        $('#nota').attr('readonly', true);
        $('#nama').attr('readonly', true);
        $('#alamat').attr('readonly', true);
        $('#poskod').attr('readonly', true);

        /* Error Telefon */
        $('#errortelefon').hide();
        $('#errortelefon').text("");
        $('#telefon').removeClass('is-invalid');

        $('#errortelefon2').hide();
        $('#errortelefon2').text("");
        $('#telefon2').removeClass('is-invalid');
    }

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

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

        $.ajax({
            method:"put",
            url: api_url + "/api/customers/update/khazanah/" + nokp,
            data:{
                "namakhazanah" : ppc,
                "telefon1": telefon1,
                "telefon2": telefon2,
                "kodbank":kodbank,
                "kodkerja":kodkerja,
                "nota_pekerjaan":nota_pekerjaan,
                "noakaun":noakaun,
                'nota':nota,
                'nama':nama,
                'alamat':alamat,
                'poskod':poskod,
                'kodcaw':kodcaw
            },
            success: function(success){
                $('#btnsave').css('display','none');
                $('#btnotp').show();
                if(success == 1){
                    Swal.fire({
                        icon: 'success',
                        title: 'Berjaya',
                        text: 'Berjaya mengemaskini maklumat pelanggan'
                    }).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);
            $('#kodkerja').attr('disabled', true);
            $('#nota_pekerjaan').attr('disabled', true);
            $('#nota').attr('readonly', true);
            $('#nama').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);
            }
        });


    });

    document.addEventListener('DOMContentLoaded', function(){
        $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
            $($.fn.dataTable.tables(true)).DataTable()
                .columns.adjust();
        });
    });
</script>

<script>
    $('#kodkerja').on('change', function() {
    var lainContainer = $('#pekerjaan-lain-container');
    if ($(this).val() === '6') {
        lainContainer.show();
    } else {
        $('#pekerjaan-lain').val('');
        lainContainer.hide();
    }
});
</script>
@endsection
