@extends('layouts.app')

@section('content')

<div class="modal fade" id="kelulusanmodal">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <!-- Modal Header -->
        <div class="modal-header">
            <h4 class="text-center">Maklumat Lanjut</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <!-- Modal body -->
        <div class="modal-body">

        <div class="row col-12 text-center">
            <div class="row col-7">
                <label>Nama : </label>
                <span id="namalanjut"> </span>
             </div>

            <div class="row col-5">
                <label>Kad Pengenalan : </label>
                <span id="nokplanjut"> </span>
            </div>
        </div>

        <div class="row mt-3">

          <div class="col-lg-6 col-xl-4 col-12">
            <!-- small box -->
            <div class="small-box bg-info">
              <div class="inner">
                <h4 id="pinjterkumpul"></h4>
                <p>Pembiayaan Terkumpul</p>
              </div>
              <div class="icon">
                <i class="fas fa-money-bill-wave"></i>
              </div>
            </div>
          </div>

          <div class="col-lg-6 col-xl-4 col-12">
            <!-- small box -->
            <div class="small-box bg-success">
              <div class="inner">
                <h4 id="bilaktif"></h4>
                <p>Pembiayaan Belum Selesai</p>
              </div>
              <div class="icon">
                <i class="fas fa-thumbs-up"></i>
              </div>
            </div>
          </div>


          <div class="col-lg-6 col-xl-4 col-12">
            <!-- small box -->
            <div class="small-box bg-danger">
              <div class="inner">
                <h4 id="billelong"></h4>
                <p>Bilangan Lelong</p>
              </div>
              <div class="icon">
                <i class="fas fa-gavel"></i>
              </div>
            </div>
          </div>


        </div>


        </div>
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>


