@extends('layouts.app')

@section('content')

@include('modal.pendahuluanserahan')
@include('modal.autoserahan')
@include('modal.denominasimodalpendahuluanserahan')

@if(count($proses) > 0)
<script>
    Swal.fire({
        title: 'Tunggu Pengesahan Daripada Operasi.',
        text: 'Menunggu Pengesahan Daripada Operasi!',
        icon: 'info',
        width: 600,
        padding: '3em',
        background: '#fffff',
        showCancelButton: false,
        showConfirmButton: false,
        allowOutsideClick: false,
        allowEscapeKey: false,
        allowEnterKey: false
    })
</script>
@endif

<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">Pendahuluan Serahan</li>
                        </ol>
                      </nav>

                <div class="card-body">

                    @php 
                        $dt = \Carbon\Carbon::now();

                        $date = $dt->format('Y-m-d');

                    @endphp

                    <div class="col-12 d-flex justify-content-end">
                        <button class="btn btn-danger fas fa-trash-alt" onclick="togglepadam();"></button>
                    </div>

                    <div class="mt-3 mx-auto">
                     {{-- @php $date = date('yy-m-d'); @endphp --}}
                        <table class='table table-hover table-striped table-bordered' id='table-pendahuluanserahan' style="width: 100%;">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Tarikh</th>
                                    <th>Description</th>
                                    <th>Pendahuluan (RM)</th>
                                    <th>Serahan (RM)</th>
                                    <th>Tindakan</th>
                                </tr>
                            </thead>
                            
                            <tbody>
                                @foreach ($listgldetail as $gldetail)
                                    <tr>
                                        <td>{{ $gldetail['tarikh'] }}</td>
                                        <td>{{ $gldetail['descpt'] }}</td>
                                        <td>{{ ($gldetail['pendahuluan'] == 0 && ($gldetail['ktacct'] == '7000/102' || $gldetail['ktacct'] == '7000/106')) ? number_format($gldetail['amaun'],2) : number_format($gldetail['pendahuluan'],2) }}</td>
                                        <td>{{ ($gldetail['serahan'] == 0 && ($gldetail['dtacct'] == '1000/026' || $gldetail['dtacct'] == '1000/020' || $gldetail['dtacct'] == '1000/090')) ? number_format($gldetail['amaun'],2) : number_format($gldetail['serahan'],2) }}</td>
                                       @if($date === $gldetail['tarikh'] && !fnmatch('SERAHAN BAYAR ONLINE*',$gldetail['descpt'])) <td class="text-center"><button onclick="{{ strpos($gldetail['teller'], 'AUTO') !== false ? 'deleteautoserahan(this);' : 'deletependser(this);' }}" data-pend="{{ $gldetail['pendahuluan'] }}" data-ser="{{ $gldetail['serahan'] }}" data-recno="{{ $gldetail['recno'] }}" class="btn btn-danger fas fa-minus-square"></button></td>@else<td></td> @endif
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>

                    </div>


                    <button class="btn btn-primary mt-4" data-toggle="modal" data-target="#pendahuluanserahanModal">Daftar</button>
                    <x-auto-serah />

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

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

    <script>

        var tablependahuluanserahan = $('#table-pendahuluanserahan').DataTable({
            "scrollX": true,
            "order": [[ 0, "desc" ]],
            "columnDefs": [
            {
                "targets": [ 4 ],
                "visible": false,
                "searchable": false
            }
            ]
        });

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


        $(document).ready(function(){
        
            let date = new Date();
            let year = date.getFullYear();
            let month = 1 + date.getMonth();
            let day = date.getDate();

            let tarikh = day + '/' + month + '/' + year;
            $('#tarikh').val(tarikh);

        });

        $("input[name='radwang']").click(function() {
            let jenis = $('#radiopendahuluanserahan:checked').val();

            if(jenis == 'pendahuluan')
            {
                $('#keterangan').val('Pendahuluan Daripada HQ');
                $('#dtacct').val('1000/010');
                $('#ktacct').val('7000/102');
                $('input[name="denominasi"]').attr('style','display: none');
                $('.denominasi').attr('style','display: none');
                

            }else if(jenis == 'serahan')
            {
                $('#keterangan').val('Serahan Kepada HQ');
                $('#dtacct').val('1000/010');
                $('#ktacct').val('1000/020');
                $('input[name="denominasi"]').attr('style','display: block');
                $('.denominasi').attr('style','display: block');

            }
            else
            {
                $('#keterangan').val('Tiada Maklumat');
                $('#dtacct').val(0);
                $('#ktacct').val(0);
            }

        });

        function togglepadam()
        {
            event.preventDefault();
 
            var column = tablependahuluanserahan.column(4);

            column.visible(!column.visible());
        }

        function deletependser(e)
        {
            let rec_no = $(e).data('recno');
            let pend = $(e).data('pend');
            let ser = $(e).data('ser');
            let jenisserahan = '';

            if(pend > 0)
            {
                jenisserahan = 'pendahuluan';
            }else{
                jenisserahan = 'serahan';
            }
            
            Swal.fire({
            title: 'Adakah anda pasti?',
            text: "Anda tidak dapat untuk mengembalinya kembali!",
            icon: 'warning',
            showCancelButton: true,
            cancelButtonText: "Batal",   
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Teruskan!'
            }).then((result) => {
                if (result.isConfirmed) {

                $.ajax({
                method: 'post',
                url: '{{ route("khazanah.deletependser") }}',
                data: {
                    "_token": "{{ csrf_token() }}",
                    'recno' : rec_no,
                    'jenisserahan' : jenisserahan
                },
                success:function(data){

                    if(data === 'berjaya')
                    {
                        location.reload();

                    }else{
                        Swal.fire(
                            'Tidak Berjaya!',
                            'Data tidak berjaya dihapuskan.',
                            'error'
                        )
                    }

                }
                });

                }
            });
        }

        function validateformat(evt)
        {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        }

        $('#pendahuluanserahanModal').on('shown.bs.modal', function (e) {
            let input = $(e.relatedTarget);
            let inputselected = input.data('input');


            if(inputselected == 'AutoSerahan')
            {
                $('#jenisserahan').val('auto');
                $('input[name="radwang"][value="pendahuluan"]').prop('disabled', true);
                $('input[name="radwang"][value="serahan"]').prop('checked', true);
                $('input[name="radwang"][value="serahan"]').prop('disabled', true);
                $('#keterangan').val('Serahan Kepada V3');
                $('#keterangan').attr('readonly', true);
                $('#dtacct').val('1000/010');
                $('#ktacct').val('1000/020');
                $('input[name="denominasi"]').attr('style','display: block');
                $('.denominasi').attr('style','display: block');
            }else{
                $('#jenisserahan').val('biasa');
                $('input[name="radwang"][value="pendahuluan"]').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('');
                $('#dtacct').val('');
                $('#ktacct').val('');
                $('#keterangan').val('');
                $('#amaun').val('');
                $('#keterangan').attr('readonly', false);
                $('input[name="radwang"]').prop('checked', false);
            }


        
        });

        function functerima()
        {

            let amaun = $('#amaun').val();
            let keterangan = $('#keterangan').val();
            let jenis = $('#radiopendahuluanserahan:checked').val();
            let dtacct = $('#dtacct').val();
            let ktacct = $('#ktacct').val();

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

        // Validation for keterangan
        if (!keterangan) {
            $("[name='errorketerangan']").show();
            $("[name='errorketerangan']").text("*Isikan keterangan dalam input!");
            $("[name='keterangan']").addClass('is-invalid');
            boolketerangan = true;
        } else {
            $("[name='errorketerangan']").hide();
            $("[name='keterangan']").removeClass('is-invalid');
            boolketerangan = false;
        }

        // Validation for jenis
        if (!jenis) {
            $(".invalid-feedback").show();
            booljenis = true;
        } else {
            $(".invalid-feedback").hide();
            booljenis = false;
        }

        // If all validations pass
        if (boolamaun === false && boolketerangan === false && booljenis === false) {
            // Carry all validated values, including auth_user
            console.log({
                amaun,
                keterangan,
                jenis,
                dtacct,
                ktacct,
                auth_user
            });

            $('#amaundiminta').val(amaun);
            $('#denominasiHQModal').modal('show');
            $('#pendahuluanserahanModal').modal('hide');
            $('#jenisjenis').val(jenis);

            return true;
        } else {
            $("#terima_transaksi").prop('disabled', false);
            event.preventDefault();
            return false;
        }
    }


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

            $(this).find("[name='erroramaun']").hide();
            $(this).find("[name='amaun']").removeClass('is-invalid');
            // $(this).find("[name='tarikh']").parent().addClass("mb-4");

            $(this).find("[name='errorketerangan']").hide();
            $(this).find("[name='keterangan']").removeClass('is-invalid');
            // $(this).find("[name='tuntutan']").parent().addClass("mb-4");

            $(this).find(".invalid-feedback").hide();
            // $(this).find("[name='errorradio']").removeClass('is-invalid');
            // $(this).find("[name='tarikhbil']").parent().addClass("mb-4");
        
        });

        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 terimapost() {
        $("#terima_transaksi").prop('disabled', true);

        let amaun = $('#amaundiminta').val();
        let kiraan = $('#amaunkiraan').val();
        let keterangan = $('#keterangan').val();
        let jenis = $('#radiopendahuluanserahan:checked').val();
        let dtacct = $('#dtacct').val();
        let ktacct = $('#ktacct').val();
        let auth_user = $('#auth_user').val(); //letak user
        let jenisserahan = $('#jenisserahan').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;
        }
        let SwalPengesahan = '';

        if(jenisserahan == 'biasa')
        {
            Swal.fire({
                title: 'Memuatkan...',
                allowEscapeKey: false,
                allowOutsideClick: false,
                didOpen: function () {
                    Swal.showLoading();
                    $('#denominasiHQModal').modal('hide');
                }
            });
        }else{
            let SwalPengesahan = Swal.fire({
                title: 'Tunggu Pengesahan Daripada Operasi.',
                icon: 'info',
                width: 600,
                padding: '3em',
                background: '#fffff',
                showCancelButton: false,
                showConfirmButton: false,
                allowOutsideClick: false,
                allowEscapeKey: false,
                allowEnterKey: false,
                didOpen: function () {
                    $('#denominasiHQModal').modal('hide');
                }
            });
        }

        let array_send = {
            amaun: amaun,
            jenisgldetail: jenis,
            keterangan: keterangan,
            kodcaw: kodcaw,
            teller: teller,
            dtacct: dtacct,
            ktacct: ktacct,
            auth_user: auth_user,
            ambilansen1: sen1,
            ambilansen5: sen5,
            ambilansen10: sen10,
            ambilansen20: sen20,
            ambilansen50: sen50,
            ambilanring1: ringgit1,
            ambilanring5: ringgit5,
            ambilanring10: ringgit10,
            ambilanring20: ringgit20,
            ambilanring50: ringgit50,
            ambilanring100: ringgit100
        };
        this.sendRequest(array_send,jenisserahan);
    }

    function sendRequest(arraysend,jenisserahan){
        if(jenisserahan == 'biasa'){
            console.log(arraysend);
            $.ajax({
                method: 'post',
                url: '{{ route("khazanah.pendahuluanserahanHQ") }}',
                data: {
                    "_token": "{{ csrf_token() }}",
                    'amaun': arraysend['amaun'],
                    'jenisgldetail': arraysend['jenisgldetail'],
                    'keterangan': arraysend['keterangan'],
                    'kodcaw': arraysend['kodcaw'],
                    'teller': arraysend['teller'],
                    'dtacct': arraysend['dtacct'],
                    'ktacct': arraysend['ktacct'],
                    'auth_user': arraysend['auth_user'], 
                    'ambilansen1': arraysend['ambilansen1'],
                    'ambilansen5': arraysend['ambilansen5'],
                    'ambilansen10': arraysend['ambilansen10'],
                    'ambilansen20': arraysend['ambilansen20'],
                    'ambilansen50': arraysend['ambilansen50'],
                    'ambilanring1': arraysend['ambilanring1'],
                    'ambilanring5': arraysend['ambilanring5'],
                    'ambilanring10': arraysend['ambilanring10'],
                    'ambilanring20': arraysend['ambilanring20'],
                    'ambilanring50': arraysend['ambilanring50'],
                    'ambilanring100': arraysend['ambilanring100']
                },
                success: function (data) {
                    if (data == 'LULUS') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Transaksi Berjaya',
                            allowEscapeKey: false,
                            allowOutsideClick: false
                        }).then(function () {
                            $('#denominasiHQModal').modal('hide');
                            $('#pendahuluanserahanModal').modal('hide');
                            location.reload();
                        });
                    } else if (data == 'GAGAL') {
                        Swal.fire({
                            icon: 'error',
                            title: 'Transaksi Gagal',
                            allowEscapeKey: false,
                            allowOutsideClick: false
                        }).then(function () {
                            $('#denominasiHQModal').modal('hide');
                            $('#pendahuluanserahanModal').modal('hide');
                            $("#terima_transaksi").prop('disabled', false);
                        });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                }
            });
        }else{
            let approvalid = '';
            $.ajax({
                method: 'post',
                url: '{{ route("khazanah.autoserahan") }}',
                data: {
                    "_token": "{{ csrf_token() }}",
                    'arraysend': arraysend
                },
                success:function(e){
                    approvalid = e.id;
                    if(e.status == 'success'){
                        Swal.update({
                            text: 'Menunggu Pengesahan Daripada Operasi!',
                        });
                    }
                }
            });

            var pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
                cluster: 'ap1',
                encrypted: true
            });
        
            var channel = pusher.subscribe('autoserahan-notice');
            channel.bind('autoserahan-event', function(data) {
                console.log(data,approvalid,kodcaw,teller);
                if(data.pengesahan === 'Lulus' && data.id == approvalid && data.kodlaluan == teller)
                {
                    Swal.fire({
                        icon: 'success',
                        title: 'Serahan V3/Auto Pendahuluan V2 Berjaya',
                        text: 'Operasi berjaya meluluskan Serahan ke V3 dan Auto Pendahuluan dari V2!'
                    }).then(function(){
                        location.reload(); 
                    });
                }else if(data.pengesahan == 'Batal' && data.id == approvalid && data.kodlaluan == teller){
                    Swal.fire({
                        icon: 'error',
                        title: 'Serahan V3/Auto Pendahuluan V2 Dibatalkan',
                        text: 'Operasi membatalkan Serahan ke V3 dan Auto Pendahuluan dari V2!'
                    }).then(function(){
                        location.reload(); 
                    });
                }

            });
        }

    }

    function deleteautoserahan(e){
        let recno = $(e).data('recno');
        let pend = $(e).data('pend');
        let ser = $(e).data('ser');

        let SwalPengesahan = Swal.fire({
            title: 'Tunggu Pengesahan Daripada Operasi.',
            icon: 'info',
            width: 600,
            padding: '3em',
            background: '#fffff',
            showCancelButton: false,
            showConfirmButton: false,
            allowOutsideClick: false,
            allowEscapeKey: false,
            allowEnterKey: false,
        });

        let approvalid = '';
            $.ajax({
                method: 'post',
                url: '{{ route("khazanah.autoserahan") }}',
                data: {
                    "_token": "{{ csrf_token() }}",
                    'do_delete': true,
                    'recno' : recno,
                    'kodcaw' : kodcaw,
                    'teller' : teller,
                    'amaun' : (pend > 0 ) ? pend : ser
                },
                success:function(e){
                    approvalid = e.id;
                    if(e.status == 'success'){
                        Swal.update({
                            text: 'Menunggu Pengesahan Daripada Operasi!',
                        });
                    }
                }
            });

            var pusher = new Pusher("{{ env('PUSHER_APP_KEY') }}", {
                cluster: 'ap1',
                encrypted: true
            });
        
            var channel = pusher.subscribe('autoserahan-notice');
            channel.bind('autoserahan-event', function(data) {
                console.log(data,approvalid,teller,kodcaw);
                if(data.pengesahan === 'Lulus' && data.id == approvalid && data.kodlaluan == teller)
                {
                    Swal.fire({
                        icon: 'success',
                        title: 'Serahan V3/Auto Pendahuluan V2 Berjaya',
                        text: 'Operasi berjaya meluluskan Serahan ke V3 dan Auto Pendahuluan dari V2!'
                    }).then(function(){
                        location.reload(); 
                    });
                }else if(data.pengesahan == 'Batal' && data.id == approvalid && data.kodlaluan == teller){
                    Swal.fire({
                        icon: 'error',
                        title: 'Serahan V3/Auto Pendahuluan V2 Dibatalkan',
                        text: 'Operasi membatalkan Serahan ke V3 dan Auto Pendahuluan dari V2!'
                    }).then(function(){
                        location.reload(); 
                    });
                }else{
                    Swal.fire({
                        icon: 'error',
                        title: 'Auto Serahan Mengalami Ralat',
                        text: 'Auto Serahan tidak berjaya!'
                    }).then(function(){
                        location.reload(); 
                    });
                }
                

            });
    }

    const getCurrentDate = () => {
        const today = new Date();
        const day = String(today.getDate()).padStart(2, '0');
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const year = today.getFullYear();

        return `${day}/${month}/${year}`;
    };

    function triggerValue(){
        let form = $('form[name="autoserah"]');
        form.find('[name="tarikh"]').val(getCurrentDate());
    }

    $('#autoSerahanModal').on('shown.bs.modal', function () {
        $('input[name="denominasi"]').attr('style','display: block');
        $('.denominasi').attr('style','display: block');
        triggerValue();
    });

    function terima_autoserah(){
        let form = $('form[name="autoserah"]');

        let amaun = form.find('[name="amaun"]').val();
        let keterangan = form.find('[name="keterangan"]').val();
        let dtacct = form.find('[name="dtacct"]').val();
        let ktacct = form.find('[name="ktacct"]').val();

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

        if(!keterangan){
            $("[name='errorketerangan']").show();
            $("[name='errorketerangan']").text("*Isikan keterangan dalam input!");
            $("[name='keterangan']").addClass('is-invalid');
            boolketerangan = true;
        }else{
            $("[name='errorketerangan']").hide();
            $("[name='keterangan']").removeClass('is-invalid');
            boolketerangan = false;
        }

        // If all validations pass
        if(boolamaun === false && boolketerangan === false) {
            // Carry all validated values, including auth_user

            $('#amaundiminta').val(amaun);
            $('#denominasiHQModal').modal('show');
            $('#autoSerahanModal').modal('hide');
            $('#jenisjenis').val('serahan');
            $('#jenisserahan').val('auto');

            return true;
        }else{
            $("#terima_transaksi_autoserah").prop('disabled', false);
            event.preventDefault();
            return false;
        }
    }


    </script>
@endsection
