@extends('layouts.app')

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

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <h3 class="text-center text-uppercase mb-5">LELONGAN</h3>
            <div class="form-group row col-12">

                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            NAMA
                        </div>
                        <div class="col-8">
                        <input type="text" value="{{ $nama }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            NO PELANGGGAN
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['nopelanggan'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            NO RUJUKAN
                        </div>
                        <div class="col-8">
                            <input type="text" id="norujukan" value="{{ $gadai['norujukan'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            NO KAD PENGENALAN
                        </div>
                        <div class="col-8">
                            <input type="text" value="{{ $gadai['nokp'] }}" class="form-control" readonly/>
                        </div>
                    </div>
                </div>
                <div class="col-8">
                    <div class="form-group row">
                        <div class="col-3">
                            JENIS LELONG
                        </div>
                        <div class="col-8">
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" class="custom-control-input" id="radbakilelong" name="radlelong" value="baki" disabled>
                                <label class="custom-control-label" style="color:green;" for="radbakilelong" >Baki Lelong</label>
                              </div>
                              <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" class="custom-control-input" id="radrugilelong" name="radlelong" value="rugi" disabled>
                                <label class="custom-control-label" style="color:red;" for="radrugilelong" >Rugi Lelong</label>
                              </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-4">
                    <div class="form-group row">
                        <div class="col-2">
                            WAKIL
                        </div>
                        <div class="col-8">
                            <input type="text" class="form-control" name="wakil" id="wakiltxt" disabled/>
                        </div>
                        <div class="col-2">
                            <button class="btn btn-primary" id="caribtn" disabled>Cari</button>
                        </div>
                    </div>
                </div>
            </div>

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

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

                            <div class="form-group row">
                                <div class="col-4">
                                   TARIKH
                                </div>
                                <div class="col-8">
                                    <input type="text" value="{{ $lelong['t_lelong'] }}" class="form-control" readonly/>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <div class="col-4">
                                   NO SIRI
                                </div>
                                <div class="col-8">
                                    <input type="text" value="{{ $lelong['sirilel'] }}" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    HARGA JUAL (RM)
                                </div>
                                <div class="col-8">
                                    <input type="text" id="hargajual" value="{{ number_format($lelong['hargajual'],2) }}" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    PEMBIAYAAN (RM)
                                </div>
                                <div class="col-8">
                                    <input type="text" id="pembiayaan" value="{{ number_format($lelong['pinjaman'],2) }}" class="form-control" readonly/>
                                </div>
                            </div>

                        </div>

                        <div class="col-6">

                            <div class="form-group row">
                                <div class="col-4">
                                   BATCH LELONG
                                </div>
                                <div class="col-8">
                                    <input type="text" id="batch" value="{{ $lelong['batchno'] }}" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    KEUNTUNGAN (RM)
                                </div>
                                <div class="col-8">
                                    <input type="text" id="keuntungan" value="{{ number_format($lelong['bakiupah'],2) }}" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    CAJ LELONG (RM)
                                </div>
                                <div class="col-8">
                                    <input type="text" id="cajlelong" value="{{ number_format($lelong['cajlelong'],2) }}" class="form-control" readonly/>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-4">
                                    JUMLAH (RM)
                                </div>
                                <div class="col-8">
                                    <input type="text" id="jumlah" value="{{ number_format($lelong['baki'],2) }}" id="jumlah" class="form-control" readonly/>
                                </div>
                            </div>

                            

                        </div>

                        <div class="col-12 mt-3">
                            <input type="button" class="float-right btn btn-danger mr-2" value="BATAL" onclick="window.location.replace('{{  route('customer_info') }}')">
                            <input type="button" id="terima_transaksi" class="float-right btn btn-primary mr-2" value="TERIMA" onclick="bayarantuntubaki()" disabled>
                        </div>

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



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

<script>

    $(document).ready(function() {

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

        if(jumlahbaki > 0)
        {
            $("#radbakilelong").prop("checked", true);
            $("#radrugilelong").prop("checked", false);
        }else{
            $("#radbakilelong").prop("checked", false);
            $("#radrugilelong").prop("checked", true);
        }
    });

    var api = '<?php echo $api_url ?>';
    let nw = 0;

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

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

            return false;
        }

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

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

        if(wakil.length <= 12)
        {
            $.ajax({
                method:'GET',
                url: "{{ route('wakil.search') }}",
                data:{
                    'wakil' : wakil
                },
                success:function(data){

                    if(data == 'no-data')
                    {
                        Swal.fire({
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonText: 'Daftar',
                        icon: 'info',
                        title: 'Maklumat anda tiada dalam senarai wakil! Tekan button okay untuk mendaftar!'
                        }).then(function(){
                            daftarfunction(wakil);
                        });
                    }else{
                        Swal.fire({
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        confirmButtonText: '<i class="fa fa-thumbs-up"></i> OK!!',
                        icon: 'success',
                        title: 'Maklumat Anda Berjaya Direkodkan!',
                        html: '<b class="text-danger">' + data.nama + '</b><br><b class="text-danger">' + data.nokp + '</b>'
                        });
                        nw = data.nowakil;

                        $('#wakiltxt').prop( "disabled", true );
                        $(e).html("Ubah");
                        $(e).attr("onclick","ubahwakil(this)");
                    }
                
                },error: function (request, status, error) {
                console.log(request.responseText);
            }
            });
        }
        else
        {
            Swal.fire({
                icon: 'error',
                titleText: 'Kad Pengenalan dan Passport',
                text: 'mestilah tidak melebihi dan kurang daripada 12 patah perkataan'
            });
        }
    
    }

    function daftarwakil()
    {
        let nopelanggan = $('#nopelangganwakil').val();
        let nowakil = $('#nowakil').val();
        let nama = $('#namawakil').val();
        let hubungan = $('#slthubungan').val();
        let alamat = $('#alamatwakil').val();
        let telefon = $('#notelwakil').val();
        let nota = $('#notawakil').val();
        let nokp = $('#nokpwakil').val();

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

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

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

            boolnowakil = false;
        }

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

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

            boolnama = false;
        }

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

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

            boolalamat = false;
        }

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

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

            booltelefon = false;
        }

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

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

            boolnota = false;
        }

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

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

            boolnokp = false;
        }


        if(boolnowakil == false && boolnama == false && boolalamat == false && booltelefon == false && boolnota == false && boolnokp == false)
        {
            $.ajax({
                method:'POST',
                url: "{{ route('wakil.create') }}",
                data:{ 
                    "_token": "{{ csrf_token() }}",
                    "nopelanggan" : nopelanggan,
                    "nowakil" : nowakil,
                    "nama" : nama,
                    "hubungan" : hubungan,
                    "alamat" : alamat,
                    "telefon" : telefon,
                    "nota" : nota,
                    "icno" : nokp
                    },
                success:function(data){

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

                        });
                    }

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

            return true;

        }else{
            return false;
        }


    }

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

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

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

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

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

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

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

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

    });


    function daftarfunction(id)
    {
        let kodcaw = "{{ Auth::user()->cawangan }}";
        
        $('#nokpwakil').val(id);

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

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

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

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

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

                        Swal.close();
                        $('#WakilModal').modal();
                        
                    },error: function (request, status, error) {
                        console.log(request.responseText);
                        Swal.close();

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

                    }
                })

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

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

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




    function bayarantuntubaki()
    {

        let norujukan = $('#norujukan').val();
        let api = "{{ config('api.url') }}";
        let nowakil = nw;
        let jenis = '';

        if($("input[name='radlelong']:checked").val() == 'baki')
        {
            jenis = 'T';
            let mohon = "Tuntut Baki Lelongan";
        }else{
            jenis = 'B';
            let mohon = "Bayar Baki Lelongan";
        }

                    
        let batchno = $('#batch').val();let teller = "{{ Auth::user()->name }}";let bakipjm = $('#pembiayaan').val().replace(/[^0-9.-]+/g,"");let bakiupah = $('#keuntungan').val();
        let cajlain = 0.00; let cajlelong = $('#cajlelong').val();
        let jumlah = $('#jumlah').val().replace(/[^0-9.-]+/g,"");let hargajual = $('#hargajual').val().replace(/[^0-9.-]+/g,"");

	$.ajax({
            method: 'put',
            url: "{{ route('lelong.tuntutbaki') }}",
            data: { 
            "_token": "{{ csrf_token() }}",
            'batchno' : batchno,
            'jenis' : jenis,
            'norujukan' : norujukan,
            'teller' : teller,
            'bakipjm' : bakipjm,
            'bakiupah' : bakiupah,
            'cajlain' : cajlain,
            'cajlelong' : cajlelong,
            'jumlah' : jumlah,
            'nowakil' : nowakil,
            'hargajual' : hargajual
            },
            success:function(data){
                let urlroute = '{{ route("resit.tuntutbaki", ":id") }}';
                urlroute = urlroute.replace(':id', norujukan);
                Swal.fire(
                        'Berjaya!',
                        'Tuntut Baki Berjaya',
                        'success'
                    ) .then(function() {
                        window.open(urlroute, '_blank');
                        window.location.replace("{{  route('customer_info') }}");
                    })
            },error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(xhr.responseText);
            }
        });

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

        //let jumlah = $('#jumlah').val();let hargajual = $('#hargajual').val();

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

                    

                    
                    let norujukan = $('#norujukan').val();
                    let api = "{{ config('api.url') }}";
                    let nowakil = 0;
                    let jenis = '';
                    let mohon = '';

                    if($("input[name='radlelong']:checked").val() == 'baki')
                    {
                        jenis = 'T';
                        mohon = "Tuntut Baki Lelongan";
                    }else{
                        jenis = 'B';
                        mohon = "Bayar Baki Lelongan";
                    }

                    
                    
                    let batchno = $('#batch').val();let teller = "{{ Auth::user()->name }}";let bakipjm = $('#pembiayaan').val().replace(/[^0-9.-]+/g,"");let bakiupah = $('#keuntungan').val();
                    let cajlain = 0.00; let cajlelong = $('#cajlelong').val();
                    let jumlah = $('#jumlah').val().replace(/[^0-9.-]+/g,"");let hargajual = $('#hargajual').val().replace(/[^0-9.-]+/g,"");

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

                        var pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
                                            cluster: 'ap1',
                                            encrypted: true
                                            });
                        
                        var channel = pusher.subscribe('notice-ubahhapus');
                        channel.bind('my-ubahhapus', function(data) {


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

                                        $.ajax({
                                            method: 'put',
                                            url: "{{ route('lelong.tuntutbaki') }}",
                                            data: { 
                                            "_token": "{{ csrf_token() }}",
                                            'batchno' : batchno,
                                            'jenis' : jenis,
                                            'norujukan' : norujukan,
                                            'teller' : teller,
                                            'bakipjm' : bakipjm,
                                            'bakiupah' : bakiupah,
                                            'cajlain' : cajlain,
                                            'cajlelong' : cajlelong,
                                            'jumlah' : jumlah,
                                            'nowakil' : nowakil,
                                            'hargajual' : hargajual
                                            },
                                            success:function(data){
                                                let urlroute = '{{ route("resit.tuntutbaki", ":id") }}';
                                                urlroute = urlroute.replace(':id', norujukan);
                                                Swal.fire(
                                                        'Berjaya!',
                                                        'Tuntut Baki Berjaya',
                                                        'success'
                                                    ) .then(function() {
                                                        window.open(urlroute, '_blank');
                                                        window.location.replace("{{  route('customer_info') }}");
                                                    })
                                            },error: function(xhr, status, error) {
                                                        var err = eval("(" + xhr.responseText + ")");
                                                        alert(xhr.responseText);
                                                    }
                                        });
                                        return true;
                                    });
                                }
                                else if(data.kelulusan == 'batal')
                                {
                                    Swal.fire({
                                        icon: 'warning',
                                        title: 'Telah Dibatalkan',
                                        text: `Komen : ${data.komen}`
                                    }).then(function(){
                                        return false;
                                    });
                                }
                            }
                        });


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

</script>
@endsection
