(function () {
    $("#inv_invoice_date, #inv_entry_date").datepicker({
        format: 'dd-mm-yyyy',
        todayHighlight: true,
    });
    disable_enable_background(false)
}()); 

var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
base_url += '/';

var duplicate    = [];
var inv_cnt      = 1;


function get_product_data()
{
    check = 1;

    if(parseInt($("#cust_id").val()) == 0 || $("#cust_id").val() == "")
    {
        $("#cust_id").css({'border-color':'red'});
        $("#acc_type_name").html("");
        $("#acc_type").val('');

        $("#pro_id").val(0);
        $("#pro_igst").val('');
        $("#pro_cgst").val('');
        $("#pro_sgst").val('');
        $("#pro_igst_total").val('');
        $("#pro_cgst_total").val('');
        $("#pro_sgst_total").val('');
        
        $("#pro_hsn_code").val('');
        $("#pro_rate").val('');
        $("#pro_qty").val('');
        $("#pro_final_total").val('');
        check = 0;
    }
    else
    {
        $("#cust_id").css({'border-color':'#CCC'});
    }

    if(check == 0)
    {
        var msg = 'Please Select Customer';
        display_alert('err',msg);
        $("body, html").animate({'scrollTop':0 },1000); 
    }
    else
    {
        var cust_id = $("#cust_id").val();
        var id = $("#pro_id").val();
        var path = base_url+"invoice/invoicectrl/get_product_data/"+id+"/"+cust_id;

        $.ajax({
            type:"post", 
            url:path,  
            dataType:'json',
            success:function(resp) 
            {
                var inv_date = $("#inv_invoice_date").val();
                var fdate = inv_date.split("-");
                var date1 = [fdate[2], fdate[1], fdate[0]].join('-');
                
                var date2 = '2022-07-18';
                
                var date11 = new Date(date1);
                var date21 = new Date(date2);

                var result1 = date11.getTime(); // 1546300800000
                var result2 = date21.getTime(); // 1895097600000

                if (result1 > result2) 
                {
                    if(resp['user'][0]['acc_type'] == 1)
                    {
                        
                        $("#acc_type_name").html("Within Maharashtra");
                        $("#acc_type").val(resp['user'][0]['acc_type']);

                        $("#pro_igst").val(0);
                        $("#pro_cgst").val(0.75);
                        $("#pro_sgst").val(0.75);

                    }
                    else
                    {
                        $("#acc_type_name").html("Outside Maharashtra");
                        $("#acc_type").val(resp['user'][0]['acc_type']);

                        $("#pro_cgst").val(0);
                        $("#pro_sgst").val(0);
                        $("#pro_igst").val(1.5);
                    }
                }
                else
                {
                   if(resp['user'][0]['acc_type'] == 1)
                    {
                        
                        $("#acc_type_name").html("Within Maharashtra");
                        $("#acc_type").val(resp['user'][0]['acc_type']);

                        $("#pro_igst").val(0);
                        $("#pro_cgst").val(resp['products'][0]['pro_cgst']);
                        $("#pro_sgst").val(resp['products'][0]['pro_sgst']);

                    }
                    else
                    {
                        $("#acc_type_name").html("Outside Maharashtra");
                        $("#acc_type").val(resp['user'][0]['acc_type']);

                        $("#pro_cgst").val(0);
                        $("#pro_sgst").val(0);
                        $("#pro_igst").val(resp['products'][0]['pro_igst']);
                    }
                }
                
                //   if(resp['user'][0]['acc_type'] == 1)
                //     {
                       
                //         $("#acc_type_name").html("Within Maharashtra");
                //         $("#acc_type").val(resp['user'][0]['acc_type']);

                //         $("#pro_igst").val(0);
                //         $("#pro_cgst").val(resp['products'][0]['pro_cgst']);
                //         $("#pro_sgst").val(resp['products'][0]['pro_sgst']);

                //     }
                //     else
                //     {
                //         $("#acc_type_name").html("Outside Maharashtra");
                //         $("#acc_type").val(resp['user'][0]['acc_type']);

                //         $("#pro_cgst").val(0);
                //         $("#pro_sgst").val(0);
                //         $("#pro_igst").val(resp['products'][0]['pro_igst']);
                //     }

                    $("#pro_hsn_code").val(resp['products'][0]['pro_hsn_code']);
                    $("#pro_rate").val(resp['products'][0]['pro_rate']);
              
                //get_amount_invoice();
            },
            error:function(resp) 
            {
                console.log(resp);
            }
        });
    }
}