<div class="container">
    <div class="row justify-content-center mt-5">
        <div class="col-md-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 active" aria-current="page">Kelulusan</li>
                    </ol>
                  </nav>


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

                    <div class="row mb-4">
                        <div class="col-2 justify-content-start">

                        </div>
                        <div class="col-8 mt-3 justify-content-center">
                        </div>
                        <div class="col-2">
                        </div>
                    </div>

                    <table class='table table-hover table-striped' id='table-kelulusan' style="width:100%;">
                        <thead class="thead-dark">
                            <tr>
                                <th>No Rujukan</th>
                                <th>Teller</th>
                                <th>Status</th>
                                <th>Nilai Pembiayaan (RM)</th>
                                <th>Nilai Marhun (RM)</th>
                                <th>Berat</th>
                                <th>Margin</th>
                                <th>Tindakan</th>
                            </tr>
                        </thead>
                        <tbody>

                            @php
                                $formatNumber = function($number){
                                    return number_format($number, 2, '.', ',');
                                }
                            @endphp

                            @foreach($kelulusan as $index=>$k)
                            <tr>
                                <td><a href="#" data-toggle="modal" data-target="#kelulusanmodal" data-norujukan="{{ $k['norujukan'] }}">{{ $k['norujukan'] }} </a></td>
                                <td>{{ $k['teller'] }}</td>
                                <td>{{ $k['status'] }}</td>
                                <td>{{ Helper::formatNumber($k['jumpinj']) }}</td>
                                <td>{{ Helper::formatNumber($k['nilaimarhun']) }}</td>
                                <td>{{ $k['berat'] }}</td>
                                <td>{{ $k['margin'] }}</td>
                                <td><button class="btn btn-primary mr-2"  data-pelulus="{{ $k['pelulus'] }}" onclick="updatelulus(this)" data-norujukan="{{ $k['norujukan'] }}" data-siri="{{ $k['siri'] }}"><i class="fas fa-thumbs-up"></i></button>
                                    <button class="btn btn-danger" data-norujukan="{{ $k['norujukan'] }}" data-pelulus="{{ $k['pelulus'] }}" data-siri="{{ $k['siri'] }}" onclick="updatebatal(this)"><i class="fas fa-thumbs-down"></i></button></td>
                            </tr>
                            @endforeach
                            @foreach($kelulusanmohonid as $index=>$km)
                            <tr>
                                <td><a href="#" data-toggle="modal" data-target="#kelulusanmodal" data-norujukan="{{ $km['norujukan'] }}">{{ $km['norujukan'] }} </a></td>
                                <td>{{ $km['teller'] }}</td>
                                <td>{{ $km['mohon'] }}</td>
                                <td>{{ Helper::formatNumber($km['pinjaman']) }}</td>
                                <td>{{ Helper::formatNumber($km['nilaimarhun']) }}</td>
                                <td>{{ $km['berat'] }}</td>
                                <td>{{ $km['margin'] }}</td>
                                <td><button class="btn btn-primary mr-2" onclick="updatelulusmohon(this)" data-norujukan="{{ $km['norujukan'] }}"><i class="fas fa-thumbs-up"></i></button>
                                    <button class="btn btn-danger" onclick="updatebatalmohon(this)" data-norujukan="{{ $km['norujukan'] }}"><i class="fas fa-thumbs-down"></i></button></td>
                            </tr>

                            @endforeach
                        </tbody>
                    </table>

                    <div class="row mt-4 d-flex justify-content-end">

                        <a href="{{ route('khazanah.rekodlepas') }}" class="btn btn-info mr-3 ">Rekod Kelulusan</a>

                    </div>

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

    var tablekelulusan = $('#table-kelulusan').DataTable({
        "scrollX": true
        });

    let api = "{{ config('api.url') }}";
    var kodcaw = "{{ Auth::user()->cawangan }}";

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

    $('#kelulusanmodal').on('show.bs.modal', function(event) {
        let button = $(event.relatedTarget);
        let norujukan = $(button).data('norujukan');

        $.ajax({
          method:'GET',
          url: api + '/api/gadai/norujukan/' + norujukan,
          dataType: 'json',
          success:function(datagadaiwithnorujukan){

            let nokp = datagadaiwithnorujukan[0][0].nokp;

            $.ajax({
                method:'GET',
                url: api + '/api/customers/' + nokp,
                dataType: 'json',
                success:function(datagadaiwithnokp){

                let nama = datagadaiwithnokp.nama;

                $('#namalanjut').text(nama);
                $('#nokplanjut').text(nokp);

                $.ajax({
                    method:'GET',
                    url: api + '/api/gadai/customers/' + nokp + '/outstandingsemasa/' + kodcaw,
                    dataType: 'json',
                    success:function(outstandingsemasa){

                        $('#pinjterkumpul').text('RM' + formatter.format(outstandingsemasa));

                    }
                });


                }
            });

            $.ajax({
            method:'GET',
            url: api + '/api/customers/' + nokp + '/gadai/belum_tebus',
            dataType: 'json',
            success:function(data){
                let bilanganaktif = 0;
                if(data == null)
                {
                    bilanganaktif = 0;
                }else{
                    bilanganaktif = data[0].length;
                }

                $('#bilaktif').text(bilanganaktif);


            }
            });


            $.ajax({
            method:'GET',
            url: api + '/api/customers/' + nokp + '/gadai/lelong',
            dataType: 'json',
            success:function(data){

                let bilanganlelong = 0;

                if(data == null)
                {
                    bilanganlelong = 0;
                }else{
                    bilanganlelong = data.length;
                }


                $('#billelong').text(bilanganlelong);
            }
            });


          }
        });

    });


    async function updatelulus(e)
    {
        let api = "{{ config('api.url') }}";
        let kodcaw = "{{ Auth::user()->cawangan }}";

        const { value: katalaluan } = await Swal.fire({
            title: 'Masukkan Katalaluan Semula',
            input: 'password',
            inputPlaceholder: 'Katalaluan',
            confirmButtonText: 'Hantar',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true
        })

        let dataminta = '';

        $.ajax({
            method:'get',
            url: "{{ route('khazanah.getmintasemulakelulusan') }}",
            async:false,
            data:{ passsemula : katalaluan },
            success:function(data)
            {
                if(data == "False")
                {
                    dataminta = data;
                }
            }
        });

        if(dataminta == 'False')
        {
            Swal.fire({
                    icon: 'error',
                    title: 'Pengesahan Katalaluan Tidak Berjaya'
                })
            event.preventDefault();
            return false;
        }

        var { value: komenkelulusan } = await Swal.fire({
            title: 'Masukkan Komen!',
            input: 'radio',
            customClass: {
                input: 'custom-radio'
            },
            inputOptions: {
                'Pelanggan Baru': 'Pelanggan Baru',
                'Pelanggan Tetap': 'Pelanggan Tetap',
                'Rekod Gadaian Baik': 'Rekod Pembiayaan Baik',
                'Lain2': 'Lain-Lain'
            },
            confirmButtonText: 'Hantar',
            showCancelButton:false,
            allowOutsideClick: false
        })

        if(komenkelulusan === 'Lain2')
        {
            var { value: komenkelulusan } = await Swal.fire({
            title: 'Masukkan Komen!',
            input: 'text',
            inputPlaceholder: 'Komen',
            confirmButtonText: 'Hantar',
            showCancelButton:false,
            allowOutsideClick: false
            });
        }


        let teller = $(e).closest('tr').children('td:eq(1)').text();
        let nm = $(e).closest('tr').children('td:eq(4)').text();
        let ber = $(e).closest('tr').children('td:eq(5)').text();
        let marg = $(e).closest('tr').children('td:eq(6)').text();

        // let komen = komenkelulusan + '|' + nm + "|" + ber +  "|" + marg + "|";
        let komen = '';


        let norujukan = $(e).data('norujukan');
        let pelulus = $(e).data('pelulus');
        let siri = $(e).data('siri');
        let namakhazanah = "{{ Auth::user()->name }}";

        teller = String(teller);

        $.ajax({
            method:'put',
            url: "{{ route('khazanah.updatekelulusan') }}",
            data: {
                "_token": "{{ csrf_token() }}",
                "norujukan" : norujukan,
                "pelulus" : pelulus,
                "siri" : siri,
                "komen" : komenkelulusan,
                "margin" : marg,
                "nilaimarhun" : nm,
                "berat" : ber,
                "status" : status,
                "namakhazanah" : namakhazanah,
                "teller" : teller
            },
            success:function(data){
                Swal.fire({
                    icon: 'success',
                    title: 'Pengesahan Berjaya'
                }).then(function(){
                    location.reload();

                });

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

    async function updatebatal(e)
    {
        const { value: katalaluan } = await Swal.fire({
            title: 'Masukkan Katalaluan Semula',
            input: 'password',
            inputPlaceholder: 'Katalaluan',
            confirmButtonText: 'Hantar',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true
        })

        let dataminta = '';

        $.ajax({
            method:'get',
            url: "{{ route('khazanah.getmintasemulakelulusan') }}",
            async:false,
            data:{ passsemula : katalaluan },
            success:function(data)
            {
                if(data == "False")
                {
                    dataminta = data;
                }
            }
        });

        if(dataminta == 'False')
        {
            Swal.fire({
                    icon: 'error',
                    title: 'Pengesahan Katalaluan Tidak Berjaya'
                })
            event.preventDefault();
            return false;
        }

        var { value: komenkelulusan } = await Swal.fire({
            title: 'Masukkan Komen!',
            input: 'text',
            inputPlaceholder: 'Komen',
            confirmButtonText: 'Hantar',
            showCancelButton:false,
            allowOutsideClick: false
        })

        let teller = $(e).closest('tr').children('td:eq(1)').text();
        let norujukan = $(e).data('norujukan');
        let pelulus = $(e).data('pelulus');
        let siri = $(e).data('siri');
        let namakhazanah = "{{ Auth::user()->name }}";

        teller = String(teller);

        $.ajax({
            method:'put',
            url: "{{ route('khazanah.updatekelulusan') }}",
            data: {
                "_token": "{{ csrf_token() }}",
                "norujukan" : norujukan,
                "pelulus" : pelulus,
                "siri" : siri,
                "komenkelulusan" : komenkelulusan,
                "pembatalan" : "batal",
                'namakhazanah' : namakhazanah,
                'teller' : teller

            },
            success:function(data){
                Swal.fire({
                    icon: 'success',
                    title: 'Pengesahan Berjaya Dibatalkan'
                }).then(function(){
                    location.reload();

                });

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


    async function updatelulusmohon(e)
    {

        const { value: katalaluan } = await Swal.fire({
            title: 'Masukkan Katalaluan',
            input: 'password',
            inputPlaceholder: 'Katalaluan',
            confirmButtonText: 'Hantar',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true
        })

        let dataminta = '';

        $.ajax({
            method:'get',
            url: "{{ route('khazanah.getmintasemulakelulusan') }}",
            async:false,
            data:{ passsemula : katalaluan },
            success:function(data)
            {
                if(data == "False")
                {
                    dataminta = data;
                }
            }
        });

        if(dataminta == 'False')
        {
            Swal.fire({
                    icon: 'error',
                    title: 'Pengesahan Katalaluan Tidak Berjaya'
                })
            event.preventDefault();
            return false;
        }


        let norujukan = $(e).data('norujukan');
        let teller = $(e).closest('tr').children('td:eq(1)').text();
        let namakhazanah = "{{ $auth_user = Auth::user()->name }}";

        teller = String(teller);

        $.ajax({
            method:'put',
            url: "{{ route('khazanah.updatekelulusan') }}",
            data: {
                "_token": "{{ csrf_token() }}",
                "norujukan" : norujukan,
                "khazanah" : namakhazanah,
                'teller' : teller
            },
            success:function(data){

                Swal.fire({
                    icon: 'success',
                    title: 'Pengesahan Berjaya'
                }).then(function(){
                    location.reload();
                });

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


    async function updatebatalmohon(e)
    {
        const { value: katalaluan } = await Swal.fire({
            title: 'Masukkan Katalaluan Semula',
            input: 'password',
            inputPlaceholder: 'Katalaluan',
            confirmButtonText: 'Hantar',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true
        })

        let dataminta = '';

        $.ajax({
            method:'get',
            url: "{{ route('khazanah.getmintasemulakelulusan') }}",
            async:false,
            data:{ passsemula : katalaluan },
            success:function(data)
            {
                if(data == "False")
                {
                    dataminta = data;
                }
            }
        });

        if(dataminta == 'False')
        {
            Swal.fire({
                    icon: 'error',
                    title: 'Pengesahan Katalaluan Tidak Berjaya'
                })
            event.preventDefault();
            return false;
        }

        const { value: komenkelulusan } = await Swal.fire({
            title: 'Masukkan Komen Daripada Khazanah',
            input: 'text',
            inputPlaceholder: 'Komen',
            confirmButtonText: 'Hantar',
            showCancelButton:false,
            allowOutsideClick: false
        })

        let norujukan = $(e).data('norujukan');
        let namakhazanah = "{{ $auth_user = Auth::user()->name }}";
        let teller = $(e).closest('tr').children('td:eq(1)').text();

        teller = String(teller);

        $.ajax({
            method:'put',
            url: "{{ route('khazanah.updatekelulusan') }}",
            data: {
                "_token": "{{ csrf_token() }}",
                "norujukan" : norujukan,
                "khazanah" : namakhazanah,
                "komenubahhapus" : komenkelulusan,
                "batal" : 'batal',
                'teller' : teller

            },
            success:function(data){

                console.log(data);

                Swal.fire({
                    icon: 'success',
                    title: 'Pengesahan Berjaya'
                }).then(function(){
                    location.reload();
                });

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


    }

</script>
@endsection
