@extends('layouts.app')
@section('content')
<!-- 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'] }}" 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>
                        <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
                                        $daerah = Http::get($api_url . '/api/daerah/' . $customer_info['koddaerah'])->json();
                                    @endphp
                                    <input type="text" readonly name='koddaerah' id='koddaerah' value="{{ $daerah['namadaerah'] }}" 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::get($api_url . '/api/negeri/' . $customer_info['kodnegeri'])->json();
                                    @endphp
                                    <input type="text" readonly name='kodnegeri' id='kodnegeri' value="{{ $negeri['negeri'] }}" class='form-control'>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <div class="mr-5 form-group float-right">
                    <button type="button" class="btn btn-primary" onclick="kemaskinifunc()" id="btnkemaskini">Kemaskini</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">Close</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">Close</button>
            </div>
        </div>
    </div>
</div>



<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 col-lg-12">
            <a href="{{ url('/') }}" class="ion-backspace" style="font-size:50px;color:blue;"></a>
            <h3 class="text-center text-uppercase">maklumat pelanggan</h3>
            
            <div class="form-group row col-md-12">
                <div class="col-md-6">
                    <div class="form-group row">
                        <div class="col-md-4">
                            Nama
                        </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">
                            No Kad Pengenalan
                        </div>
                        <div class="col-md-8">
                            <input type="text" class="form-control" name="noic" id="noic" readonly value="{{ $customer_info['kpbaru'] }}">
                        </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>Belum Tebus
                        </label>
                        <label class="btn btn-primary">
                            <input type="radio" name="options" id="option2" value="sudah_tebus" autocomplete="off">Sudah Tebus
                        </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>
            </div>
            <div class="card">
                <div class="card-body">
                    <table id="myTable">
                        <thead>
                            <tr>
                                <th>Bil</th>
                                <th>No Rujukan</th>
                                <th>Tarikh Gadai</th>
                                <th>Pembiayaan</th>
                                <th>Nilai Marhun</th>
                                <th>Tempoh</th>
                                <th>Keuntungan</th>
                                <th>Tarikh Matang</th>
                                <th>Margin</th>
                                <th>Kos Keuntungan</th>
                                <th>Hapus Gadai</th>
                                <!-- <th>Tebus/Upah</th> -->
                            </tr>
                        </thead>
                    </table>

                    {{-- Sudah Tebus --}}

                    <table id="dahtebusTable">
                        <thead>
                            <tr>
                                <th>Bil</th>
                                <th>No Rujukan</th>
                                <th>Tarikh Gadai</th>
                                <th>Pembiayaan</th>
                                <th>Nilai Marhun</th>
                                <th>Tempoh</th>
                                <th>Keuntungan</th>
                                <th>Tarikh Matang</th>
                                <th>Margin</th>
                                <th>Kos Keuntungan</th>
                                <th>Hapus Gadai</th>
                                <!-- <th>Tebus/Upah</th> -->
                            </tr>
                        </thead>
                    </table>

                    <table id="lelongTable">
                        <thead>
                            <tr>
                                <th>Bil</th>
                                <th>No Rujukan</th>
                                <th>Tarikh Gadai</th>
                                <th>Pembiayaan</th>
                                <th>Nilai Marhun</th>
                                <th>Tempoh</th>
                                <th>Keuntungan</th>
                                <th>Tarikh Matang</th>
                                <th>Margin</th>
                                <th>Kos Keuntungan</th>
                                <th>Hapus Gadai</th>
                                <!-- <th>Tebus/Upah</th> -->
                            </tr>
                        </thead>
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var api_url = "<?php echo $api_url ?>";

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

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

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

    const formatter = new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2
    })
    function gadaiTable(data,jenistebus){
        var counter = 1;

        tablegadai.clear().draw();
        tabledahtebus.clear().draw();
        tablelelong.clear().draw();

        $.each(data,function(index,gadai){
            $.each(gadai, function(index,gadai_detail){

                if(jenistebus == "belum_tebus")
                {
                        var keuntungan_semasa = (gadai_detail['kadarupah']/100)*gadai_detail['bakipjm']*gadai_detail['jbg'];
                        
                        var urlroute = '{{ route("penebusan", ":id") }}';
                        urlroute = urlroute.replace(':id', gadai_detail["norujukan"]);

                        tablegadai.row.add([
                        counter,
                        '<a href=' + urlroute +'>' + gadai_detail['norujukan'] + '</a>',
                        gadai_detail['t_gadai'],
                        'RM '+formatter.format(gadai_detail['pinjaman']),
                        'RM '+ formatter.format(gadai_detail['nilaimarhun']),
                        gadai_detail['jbg'],
                        'RM '+ formatter.format(keuntungan_semasa),
                        gadai_detail['t_matang'],
                        (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                        'RM ' + formatter.format((Number(gadai_detail['kadarupah'])*Number(gadai_detail['pinjaman'])).toFixed(2)),
                        ''
                    ]).draw();
                }
                else if(jenistebus == "sudah_tebus")
                {
                        var keuntungan_semasa = (gadai_detail['kadarupah']/100)*gadai_detail['bakipjm']*gadai_detail['jbg'];
                        tabledahtebus.row.add([
                        counter,
                        gadai_detail['norujukan'],
                        gadai_detail['t_gadai'],
                        'RM '+formatter.format(gadai_detail['pinjaman']),
                        'RM '+ formatter.format(gadai_detail['nilaimarhun']),
                        gadai_detail['jbg'],
                        'RM '+ formatter.format(keuntungan_semasa),
                        gadai_detail['t_matang'],
                        (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                        'RM ' + formatter.format((Number(gadai_detail['kadarupah'])*Number(gadai_detail['pinjaman'])).toFixed(2)),
                        ''
                    ]).draw();
                }
                else if(jenistebus == "lelong")
                {
                        var keuntungan_semasa = (gadai_detail['kadarupah']/100)*gadai_detail['bakipjm']*gadai_detail['jbg'];
                        tablelelong.row.add([
                        counter,
                        gadai_detail['norujukan'],
                        gadai_detail['t_gadai'],
                        'RM '+formatter.format(gadai_detail['pinjaman']),
                        'RM '+ formatter.format(gadai_detail['nilaimarhun']),
                        gadai_detail['jbg'],
                        'RM '+ formatter.format(keuntungan_semasa),
                        gadai_detail['t_matang'],
                        (((Number(gadai_detail['pinjaman'])/Number(gadai_detail['nilaimarhun']))*100).toFixed(2)).toLocaleString("en-GB") + '%',
                        'RM ' + formatter.format((Number(gadai_detail['kadarupah'])*Number(gadai_detail['pinjaman'])).toFixed(2)),
                        ''
                    ]).draw();
                }

                

                counter = counter + 1;
            });
        });




    }
    $(document).ready( function () {
        $('#myTable').parents('div.dataTables_wrapper').first().hide();
        $('#dahtebusTable').parents('div.dataTables_wrapper').first().hide();
        $('#lelongTable').parents('div.dataTables_wrapper').first().hide();

        var noic = $("#noic").val();
        $.ajax({
            method:"GET",
            url: api_url + "/api/customers/"+noic+"/gadai/belum_tebus",
            success: function(data){
                $('#myTable').parents('div.dataTables_wrapper').first().show();
                gadaiTable(data,"belum_tebus");
            }
        });
        $("input[name='options']").click(function(){
            gadaiOptionButton(noic)
        });
    } );

    function gadaiOptionButton(noic){
        tablegadai.clear().draw();
        if($("input[name='options']:checked").val() == 'belum_tebus'){
            
            $('#myTable').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",
                success: function(data){
                    gadaiTable(data,"belum_tebus");
                }
            });
        }
        if($("input[name='options']:checked").val() == 'sudah_tebus'){

            $('#myTable').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",
                success: function(data){
                    gadaiTable(data,"sudah_tebus");
                }
            });
        }
        if($("input[name='options']:checked").val() == 'lelong'){

            $('#myTable').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",
                success: function(data){
                    gadaiTable(data,"lelong");
                }
            });
        }
    }

    function kemaskinifunc()
    {
        $('#btnkemaskini').addClass('btn-danger');
        $('#btnkemaskini').removeClass('btn-primary');
        $('#btnkemaskini').text('Cancel');
        $('#btnkemaskini').attr('onclick','cancelbutton()');
        $('#btnotp').text('Save');
        $('#btnotp').attr('onclick','kemaskinipelanggan()');

        //attribute nak readonly false
        $('#telefon').attr('readonly', false);
        $('#telefon2').attr('readonly', false);

    }

    function cancelbutton()
    {
        $('#btnkemaskini').removeClass('btn-danger');
        $('#btnkemaskini').addClass('btn-primary');
        $('#btnkemaskini').text('Kemaskini');
        $('#btnkemaskini').attr('onclick','kemaskinifunc()');
        $('#btnotp').text('Daftar Akuan Online');
        $('#btnotp').attr('onclick','#');

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

        //attribute nak readonly false
        $('#telefon').attr('readonly', true);
        $('#telefon2').attr('readonly', true);

    }

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

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

                    $.ajax({
                    method:"put",
                    url: api_url + "/api/customersonline/" + nokp,
                    data:{
                            "alamat": alamat,
                            "poskod": poskod,
                            "telefon1": telefon1,
                            "telefon2": telefon2
                        },
                    success: function(success){
                        Swal.fire({
                            icon: 'success',
                            title: 'Berjaya',
                            text: 'Anda telah berjaya mengemaskini maklumat pelanggan'
                        })
                    },
                    error: function (request, status, error) {
                        alert(request.responseText);
                    }

                    });
    

        });



    function kemaskinipelanggan()
    {

        var errortelefon1 = 0;
        var errortelefon2 = 0;
       
        if(!($('#telefon').val().length > 10 && $('#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 > 10 && $('#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('Kemaskini');
            $('#btnkemaskini').attr('onclick','kemaskinifunc()');
            $('#btnotp').text('Daftar Akuan Online');
            $('#btnotp').attr('onclick','#');

            //attribute nak readonly false
            $('#telefon').attr('readonly', true);
            $('#telefon2').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' : noic
            },
            dataType:'json',
            success: function(otp_token){
                console.log(otp_token['error']);
                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){
                // alert('Gadai Tidak Berjaya');
                console.log(xhRequest);
            }
        });
    })


</script>
@endsection