function calculate_sub_total_amt()
{
    rate =  $("#pro_rate").val();
    qty = $("#pro_qty").val();

    var sgst = 0;
    var cgst = 0;
    var igst = 0;

    var sub_total = parseFloat(rate) * parseFloat(qty);
    if(isNaN(sub_total)) sub_total = 0;

    if($("#acc_type").val() == 1) // within MH
    {
        sgst = $("#pro_sgst").val();
        cgst = $("#pro_cgst").val();
        igst = 0;
    }
    else if($("#acc_type").val() == 2) // outside MH
    {
        sgst = 0;
        cgst = 0;
        igst = $("#pro_igst").val();
    }
    else
    {
        sgst = 0;
        cgst = 0;
        igst = 0;
    }

    var sgst_amt = (parseFloat(sub_total) * parseFloat(sgst)) / 100;
    if(isNaN(sgst_amt)) sgst_amt = 0;
    $("#pro_sgst_total").val(sgst_amt.toFixed(3));

    var cgst_amt = (parseFloat(sub_total) * parseFloat(cgst)) / 100;
    if(isNaN(cgst_amt)) cgst_amt = 0;
    $("#pro_cgst_total").val(cgst_amt.toFixed(3));

    var igst_amt = (parseFloat(sub_total) * parseFloat(igst)) / 100;
    if(isNaN(igst_amt)) igst_amt = 0;
    $("#pro_igst_total").val(igst_amt.toFixed(3));

    var total_amt = parseFloat(sub_total) + parseFloat(sgst_amt) + parseFloat(cgst_amt) + parseFloat(igst_amt);
    if(isNaN(total_amt)) total_amt = 0;

    $("#pro_sub_total").val(sub_total.toFixed(2));
    $("#pro_final_total").val(total_amt.toFixed(2));
}

function calculate_final_total_for_trans()
{
    var total_qty = 0;
    var total_rate = 0;
    var total_sgst_amt = 0;
    var total_cgst_amt = 0;
    var total_igst_amt = 0;
    var total_sub_amt = 0;
    var total_final = 0;

    var total_tr = $('#invoice_wrapper tr').length;

    for (var i = 2; i <= total_tr; i++)
    {
        var id = $('#invoice_wrapper tr:nth-child('+i+')').attr('id');
        var lastunderscore = id.lastIndexOf("_");
        var cnt = id.substring(lastunderscore+1);

        var qty=parseFloat($("#inv_qty_"+cnt).val());
        if(isNaN(qty))qty=0;
        total_qty=parseFloat(total_qty)+parseFloat(qty);
        
        var rate=parseFloat($("#inv_rate_"+cnt).val());
        if(isNaN(rate))rate=0;
        total_rate=parseFloat(total_rate)+parseFloat(rate);

        var sgst_amt=parseFloat($("#inv_sgst_total_"+cnt).val());
        if(isNaN(sgst_amt))sgst_amt=0;
        total_sgst_amt=parseFloat(total_sgst_amt)+parseFloat(sgst_amt);

        var cgst_amt=parseFloat($("#inv_cgst_total_"+cnt).val());
        if(isNaN(cgst_amt))cgst_amt=0;
        total_cgst_amt=parseFloat(total_cgst_amt)+parseFloat(cgst_amt);

        var igst_amt=parseFloat($("#inv_igst_total_"+cnt).val());
        if(isNaN(igst_amt))igst_amt=0;
        total_igst_amt=parseFloat(total_igst_amt)+parseFloat(igst_amt);

        var sub_amt=parseFloat($("#inv_sub_total_"+cnt).val());
        if(isNaN(sub_amt))sub_amt=0;
        total_sub_amt=parseFloat(total_sub_amt)+parseFloat(sub_amt);

        var final=parseFloat($("#inv_total_"+cnt).val());
        if(isNaN(final))final=0;
        total_final=parseFloat(total_final)+parseFloat(final);


    }
    $("#total_qty").val(total_qty.toFixed(2));
    $("#total_rate").val(total_rate.toFixed(2));
    $("#total_inv_sgst").val(total_sgst_amt.toFixed(3));
    $("#total_inv_cgst").val(total_cgst_amt.toFixed(3));
    $("#total_inv_igst").val(total_igst_amt.toFixed(3));
    $("#sub_total").val(total_sub_amt.toFixed(2));
    $("#final_total").val(total_final.toFixed(2));
}

