$(document).ready(function()
{
    $("#vc_cheque_date, #vc_entry_date").datepicker({
        format: 'dd-mm-yyyy',
        todayHighlight: true,
    });
    
});
/************************************ Voucher Master Start *********************************/

    var voucher_cnt = 1;

    function get_group_data()
    {
        if($("#vc_cash_acc_id :selected").text() == 'BANK')
        {
            $("#vc_cheque_no").show();      
            $("#vc_cheque_no_label").show();        
            $("#vc_cheque_date").show();        
            $("#vc_cheque_date_label").show();   

            var data = '';

            data += '<option value="0">SELECT</option>';
            // data += '<option value="23">STAFF</option>';
            data += '<option value="5">CLIENT</option>';
            // data += '<option value="6">SUPPLIER</option>';
            // data += '<option value="1">GENERAL</option>';

            $("#vc_grp_id").html(data);
            $("#vc_grp_id").val(0);

            $("#vc_party_id").html("<option value='0'>SELECT GROUP</option>");
            $("#vc_party_id").val(0);
            $("#vc_payment_status").val('');
            $("#vc_amount").val(0);
            $("#vc_round_off").val(0);

        }
        else if($("#vc_cash_acc_id :selected").text() == 'CASH')
        {
            $("#vc_cheque_no").hide();
            $("#vc_cheque_no_label").hide();
            $("#vc_cheque_no").val('');

            $("#vc_cheque_date").hide();
            $("#vc_cheque_date_label").hide();
            $("#vc_cheque_date").val('');

            data += '<option value="0">SELECT</option>';
            // data += '<option value="23">STAFF</option>';
            data += '<option value="5">CLIENT</option>';
            // data += '<option value="6">SUPPLIER</option>';
            // data += '<option value="1">GENERAL</option>';

            $("#vc_grp_id").html(data);
            $("#vc_grp_id").val(0);

            $("#vc_party_id").html("<option value='0'>SELECT GROUP</option>");
            $("#vc_party_id").val(0);
            $("#vc_payment_status").val('');
            $("#vc_amount").val(0);
            $("#vc_round_off").val(0);
        }
        else
        {
            $("#vc_cheque_no").hide();
            $("#vc_cheque_no_label").hide();
            $("#vc_cheque_no").val('');

            $("#vc_cheque_date").hide();
            $("#vc_cheque_date_label").hide();
            $("#vc_cheque_date").val('');

            $("#vc_grp_id").html("<option value='0'>SELECT ACCOUNT</option>");
            $("#vc_grp_id").val(0);

            $("#vc_party_id").html("<option value='0'>SELECT GROUP</option>");
            $("#vc_party_id").val(0);
            $("#vc_payment_status").val('');
            $("#vc_amount").val(0);
            $("#vc_round_off").val(0);

            $("#bal_purchase_details").html('');

        }
    }

    function get_party_list()
    {
        var grp_id = $("#vc_grp_id").val();
        var path = base_url+"voucher/voucherctrl/get_party_list/"+grp_id;   
        if(grp_id > 0)
        {
            $("#loading").show();
            ajaxCall('POST',path,'','JSON',function(resp) 
            {
                console.log(resp);   
                var data = '';
                if(resp.length != 0)
                {   
                    data += '<option value="0">SELECT</option>';

                    $.each(resp, (index, value) =>
                    {
                        if(grp_id == 23) // STAFF
                        {
                            data += '<option value="'+value['km_id']+'">'+value['km_name'].toUpperCase()+'</option>';
                        }
                        else if(grp_id == 5) 
                        {
                            data += '<option value="'+value['client_id']+'">'+value['client_name'].toUpperCase()+'</option>';
                        }
                        
                    });
                }
                else
                {
                    data += '<option value="0">NO DATA</option>';
                }

                $("#vc_party_id").html(data);
                $("#loading").hide();
            },
            function(errmsg) {
                console.log(errmsg);
            });
        }
        else
        {
            $("#vc_party_id").html("<option value='0'>SELECT GROUP</option>");
            $("#vc_party_id").val(0);
            $("#vc_payment_status").val('');
            $("#vc_amount").val(0);
            $("#vc_round_off").val(0);
            $("#bal_purchase_details").html('');
        }
        
    }


    function delete_voucher_item(id, path,type)
    {
        var ans = confirm("Are you sure? You want to delete item.");

        if(ans == true)
        {
            var update_path = base_url+"voucher/voucherctrl/"+path+"/"+id+"/"+type;
             
            ajaxCall('GET',update_path,'','JSON',function(resp)
            {   
                console.log(resp);
                if(resp == 2) { alert("You can not delete this item!"); }
                    else { window.location.reload(); }
                $("#loading").hide();            
            },
            function(errmsg)
            {
                console.log(errmsg);
            });
        }
    } 

    function add_receipt_voucher(id)
    {
        var check = 1;

        var acc_id = $("#vc_cash_acc_id").val();

        if($("#vc_entry_date").val() == "")
        {
            $("#vc_entry_date").css({'background-color':'yellow'});
            check = 0;
        }
        else
        {
            $("#vc_entry_date").css({'background-color':'#fff'});
        }

        if($('#vc_amount').val() < 0 || $('#vc_amount').val() == '' || isNaN(($('#vc_amount')).val()))
        {
            $("#vc_amount").css({'background-color':'yellow'});
            check = 0;
        }
        else
        {
            $("#vc_amount").css({'background-color':'#fff'});
        }

        if($('#vc_party_id').val() == 0 || $('#vc_party_id').val() == '')
        {
            $("#vc_party_id_flexselect").css({'background-color':'yellow'});
            check = 0;
        }
        else
        {
            $("#vc_party_id_flexselect").css({'background-color':'#fff'});
        }

        for (var i = 1; i < voucher_cnt; i++) 
        {
            if(($('#om_adjust_amt_'+i).val() < 0 || $('#om_adjust_amt_'+i).val() == '' || isNaN(($('#om_adjust_amt_'+i)).val())))
            {
                // $('#sm_adjust_amt_'+i).css({'background-color':'yellow'});
                // check = 0;
            }
            else
            {
                var om_adjust_amt = parseFloat($('#om_adjust_amt_'+i).val());
                if(isNaN(om_adjust_amt)) om_adjust_amt = 0;

                var om_adjust_round_off = parseFloat($('#om_adjust_round_off_'+i).val());
                if(isNaN(om_adjust_round_off)) om_adjust_round_off = 0;


                var total_adjust_amt = parseFloat(om_adjust_amt) + parseFloat(om_adjust_round_off);
                if(isNaN(total_adjust_amt)) total_adjust_amt = 0;

                var om_current_bal_amt = parseFloat($('#om_current_bal_amt_'+i).val());
                if(isNaN(om_current_bal_amt)) om_current_bal_amt = 0;

                
                if(total_adjust_amt > om_current_bal_amt)
                {
                    $('#om_adjust_amt_'+i).css({'background-color':'yellow'});
                    $('#om_adjust_round_off_'+i).css({'background-color':'yellow'});
                    check = 2;
                }
                else
                {
                    $('#om_adjust_amt_'+i).css({'background-color':'#fff'});
                    $('#om_adjust_round_off_'+i).css({'background-color':'#fff'});
                }
                
            }
        }

        if(check == 0)
        {
            var msg = 'Oh snap ! You forgot to enter some information';
            display_alert('err',msg);

            $("body, html").animate({'scrollTop':0},1000);
        }
        else if(check == 2)
        {
            var msg = 'Adjust Amt should not be greater than current balance';
            display_alert('err',msg);
            $("body, html").animate({'scrollTop':0},1000);
        }
        else
        {     
            var check_validation           = 1;
            var check_validation_round     = 1;
            var total_adjust_amt           = 0;
            var total_adjust_round_off_amt = 0;

            var vc_amount = parseFloat($('#vc_amount').val());
            if(isNaN(vc_amount)) vc_amount = 0;

            var vc_round_off = parseFloat($('#vc_round_off').val());
            if(isNaN(vc_round_off)) vc_round_off = 0;

            for (var i = 1; i < voucher_cnt; i++) 
            {
                var om_adjust_amt = parseFloat($('#om_adjust_amt_'+i).val());
                if(isNaN(om_adjust_amt)) om_adjust_amt = 0;

                var om_adjust_round_off = parseFloat($('#om_adjust_round_off_'+i).val());
                if(isNaN(om_adjust_round_off)) om_adjust_round_off = 0;

                // console.log(om_adjust_round_off);

                total_adjust_amt = parseFloat(total_adjust_amt) + parseFloat(om_adjust_amt);
                total_adjust_round_off_amt = parseFloat(total_adjust_round_off_amt) + parseFloat(om_adjust_round_off);
            }
            
            // console.log(total_adjust_amt);

            if((total_adjust_amt != 0) || (total_adjust_round_off_amt != 0))
            {
                if((vc_amount != total_adjust_amt))
                {
                    check_validation = 0;
                }
                else
                {
                    check_validation = 1;
                }

                if (vc_round_off > 0) 
                {
                    if((vc_round_off != total_adjust_round_off_amt))
                    {
                        check_validation_round = 0;
                    }
                    else
                    {
                        check_validation_round = 1;
                    }
                }
                else
                {
                    check_validation_round = 1; 
                }
            }
            else
            {
                check_validation = 1;
            }

            if(check_validation == 0)
            {
                var msg = 'Voucher Amt and adjust amt are not matching';
                display_alert('err',msg);

                $("body, html").animate({'scrollTop':0},1000);
            }
            else if(check_validation_round == 0)
            {
                var msg = 'Voucher round off Amt and adjust round off amt are not matching';
                display_alert('err',msg);

                $("body, html").animate({'scrollTop':0},1000);
            }
            else if((check_validation == 1) && (check_validation_round == 1))
            {
                var path = base_url+"voucher/voucherctrl/receipt_voucher_insert/"+id;   
                var form_data = $("#receipt_voucher_form").serialize();

                $("#loading").show();
                $("#sbt_btn").prop('disabled', true);
                $.ajax({
                    type:'POST',
                    url:path,
                    data:form_data,
                    success:function(resp)
                    {
                        console.log(resp);
                        if(resp == 1)
                        {
                            if(id == 0)
                            {
                                var msg = 'Successfully added!';
                                display_alert('succ',msg);
                                $("html, body").animate({'scrollTop':0},1000);
                                setInterval(function(){window.location.reload(); },1000);
                            }
                            else
                            {
                                var msg = 'Successfully updated!';
                                display_alert('succ',msg);  
                                $("html, body").animate({'scrollTop':0},1000);
                                setInterval(function(){window.location.reload(); },1000);
                            }
                        }
                        else if (resp == 2) 
                        {
                            var msg = 'Voucher Entery No Already Exist';
                            display_alert('warn',msg);
                            $("html, body").animate({'scrollTop':0},1000);
                        }
                        else
                        {
                            var msg = 'Unknown Error ! Please try again letter';
                            display_alert('warn',msg);
                            $("html, body").animate({'scrollTop':0},1000);
                            $("#sbt_btn").prop('disabled', false);
                        }
                        $("#loading").hide();
                    },
                    error:function(resp){
                        console.log(resp);
                        $("#sbt_btn").prop('disabled', false);
                    }   
                });
            }
            else
            {
                var msg = 'Unknown Error ! Please try again letter';
                display_alert('warn',msg);
                $("html, body").animate({'scrollTop':0},1000);
                $("#sbt_btn").prop('disabled', false);
            }
        }
    }

    
