
//Pendahuluan Serah

function totalamount(idwang,bilangan)
{
    var amount = 0;
    switch (idwang) { 
        case 'bundle1': 
            amount += (bilangan * 100);
            break;
        case 'bundle20': 
            amount += (bilangan * 1000);
            break;
        case 'bundle5': 
            amount += (bilangan * 500);
            break;		
        case 'bundle50': 
            amount += (bilangan * 5000);
            break;
        case 'bundle10': 
            amount += (bilangan * 1000);
            break;
        case 'bundle100': 
            amount += (bilangan * 5000);
            break;
        case 'sen1': 
            amount += (bilangan * 0.01);
            break;
        case 'sen5': 
            amount += (bilangan * 0.05);
            break;
        case 'sen10': 
        amount += (bilangan * 0.10);
        break;
        case 'sen20': 
            amount += (bilangan * 0.20);
            break;		
        case 'sen50': 
            amount += (bilangan * 0.50);
            break;
        case 'ringgit1': 
            amount += (bilangan * 1);
            break;
        case 'ringgit5': 
            amount += (bilangan * 5);
            break;      
        case 'ringgit10': 
            amount += (bilangan * 10);
            break;		
        case 'ringgit20': 
            amount += (bilangan * 20);
            break;
        case 'ringgit50': 
            amount += (bilangan * 50);
            break;
        case 'ringgit100': 
            amount += (bilangan * 100);
            break;         
    }

    return amount;
}

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


var arrayambilan = [["bundle1",0],["bundle5",0],["bundle10",0],
                    ["bundle20",0],["bundle50",0],["bundle100",0],
                    ["sen1",0],["sen5",0],["sen10",0],
                    ["sen20",0],["sen50",0],["ringgit1",0],
                    ["ringgit5",0],["ringgit10",0],["ringgit20",0],
                    ["ringgit50",0],["ringgit100",0]
                    ];

function totalkey(datakeyin)
{
    var idkey = $(datakeyin).attr('id');
    var valkey = $(datakeyin).val();
    var deno = $(datakeyin).data('deno');
    var amount = 0;

    if(valkey > deno)
    {
        $('#' + idkey).val(0);
      Swal.fire({
          icon: 'error',
          title: 'Amaun Kiraan lebih banyak daripada Amaun Sebenar!'
        });

        return ;
    }

    var validate = parseFloat($('#amt').data('amaun'));
    
    $.each(arrayambilan, function( index, arr ){
        if(arr[0] == idkey)
        {

            arrayambilan[index][1] = totalamount(idkey,valkey);
        }
            
        amount += arr[1];
      });


      

      if(amount > validate)
      {
          $('#' + idkey).val(0);
        Swal.fire({
            icon: 'error',
            title: 'Amaran',
            text: 'Jumlah Melebihi kadar',
          });
      }
      else
      {
        $('#amaunkiraan').val(formatter.format(amount));
      }
      
}

function totalkeyserahan(datakeyin)
{
    var idkey = $(datakeyin).attr('id');
    var valkey = $(datakeyin).val();
    var amount = 0;


    var validate = parseFloat($('#amt').data('amaun'));
    
    $.each(arrayambilan, function( index, arr ){
        if(arr[0] == idkey)
        {
            arrayambilan[index][1] = totalamount(idkey,valkey);
        }
            
        amount += arr[1];
      });


      if(amount > validate)
      {
        $('#' + idkey).val(0);
        Swal.fire({
            icon: 'error',
            title: 'Amaran',
            text: 'Jumlah Melebihi kadar',
        });
      }
      else
      {
        $('#amt').val(amount);
      }
      
}