function add_invoice_trans_row(id)
{
    var check = 1;
    if($("#pro_id").val() == 0)
    {
        $("#pro_id").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#pro_id").css({'border-color':'#000'});
    }

    if($("#cust_id").val() == 0)
    {
        $("#cust_id").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#cust_id").css({'border-color':'#000'});
    }

    if($("#acc_type").val() == 1)//within MH
    {
        if($("#pro_igst").val() > 0 || $("#pro_igst_total").val() > 0)
        {
            alert("Select customer again")
            $("#cust_id").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#cust_id").css({'border-color':'#000'});
        }
    }

    if($("#sm_acc_type").val() == 2)//outside MH
    {
        if($("#pro_sgst").val() > 0 || $("#pro_sgst_total").val() > 0 || $("#pro_cgst").val() > 0 || $("#pro_cgst_total").val() > 0)
        {
            alert("Select customer again")
            $("#cust_id").css({'border-color':'red'});
            check = 0;
        }
        else
        {
            $("#cust_id").css({'border-color':'#000'});
        }
    }

    if($("#pro_final_total").val() <= 0)
    {
        $("#pro_final_total").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#pro_final_total").css({'border-color':'#000'});
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);
        $("body, html").animate({'scrollTop':0},1000);
    }
    else
    {
        var check_dupli_item = 0;
        if(id != 0)
        {
            var total_tr = $('#invoice_wrapper tr').length;

            for (var i = 2; i <= total_tr; i++)
            {
                id = $('#invoice_wrapper tr:nth-child('+i+')').attr('id');
                lastunderscore = id.lastIndexOf("_");
                cnt = id.substring(lastunderscore+1);
                inv_id = $("#inv_id_"+cnt).val();
                if(duplicate.indexOf(inv_id) < 0)
                {
                    duplicate.push(inv_id);
                }

            }

        }
        var inv_id      = $("#inv_id").val();
        for (var i = 0; i <= duplicate.length; i++)
        {
            if(duplicate.indexOf(inv_id) > -1)
            {
                check_dupli_item = 1;
            }
        }

        if(0)
        {
            alert("Duplicate Item Found");
        }
        else
        {
            duplicate.push(inv_id);

            var data = '';
            data += '<tr id="rowid_'+inv_cnt+'">';

            var pro_id = $("#pro_id").val();
            var pro_name = $("#pro_id option:selected").text();
            var pro_hsn = $("#pro_hsn_code").val();
            var pro_rate = $("#pro_rate").val();

            data += '<td>';
            data += '<input type="hidden" name="inv_id[]" id="inv_id_'+inv_cnt+'" class="form-control floating-input" value="0"/>';
            data += '<input class="form-control floating-input" id="pro_name_'+inv_cnt+'" value="'+pro_name+'" readonly />';
            data += '<input type="hidden" name="pro_id[]" id="pro_id_'+inv_cnt+'" class="form-control floating-input" value="'+pro_id+'"/>';
            data += '</td>';

            data += '<td>';
            data += '<input type="text" name="hsn_code[]" id="hsn_code_'+inv_cnt+'" class="form-control floating-input" value="'+pro_hsn+'" readonly/>';
            data += '</td>';

            data += '<td>';
            data += '<input type="text" name="inv_rate[]" id="inv_rate_'+inv_cnt+'" class="form-control floating-input" value="'+pro_rate+'" readonly/>';
            data += '</td>';

            var pro_qty = $("#pro_qty").val();
            data += '<td>';
            data += '<input type="text" name="inv_qty[]" id="inv_qty_'+inv_cnt+'" class="form-control floating-input" value="'+pro_qty+'" readonly/>';
            data += '</td>';

            var pro_cgst = $("#pro_cgst").val();
            var pro_cgst_total = $("#pro_cgst_total").val();
            data += '<td>';
            data += '<input type="text" name="inv_cgst_total[]" id="inv_cgst_total_'+inv_cnt+'" class="form-control floating-input" value="'+pro_cgst_total+'" readonly/>';
            data += '<input type="text" name="inv_cgst[]" id="inv_cgst_'+inv_cnt+'" class="form-control floating-input" value="'+pro_cgst+'" readonly/>';
            data += '</td>';

            var pro_sgst = $("#pro_sgst").val();
            var pro_sgst_total = $("#pro_sgst_total").val();
            data += '<td>';
            data += '<input type="text" name="inv_sgst_total[]" id="inv_sgst_total_'+inv_cnt+'" class="form-control floating-input" value="'+pro_sgst_total+'" readonly/>';
            data += '<input type="text" name="inv_sgst[]" id="inv_sgst_'+inv_cnt+'" class="form-control floating-input" value="'+pro_sgst+'" readonly/>';
            data += '</td>';

            var pro_igst = $("#pro_igst").val();
            var pro_igst_total = $("#pro_igst_total").val();
            data += '<td>';
            data += '<input type="text" name="inv_igst_total[]" id="inv_igst_total_'+inv_cnt+'" class="form-control floating-input" value="'+pro_igst_total+'" readonly/>';
            data += '<input type="text" name="inv_igst[]" id="inv_igst_'+inv_cnt+'" class="form-control floating-input" value="'+pro_igst+'" readonly/>';
            data += '</td>';

            var pro_sub_total = $("#pro_sub_total").val();
            var pro_final_total = $("#pro_final_total").val();
            data += '<td>';
            data += '<input type="text" name="inv_sub_total[]" id="inv_sub_total_'+inv_cnt+'" class="form-control floating-input" value="'+pro_sub_total+'" readonly/>';
            data += '<input type="text" name="inv_total[]" id="inv_total_'+inv_cnt+'" class="form-control floating-input" value="'+pro_final_total+'" readonly/>';
            data += '</td>';

            data += '<td style="text-align: center;">';
            data += '<a href="javascript:void(0)" onclick="remove_invoice_row('+inv_cnt+')">';
            data += '<i class="glyphicon glyphicon-trash" style="color: #333;padding-top: 9px;"></i>';
            data += '</a>';
            data += '</td>';

            data += '</tr>';

            inv_cnt++;

            $("#invoice_wrapper").append(data);
            calculate_final_total_for_trans();
            $("#pro_id").val(0);
            $("#pro_igst").val('');
            $("#pro_cgst").val('');
            $("#pro_sgst").val('');
            $("#pro_igst_total").val('');
            $("#pro_cgst_total").val('');
            $("#pro_sgst_total").val('');
            
            $("#pro_hsn_code").val('');
            $("#pro_rate").val('');
            $("#pro_qty").val('');
            $("#pro_final_total").val('');
        }
    }
}