/************************************ Voucher Master End ***********************************/


    function get_client_payment_status()
    {
        var party_id= $("#vc_party_id").val();
        var grp_id  = $("#vc_grp_id").val();
        if(party_id > 0)
        {
            var path = base_url+"voucher/voucherctrl/get_client_payment_status?acc_id="+party_id+"&grp_id="+grp_id;  

            $("#loading").show();
            ajaxCall('POST',path,'','JSON',function(resp) 
            {
                console.log(resp);
                $("#vc_payment_status").val(resp['status']);

                get_party_bill_details();
                $("#loading").hide();            
            },
            function(errmsg) 
            {
                console.log(errmsg);
            });
            
        }
        else
        {
            $("#vc_payment_status").val('');
            $("#vc_amount").val(0);
            $("#vc_round_off").val(0);
            $("#bal_purchase_details").html('');
        }
    }


    var voucher_cnt = 1;
    function get_party_bill_details()
    {
        var grp_id  = parseFloat($("#vc_grp_id").val());
        var party_id    = parseFloat($("#vc_party_id").val());

        // console.log(grp_id);
        // console.log(party_id);

        var vc_payment_status = $("#vc_payment_status").val();

        if(vc_payment_status != "0 TO RECEIVE")
        {
            vc_payment_bal = "-1";
        }
        else
        {
            vc_payment_bal = vc_payment_status.indexOf("PAY");
        }
    
        if(party_id > 0)
        {
            // console.log("xyz");

            var path = base_url+"voucher/voucherctrl/get_party_order_details/"+party_id+"/"+grp_id;  

            $("#loading").show();
            $.ajax({
                type:'POST',
                url:path,
                dataType:'json',
                success:function(resp)
                {
                    console.log(resp);
                    var data = '';
                    if(resp.length != 0)
                    {   
                        if (grp_id == 5) 
                        {
                            data += '<table class="table">';

                            data += '<tr>';
                            data += '<th>Bill No</th>';
                            data += '<th>Bill Date</th>';
                            data += '<th>Final Total</th>';
                            data += '<th>Advance</th>';
                            data += '<th>Allocated Amt</th>';
                            data += '<th>Allocated Round off Amt</th>';
                            data += '<th>Adjust Amt</th>';
                            data += '<th>Round off Amt</th>';
                            data += '<th>Current Bal Amt</th>';
                            data += '</tr>';

                            
                            $.each(resp, function(index, value)
                            {
                                var current_bal = (parseFloat(value['om_final_amt']) - ( 
                                                    parseFloat(value['om_allocated_amt']) + 
                                                    parseFloat(value['om_voucher_round_off_amt']) + 
                                                    parseFloat(value['om_promo_disc_amt']) +
                                                    parseFloat(value['om_round_off']) +
                                                    parseFloat(value['om_advance_amt'])
                                                    )
                                                );
                                if (isNaN(current_bal)) current_bal = 0;
                                current_bal = current_bal.toFixed(2);

                                data += '<tr>';
                                data += '<td>';
                                data += '<input type="hidden" class="form-control" name="om_id[]" id="om_id_'+voucher_cnt+'" value="'+value['om_id']+'"/>';
                                
                                data += '<input type="hidden" class="form-control" name="vt_id[]" value="0"/>';

                                data += '<input type="text" class="form-control" name="om_entry_no[]" id="om_entry_no_'+voucher_cnt+'" value="'+value['om_entry_no']+'" readonly/></td>';
                                data += '<td><input type="text" class="form-control" name="om_entry_date[]" id="om_entry_date_'+voucher_cnt+'" value="'+value['om_entry_date']+'" readonly/></td>';

                                data += '<td><input type="text" class="form-control" name="om_final_amt[]" id="om_final_amt_'+voucher_cnt+'" value="'+value['om_final_amt']+'" readonly/></td>';
                                
                                data += '<td><input type="text" class="form-control" name="om_advance_amt[]" id="om_advance_amt_'+voucher_cnt+'" value="'+value['om_advance_amt']+'" readonly/></td>';
                                
                                data += '<td><input type="text" class="form-control" name="om_allocated_amt[]" id="om_allocated_amt_'+voucher_cnt+'" value="'+value['om_allocated_amt']+'" readonly/></td>';

                                data += '<td>';
                                data += '<input type="text" class="form-control" name="om_round_off[]" id="om_round_off_'+voucher_cnt+'" value="'+value['om_round_off']+'" readonly/>';

                                data += '<input type="hidden" class="form-control" name="om_voucher_round_off_amt[]" id="om_voucher_round_off_amt_'+voucher_cnt+'" value="'+value['om_voucher_round_off_amt']+'" readonly/>';
                                
                                data += '</td>';

                                data += '<td>';
                                data += '<input type="text" class="form-control" name="om_adjust_amt[]" id="om_adjust_amt_'+voucher_cnt+'" value=""/>';
                                data += '</td>';

                                data += '<td>';
                                data += '<input type="text" class="form-control" name="om_adjust_round_off[]" id="om_adjust_round_off_'+voucher_cnt+'" value=""/>';
                                data += '</td>';

                                data += '<td><input type="text" class="form-control" id="om_current_bal_amt_'+voucher_cnt+'" value="'+current_bal+'" readonly/></td>';
                                data += '</td>';

                                data += '</tr>';

                                voucher_cnt++;
                            });

                            data += '</table>';
                        }
                        else
                        {
                            data += '<table class="table">';

                            data += '<tr>';
                            data += '<th>Hisab Bill No</th>';
                            data += '<th>Hisab Bill Date</th>';
                            data += '<th>Final Total</th>';
                            data += '<th>Allocated Amt</th>';
                            data += '<th>Allocated Round off Amt</th>';
                            data += '<th>Adjust Amt</th>';
                            data += '<th>Round off Amt</th>';
                            data += '<th>Current Bal Amt</th>';
                            data += '</tr>';

                            
                            $.each(resp, function(index, value)
                            {
                                var current_bal = parseFloat(value['hm_amount']) - parseFloat(value['hm_allocated_amt']) - parseFloat(value['hm_round_off']);
                                if (isNaN(current_bal)) current_bal = 0;
                                current_bal = current_bal.toFixed(2);

                                data += '<tr>';
                                data += '<td>';
                                data += '<input type="hidden" class="form-control" name="hm_id[]" id="hm_id_'+voucher_cnt+'" value="'+value['hm_id']+'"/>';
                                data += '<input type="hidden" class="form-control" name="vt_id[]" value="0"/>';
                                
                                data += '<input type="text" class="form-control" name="om_no[]" id="om_no_'+voucher_cnt+'" value="'+value['hm_entry_no']+'" readonly/></td>';
                                data += '<td><input type="text" class="form-control" name="om_date[]" id="om_date_'+voucher_cnt+'" value="'+value['hm_entry_date']+'" readonly/></td>';

                                data += '<td><input type="text" class="form-control" name="om_final_total[]" id="om_final_total_'+voucher_cnt+'" value="'+value['hm_amount']+'" readonly/></td>';
                                
                                data += '<td><input type="text" class="form-control" name="om_allocated_amt[]" id="om_allocated_amt_'+voucher_cnt+'" value="'+value['hm_allocated_amt']+'" readonly/></td>';

                                data += '<td><input type="text" class="form-control" name="om_round_off[]" id="om_round_off_'+voucher_cnt+'" value="'+value['hm_round_off']+'" readonly/></td>';


                                data += '<td>';
                                data += '<input type="text" class="form-control" name="om_adjust_amt[]" id="om_adjust_amt_'+voucher_cnt+'" value=""/>';
                                data += '</td>';

                                data += '<td>';
                                data += '<input type="text" class="form-control" name="om_adjust_round_off[]" id="om_adjust_round_off_'+voucher_cnt+'" value=""/>';
                                data += '</td>';

                                data += '<td><input type="text" class="form-control" id="om_current_bal_amt_'+voucher_cnt+'" value="'+current_bal+'" readonly/></td>';
                                data += '</td>';

                                data += '</tr>';

                                voucher_cnt++;
                            });

                            data += '</table>';
                        }
                    }
                    else
                    {
                        console.log("No Data");
                    }

                    $("#order_details").html(data);
                    $("#loading").hide();
                },
                error:function(resp) {
                    console.log(resp);
                }   
            });
        }
    }