@extends('layouts.app')
@section('content')
@include('modal.permohonanwang')
@include('modal.CITModal')
@include('modal.denominasipermohonan')

<div class="container">
    <div class="row justify-content-center">
        <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">Permohonan</li>
                    </ol>
                </nav>

                <div class="card-body mx-auto col-12">   
                    
                    @if(session()->has('message'))
                    <div class="alert alert-success">
                        {{ session()->get('message') }}
                    </div>
                    @endif

                    @if(session()->has('error'))
                    <div class="alert alert-danger">
                        {{ session()->get('error') }}
                    </div>
                    @endif

                    <div class="mx-auto d-flex justify-content-center col-12">
                        <div class="col-4">
                            <div class="small-box bg-warning text-center"><div class="inner"><b>Peti Besi: <span>RM {{ number_format($getVault,2) }}</span></b></div></div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between mb-2">
                        <h5 class="mt-2">Senarai Permohonan Masih Aktif</h5>
                        <div>
                            <button class="btn btn-info" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#PermohonanWang">Mohon</button>
                            <a class="btn btn-info" href="{{ route('permohonan.rekod') }}">Rekod Permohonan</a>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <table class="table table-striped table-hover" id="permohonantable">
                                <thead class="thead-dark text-center">
                                    <tr>
                                        <th>Bil</th>
                                        <th>No Permohonan</th>
                                        <th>Tarikh Mohon</th>
                                        <th>Jumlah Mohon (RM)</th>
                                        <th>Semak</th>
                                        <th>Jenis Permohonan</th>
                                        <th>Tindakan</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($permohonan as $mohon)
                                    <tr class="text-center">
                                        <td>{{ $loop->iteration }}</td>
                                        <td>{{ $mohon['nopermohonan'] }}</td>
                                        <td>{{ $mohon['tarikh_permohonan'] }}</td>
                                        <td>{{ number_format($mohon['amaun_mohon'],2) }}</td>
                                        <td>
                                            <a href="{{ route('permohonan.status', ['mohonid' => $mohon['nopermohonan']]) }}" class="btn btn-info"><i class="fas fa-eye"></i></a>
                                        </td>
                                        <td>{{ $mohon['jenismohon'] }}</td>
                                        <td>
                                            @php
                                                if($mohon['tagdeposit'] === 1)
                                                {
                                                    echo '<button data-amaun="' . $mohon["jumlah_diluluskan"] . '" data-mohonid="' . $mohon["nopermohonan"] . '" id="btnterima" class="btn btn-success">Telah disahkan</button>';
                                                }else if(($mohon['tagcit'] === 0 && $mohon['jenismohon'] === 'bayaranbalik'))
                                                {
                                                    echo '<button data-mohonid="' . $mohon["nopermohonan"] . '" id="btncit" class="btn btn-secondary"  data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#CITModal">CIT</button>';
                                                }
                                                else{
                                                    if($mohon['tagjanapc'] == 0)
                                                    {
                                                        echo '<button class="btn btn-info"  data-mohonid="' . $mohon["nopermohonan"] . '" onclick="janasurat(this)">JANA SURAT</button>';
                                                    }else if($mohon['tagjanapc'] == 1)
                                                    {
                                                        echo '<button class="btn btn-info" data-mohonid="' . $mohon["nopermohonan"] . '" onclick="muatnaiksurat(this)">MUAT NAIK</button>';
                                                    }else{
                                                        echo '<span class="p-2 badge badge-info">DALAM PROSES</span>';
                                                    }
                                                }
                                            @endphp

                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script src="{{ asset('js/main.js') }}"></script>