function kiraan(datakeyin)
{
    var idkey = $(datakeyin).attr('id');
    var valkey = $(datakeyin).val();
    var amount = 0;
    let amountkiraan = 0;
    var id = $('#jenisjenis').val();

    var validate = parseFloat($('#amaundiminta').val());
    
    $.each(arrayambilan, function( index, arr ){
        if(arr[0] == idkey)
        {

            arrayambilan[index][1] = totalamount(idkey,valkey);
        }
            
        amount += arr[1];
      });

      if(id === 'serahan')
      {
        var deno = $(datakeyin).data('deno');

        if(valkey > deno)
        {
            Swal.fire({
                icon: 'error',
                title: 'Amaran',
                text: 'Peti Besi tidak mencukupi!'
              });

            return false;
        }
          
      }

      if(amount > validate)
      {
        Swal.fire({
            icon: 'error',
            title: 'Amaran',
            text: 'Jumlah denominasi melebihi kadar'
          });
      }
      else
      {
        
        $('#amaunkiraan').val(amount);

      }

      switch(idkey) {
        case 'bundle1': 
            amountkiraan += (valkey * 100);
            $('#totalb1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle20': 
            amountkiraan += (valkey * 1000);
            $('#totalb20').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle5': 
            amountkiraan += (valkey * 500);
            $('#totalb5').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'bundle50': 
            amountkiraan += (valkey * 5000);
            $('#totalb50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle10': 
            amountkiraan += (valkey * 1000);
            $('#totalb10').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle100': 
            amountkiraan += (valkey * 5000);
            $('#totalb100').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen1': 
            amountkiraan += (valkey * 0.01);
            $('#totalsen1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen5': 
            amountkiraan += (valkey * 0.05);
            $('#totalsen5').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen10': 
            amountkiraan += (valkey * 0.10);
            $('#totalsen10').val(formatter.format(amountkiraan.toFixed(2)));
        break;
        case 'sen20': 
            amountkiraan += (valkey * 0.20);
            $('#totalsen20').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'sen50': 
            amountkiraan += (valkey * 0.50);
            $('#totalsen50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit1': 
            amountkiraan += (valkey * 1);
            $('#totalring1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit5': 
            amountkiraan += (valkey * 5);
            $('#totalring5').val(formatter.format(amountkiraan.toFixed(2)));
            break;      
        case 'ringgit10': 
            amountkiraan += (valkey * 10);
            $('#totalring10').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'ringgit20': 
            amountkiraan += (valkey * 20);
            $('#totalring20').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit50': 
            amountkiraan += (valkey * 50);
            $('#totalring50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit100': 
            amountkiraan += (valkey * 100);
            $('#totalring100').val(formatter.format(amountkiraan.toFixed(2)));
            break;         
      }
      
}

function kiraanpanjar(datakeyin)
{
    var idkey = $(datakeyin).attr('id');
    var valkey = $(datakeyin).val();
    var amount = 0;
    let amountkiraan = 0;

    var validate = parseFloat($(datakeyin).data('amaun'));
    
    $.each(arrayambilan, function( index, arr ){
        if(arr[0] == idkey)
        {

            arrayambilan[index][1] = totalamount(idkey,valkey);
        }
            
        amount += arr[1];
      });

      if(Number(valkey) > Number(validate))
      {
        Swal.fire({
            icon: 'error',
            title: 'Amaran',
            text: 'Jumlah denominasi melebihi kadar'
          });
          $(datakeyin).val('');
      }
      else
      {
        
        $('#amaunkiraan').val(amount);

      }

      switch(idkey) {
        case 'bundle1': 
            amountkiraan += (valkey * 100);
            $('#totalb1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle20': 
            amountkiraan += (valkey * 1000);
            $('#totalb20').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle5': 
            amountkiraan += (valkey * 500);
            $('#totalb5').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'bundle50': 
            amountkiraan += (valkey * 5000);
            $('#totalb50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle10': 
            amountkiraan += (valkey * 1000);
            $('#totalb10').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'bundle100': 
            amountkiraan += (valkey * 5000);
            $('#totalb100').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen1': 
            amountkiraan += (valkey * 0.01);
            $('#totalsen1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen5': 
            amountkiraan += (valkey * 0.05);
            $('#totalsen5').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'sen10': 
            amountkiraan += (valkey * 0.10);
            $('#totalsen10').val(formatter.format(amountkiraan.toFixed(2)));
        break;
        case 'sen20': 
            amountkiraan += (valkey * 0.20);
            $('#totalsen20').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'sen50': 
            amountkiraan += (valkey * 0.50);
            $('#totalsen50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit1': 
            amountkiraan += (valkey * 1);
            $('#totalring1').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit5': 
            amountkiraan += (valkey * 5);
            $('#totalring5').val(formatter.format(amountkiraan.toFixed(2)));
            break;      
        case 'ringgit10': 
            amountkiraan += (valkey * 10);
            $('#totalring10').val(formatter.format(amountkiraan.toFixed(2)));
            break;		
        case 'ringgit20': 
            amountkiraan += (valkey * 20);
            $('#totalring20').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit50': 
            amountkiraan += (valkey * 50);
            $('#totalring50').val(formatter.format(amountkiraan.toFixed(2)));
            break;
        case 'ringgit100': 
            amountkiraan += (valkey * 100);
            $('#totalring100').val(formatter.format(amountkiraan.toFixed(2)));
            break;         
      }
      
}

async function openuptambahdanserah(e)
{
    var id = $(e).attr('id');
    var kodcaw = $(e).data('kodcaw');
    var teller = $(e).data('teller');
    var api_url = $('#api').val();

    if(id == 'tambahmodal')
    {
        const { value: amaun } =  await Swal.fire({
            title: 'Masukkan Amaun Pendahuluan',
            input: 'text',
            inputPlaceholder: 'Amaun',
            confirmButtonText: 'Terima',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true,
            inputValidator: (value) => {
                if (!value) {
                  return 'Isikan tempat kosong diatas!'
                }

                if(value <= 0){
                    return 'Masukkan jumlah yang munasabah sahaja!';
                }

                if(isNaN(value))
                {
                    return 'Amaun hendaklah dalam nombor!'
                }
              }
        });
        
        if (amaun) {
            // Swal.fire(`Entered email: ${amaun}`)
                if (isNaN(amaun)) 
                {
                    Swal.fire('error','Amaun hendaklah dalam nombor!','error');
                    return false;
                }
                else
                {
                    $.ajax({
                        method: "GET",
                        url: event_tellercash,
                        success:function(data){
                            console.log('successfull trigger');
                        },
                        error: function(xhRequest, ajaxOptions, thrownError){
                            console.log(xhRequest,thrownError);
                        }
                    })

                    $.ajax({
                        method:"POST",
                        url: api_url + '/api/requestTeller/' + kodcaw,
                        data: {
                            "kodlaluan" : teller,
                            "modal" : amaun,
                            "serahan" : 0
                        },
                        success:function(data)
                        {

                            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
                            })

                                var pusher = new Pusher(pusherenv, {
                                    cluster: 'ap1',
                                    encrypted: true
                                });
                            
                                var channel = pusher.subscribe('pendahuluanserahan-notice');
                                channel.bind('penserahan-event', function(data) {
                                    console.log(data);
                                    if(data.pengesahan === 'Lulus' && data.jenis == 'pendahuluan' && data.cawangan == kodcaw && data.kodlaluan == teller)
                                    {
                                        Swal.fire({
                                            icon: 'success',
                                            title: 'Tambah Pendahuluan',
                                            text: 'Tambah Pendahuluan berjaya dipohon!'
                                        }).then(function(){
                                            location.reload(); 
                                        });
                                    }else if(data.pengesahan == 'Batal' && data.jenis == 'all' && data.cawangan == kodcaw && data.kodlaluan == teller){
                                        Swal.fire({
                                            icon: 'error',
                                            title: 'Tambah Pendahuluan',
                                            text: 'Tambah Pendahuluan tidak diluluskan!'
                                        }).then(function(){
                                            location.reload(); 
                                        });
                                    }else{
                                        Swal.fire({
                                            icon: 'error',
                                            title: 'Tambah Pendahuluan',
                                            text: 'Tambah Pendahuluan tidak berjaya!'
                                        }).then(function(){
                                            location.reload(); 
                                        });
                                    }
                                   

                                });

                        },
                        error: function(xhRequest, ajaxOptions, thrownError){
                            console.log(xhRequest);
                        }
                    });
                }
                    
        }
        
    }else if(id == 'serahanmodal') 
    {
        let bakiakhir = parseFloat($('#bakiakhir').text().substring(2).replace(/[^0-9.-]+/g,""));

        const { value: amaun } = await Swal.fire({
            title: 'Masukkan Amaun Serahan',
            input: 'text',
            inputPlaceholder: 'Amaun',
            confirmButtonText: 'Terima',
            showCancelButton:true,
            cancelButtonText:'Batal',
            allowOutsideClick: true,
            inputValidator: (value) => {
                if (!value) {
                  return 'Isikan tempat kosong diatas!';
                }
                
                if(value <= 0){
                    return 'Masukkan jumlah yang munasabah sahaja!';
                }

                if(value > bakiakhir)
                {
                    return 'Amaun serahan hendaklah tidak lebih daripada baki akhir tunai!';
                }

                if(isNaN(value))
                {
                    return 'Amaun hendaklah dalam nombor!';
                }
              }
        });
        if (amaun) {
            if (isNaN(amaun)) 
            {
                Swal.fire('error','Amaun hendaklah dalam nombor!','error');
                return false;
            }
            else
            {
                $('#denominasiModal').modal();
                $('#amaundiminta').val(amaun);
                $('#jenisjenis').val(id);
                $('#kodcawangan').val(kodcaw);
                $('#tellerla').val(teller);
            } 
        }
    }   

}


//Pendahuluan
function tambahdanserahanfunc(e)
{

    var id = $('#jenisjenis').val();
    var kodcaw = $('#kodcawangan').val();
    var teller = $('#tellerla').val();
    var api_url = $('#api').val();

    let bd1 = Number($('#bundle1').val());let bd5 = Number($('#bundle5').val()); let bd10 = Number($('#bundle10').val());let bd20 = Number($('#bundle20').val());let bd50 = Number($('#bundle50').val());let bd100 = Number($('#bundle100').val());let txtring1 = Number($('#ringgit1').val());let txtring5 = Number($('#ringgit5').val());let txtring10 = Number($('#ringgit10').val());let txtring20 = Number($('#ringgit20').val());let txtring50 = Number($('#ringgit50').val()); 
	let txtring100 = Number($('#ringgit100').val());let txtsen1 = Number($('#sen1').val());let txtsen5 = Number($('#sen5').val());let txtsen10 = Number($('#sen10').val());let txtsen20 = Number($('#sen20').val());let txtsen50 = Number($('#sen50').val()); 

    var txt = $('#amaunkiraan').val();
    var txt2 = $('#amaundiminta').val();

    if(Number(txt) != Number(txt2))
    {
        Swal.fire({
            icon: 'error',
            title: 'Amaran',
            text: 'Amaun yang diminta tidak sama dengan amaun yang dikira!'
        });

        $('#denominasiModal').modal('hide');

        return false;
    }


    if(id == "serahanmodal")
    {

        $.ajax({
            method: "GET",
            url: event_tellercash,
            success:function(data){
                console.log('successfull trigger');
            }
        })

        $.ajax({
            method:"POST",
            url: api_url + '/api/requestTeller/' + kodcaw,
            data: {
                'kodlaluan' : teller,
                'modal' : 0,
                'serahan' : txt,
                'bd1' : bd1,
                'bd5' : bd5,
                'bd10' : bd10,
                'bd20' : bd20,
                'bd50' : bd50,
                'bd100' : bd100,
                'txtring1' : txtring1,
                'txtring5' : txtring5,
                'txtring10' : txtring10,
                'txtring20' : txtring20,
                'txtring50' : txtring50,
                'txtring100' : txtring100,
                'txtring1000' : 0,
                'txtsen1' : txtsen1,
                'txtsen5' : txtsen5,
                'txtsen10' : txtsen10,
                'txtsen20' : txtsen20,
                'txtsen50' : txtsen50 
            },
            success:function(data)
            {
                  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
                })

                    var pusher = new Pusher(pusherenv, {
                        cluster: 'ap1',
                        encrypted: true
                    });
                
                    var channel = pusher.subscribe('pendahuluanserahan-notice');
                    channel.bind('penserahan-event', function(data) {
                        // let message = JSON.stringify(data);

                        if(data.pengesahan === 'Lulus' && data.jenis == 'serahan' && data.cawangan == kodcaw && data.kodlaluan == teller)
                        {
                            Swal.fire({
                                icon: 'success',
                                title: 'Serahan Modal',
                                text: 'Serahan modal berjaya dipohon!'
                            }).then(function(){
                                window.open(laporanroute, '_blank'); 
                                location.reload();
                            });
                        }else if(data.pengesahan == 'Batal' && data.jenis == 'all' && data.cawangan == kodcaw && data.kodlaluan == teller){
                            Swal.fire({
                                icon: 'error',
                                title: 'Serahan Modal',
                                text: 'Serahan modal tidak diluluskan!'
                            }).then(function(){
                                location.reload(); 
                            });
                        }else{
                            Swal.fire({
                                icon: 'error',
                                title: 'Serahan Modal',
                                text: 'Serahan modal tidak diluluskan!'
                            }).then(function(){
                                location.reload(); 
                            });
                        }
                       

                    });

                  $('#denominasiModal').modal('hide');
            },
            error: function(xhRequest, ajaxOptions, thrownError){
                console.log(xhRequest);
            }
        });
    }
}