function remove_invoice_row(cnt)
{
    $("#rowid_"+cnt).detach();
   calculate_final_total_for_trans();
   // if($("#sm_sub_amt").val() <= 0)
   //  {
   //      $("#sbt_btn").hide();
   //  }
}

function add_invoice(id)
{
    disable_enable_background(false);

    var check = 1;
    if($("#inv_no").val() == '')
    {
        $("#inv_no").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#inv_no").css({'border-color':'#CCC'});
    }

    if($("#inv_entry_date").val() == '')
    {
        $("#inv_entry_date").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#inv_entry_date").css({'border-color':'#CCC'});
    }

    if($("#cust_id ").val() == '')
    {
        $("#cust_id ").css({'border-color':'red'});
        check = 0;
    }
    else
    {
        $("#cust_id ").css({'border-color':'#CCC'});
    }

    if(check == 0)
    {
        var msg = 'Oh snap ! You forgot to enter some information';
        display_alert('err',msg);
        $("body, html").animate({'scrollTop':0},1000);
    }
    else
    {

        var path = base_url+"invoice/invoicectrl/invoice_insert/"+id;
        var form_data = $("#invoice_form").serialize();

        $.ajax({
        type:'post',
        url:path,
        data:form_data,
        dataType:'json',
        success:function(resp)
                
        {
            console.log(resp);
            if(resp['flag'] == 1)
            {
                if(id == 0)
                {
                    var msg = 'Invoice created successfully!';
                    display_alert('succ',msg);
                    $("#invoice_form")[0].reset();
                    $("body, html").animate({'scrollTop':0},2000);
                    // window.open(base_url+"invoice/invoicectrl/invoice_master?action=view",'_blank','width=1024, height=768');
                    window.open(base_url+"invoice/invoicectrl/invoice_master?action=print&id="+resp['last_id'],'_blank','width=1024, height=768');
                }
                else
                {
                    var msg = 'Invoice updated successfully!';
                    display_alert('succ',msg);
                    $("body, html").animate({'scrollTop':0},2000);
                    window.location.reload();
                }
            }
            else if(resp['flag'] == 2)
            {
                var msg = 'This invoice already Exist!';
                display_alert('err',msg);
                $("body, html").animate({'scrollTop':0},1000);
            }
            else
            {
                var msg = 'Database Error ! Please try again letter';
                display_alert('warn',msg);
                $("body, html").animate({'scrollTop':0},1000);
            }
        },function(errmsg)
            {
                console.log(errmsg)
            }
        });
    }
}

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

        if(ans == true)
        {
            var update_path = base_url+"invoice/invoicectrl/delete_invoice/"+id;

            ajaxCall('POST',update_path,'','',resp =>
            {
                if(resp == 2)
                    {
                        alert("You can not delete this item!");
                    }
                    else
                    {
                        // $("#table_reload").load(window.location + " .table");
                        // $("#count_reload").load(window.location + " #total_rows");
                        window.location.reload();
                    }

            },
            errmsg =>
            {});
        }
}