<script type="text/javascript">

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

    var api_url = '{{ $api_url }}';

    $('#PermohonanWang').on('hidden.bs.modal', function (e) {
    $(this)
        .find("input[name='jumlahmohon']")
        .val('')
        .removeClass('is-invalid')
        .end()
        .find("input[type=checkbox], input[type=radio]")
        .prop("checked", "")
        .end();

    $("#erroramaun").hide();
    $("#pilihper").hide();

    })

    $('#CITModal').on('shown.bs.modal', function (e) {
    
        let mohon = $('#btncit').data('mohonid');
        $('#mohonid').val(mohon);

    });

    function funcbatal()
        {
            $('#denominasiHQModal').modal('hide');
            // $('#pendahuluanserahanModal').modal('show');

            $("#terima_transaksi").prop('disabled', false);

            $('#bundle1').val('');
            $('#totalb1').val(0.00);
            $('#bundle5').val('');
            $('#totalb5').val(0.00);
            $('#bundle10').val('');
            $('#totalb10').val(0.00);
            $('#bundle20').val('');
            $('#totalb20').val(0.00);
            $('#bundle50').val('');
            $('#totalb50').val(0.00);
            $('#bundle100').val('');
            $('#totalb100').val(0.00);
            $('#amaunkiraan').val('');
        }

    function funcpermohonan(){

        let amaun = $('#jumlahmohon').val();
        // let tarikh = $('#tarikhmohon').val();
        let jenis = $('#radwang:checked').val();
        let petibesi = $('#bakipetibesi').val();
        let outstanding = $('#outstanding').val();

        let boolamaun = false;let booljenis = false;

        if(amaun === ''){
            $("#erroramaun").show();
            // $("[name='erroramaun']").text("*Isikan amaun dalam input!");
            $("[name='jumlahmohon']").addClass('is-invalid');
            boolamaun = true;
        }else{
            $("#erroramaun").hide();
            $("[name='jumlahmohon']").removeClass('is-invalid');
            boolamaun = false;
        }

        if(!jenis)
            {
                $("#pilihper").show();

                booljenis = true;
            }else{
                $("#pilihper").hide();

                booljenis = false;
            }

        if(boolamaun === false && booljenis === false)
        {
            $("#terima_permohonan").prop('disabled', true);
            $('#permohonanform').submit();

            return true;
        }else{

            $("#terima_permohonan").prop('disabled', false);

            event.preventDefault();
            return false;
        }
    }

    $(document).on('click', '#btnterima', function(e) {
        let nama = "{{ Auth::user()->name }}";
        let mid = $(this).data("mohonid");
        let amaun = $(this).data("amaun");

        Swal.fire({
            title: 'Adakah wang sudah diterima?',
            showDenyButton: true,
            showCancelButton: false,
            confirmButtonText: 'Terima',
            denyButtonText: `Belum`,
            allowOutsideClick: false
            }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {

                $('#denominasiPermohonan').modal('show');
                $('#amaundiminta').val(amaun);
                $('#mohonidpermohonan').val(mid);

            } else if (result.isDenied) {
                // Swal.fire('Belum Diterima!', '', 'info')
            }
        });
    });

    function terimapermohonanwang()
    {
        $("#terima_transaksi").prop('disabled', true);

        let amaun = $('#amaundiminta').val();
        let kiraan = $('#amaunkiraan').val();
        let keterangan = 'Pendahuluan Wang Daripada HQ';
        let jenis = 'pendahuluan';
        let dtacct = '1000/010';
        let ktacct = '7000/102';
        let kodcaw = "{{ Auth::user()->cawangan }}";
        let teller = "{{ Auth::user()->name }}";
        let mid = $('#mohonidpermohonan').val();

        //denominasi bundle
        let bundle1 = $('#bundle1').val();let bundle5 = $('#bundle5').val();let bundle10 = $('#bundle10').val();
        let bundle20 = $('#bundle20').val();let bundle50 = $('#bundle50').val();let bundle100 = $('#bundle100').val();

        //denominasi keping
        let sen1 = $('#sen1').val();let sen5 = $('#sen5').val();let sen10 = $('#sen10').val();let sen20 = $('#sen20').val();let sen50 = $('#sen50').val();
        let ringgit1 = $('#ringgit1').val();let ringgit5 = $('#ringgit5').val();let ringgit10 = $('#ringgit10').val();let ringgit20 = $('#ringgit20').val();let ringgit50 = $('#ringgit50').val();
        let ringgit100 = $('#ringgit100').val();

        if(Number(amaun) !== Number(kiraan))
        {
            Swal.fire({
                icon: 'error',
                title: 'Sila Periksa Amaun dan Kiraan.'
            });

            return false;
        }

        Swal.fire({
            title: 'Memuatkan...',
            allowEscapeKey : false,
            allowOutsideClick: false,
            didOpen: function () {
                Swal.showLoading();
                $('#denominasiPermohonan').modal('hide');
            }
        });

        $.ajax({
            method: 'post',
            url: '{{ route("khazanah.pendahuluanserahanHQ") }}',
            data: {
                "_token": "{{ csrf_token() }}",
                'amaun' : amaun,
                'jenisgldetail' : jenis,
                'keterangan' : keterangan,
                'kodcaw' : kodcaw,
                'teller' : teller,
                'dtacct' : dtacct,
                'ktacct' : ktacct,
                'ambilansen1' : sen1,
                'ambilansen5' : sen5,
                'ambilansen10' : sen10,
                'ambilansen20' : sen20,
                'ambilansen50' : sen50,
                'ambilanring1' : ringgit1,
                'ambilanring5' : ringgit5,
                'ambilanring10' : ringgit10,
                'ambilanring20' : ringgit20,
                'ambilanring50' : ringgit50,
                'ambilanring100' : ringgit100
            },
            success:function(data){
                if(data == 'LULUS'){

                    Swal.fire({
                        icon: 'success',
                        title: 'Transaksi Berjaya Diterima',
                        allowEscapeKey : false,
                        allowOutsideClick: false
                    }).then(function(){

                        $('#denominasiPermohonan').modal('hide');
                        
                        $.ajax({
                        method:"put",
                        url: api_url + '/admin/permohonan/tagterima',
                        data: {
                            "mohonid" : mid,
                            "namapenerima" : teller
                        },
                        success:function(data)
                        {
                            if(data === 1)
                            {
                                location.reload();
                            }
                        }
                        });
                        
                    });

                }else if(data == 'GAGAL'){
                    Swal.fire({
                        icon: 'error',
                        title: 'Transaksi Gagal',
                        allowEscapeKey : false,
                        allowOutsideClick: false
                    }).then(function(){

                        $('#denominasiPermohonan').modal('hide');
                        // $("#terima_transaksi").prop('disabled', false);
                        
                    });
                }
            },error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    }

    function verifyCIT(){
       
        var boolbank = false,boolnorujukan = false,boolresit = false,boolinvoice = false;
        var bank = $('select[name="selectedbank"]').val();
        var norujukan = $('input[name="noresit"]').val();
        var resit = $('input[name="resit"]').val();
        var invoice = $('input[name="invoice"]').val();

        

        if(bank !== '')
        {
            boolbank = true;
        }else{
            boolbank = false;
        }

        if(norujukan !== '')
        {
            boolnorujukan = true;
        }else{
            boolnorujukan = false;
        }

        if(resit)
        {
            boolresit = true;
        }else{
            boolresit = false;
        }

        if(invoice)
        {
            boolinvoice = true;
        }else{
            boolinvoice = false;
        }

        if(boolbank == true && boolnorujukan == true && boolresit == true && boolinvoice == true)
        {
            $("#terimahantar").prop('disabled', true);
            return true;
            
        }else{
            $("#terimahantar").prop('disabled', false);
            event.preventDefault();
            return false;
        }

        event.preventDefault();
        return false;

       
    }

    function janasurat(e){

        let mid = $(e).data("mohonid");
        console.log(mid);
        $.ajax({
            method: 'post',
            url: api_url + '/admin/permohonan/updatejanapc',
            data: {
                "_token": "{{ csrf_token() }}",
                'status' : 'jana',
                'mohonid' : mid,
            },
            success:function(data){
                window.open("{{ route('permohonan.jana')}}" + "/?mohonid=" + mid);
                location.reload();

            }
        })

    }

    function muatnaiksurat(e){
        let mid = $(e).data("mohonid");

        Swal.fire({
        title: 'Muat Naik Fail Permohonan',
        showCancelButton: true,
        confirmButtonText: 'Upload',
        input: 'file',
        allowOutsideClick: false,
        willOpen: () => {
            $(".swal2-file").change(function () {
                var reader = new FileReader();
                reader.readAsDataURL(this.files[0]);
            });
        }
        }).then((file) => {
            if (file.value) {
                var formData = new FormData();
                var file = $('.swal2-file')[0].files[0];
                formData.append("mohonid", mid);
                formData.append("image", file);
                formData.append("status", 'proses');

                $.ajax({
                    method: 'post',
                    url: "{{ route('permohonan.proses') }}",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
                    success:function(response){

                        if(response == 'success')
                        {
                            location.reload();
                        }
                    
                    }
                })

            }
        });
    
    }

</script>
@endsection
