//Product search js
$("body").on("change", ".category_id", function () {
  var category_id = $(this).val();
  $.ajax({
    beforeSend: function() {
        $(".preloader-ajax").show();
        $(".preloader-ajax-bg").show();
      },
    type: "post",
    async: false,
    dataType:"JSON",
    url: base_url+'/admin/product/get_pos_product_by_cat_id',
    data: {
      category_id: category_id,
    },
    success: function (data) {
      if (data.result == "420") 
      {
        $("#product_search").html(
          '<div class="col-sm-12"><h5 class="text-center">Product not found !</h5></div>'
        );
        $(".preloader-ajax").hide();
        $(".preloader-ajax-bg").hide();
      } else 
      {
        $("#product_search").html(data.result);
        $(".preloader-ajax").hide();
        $(".preloader-ajax-bg").hide();
      }
    },
    error: function () {
      alert("Request Failed, Please try again!");
    },
  });
});
$( document ).ready(function() {
    get_all_prd();
});
function get_all_prd() 
{
    $.ajax({
      beforeSend: function() {
        $(".preloader-ajax").show();
        $(".preloader-ajax-bg").show();
      },
      type: "GET",
      dataType:"JSON",
      async: true,
      url: base_url+'/admin/product/get_pos_product',
      success: function (data) 
      {
          $('#product_search').html(data.product);
          $('#all_cat').html(data.category);
          $(".preloader-ajax").hide();
          $(".preloader-ajax-bg").hide();
      },
      error: function () {
        $(".preloader-ajax").hide();
        $(".preloader-ajax-bg").hide();
      }
    });
}
//Product search button js
$("body").on("click", ".select_product", function (e) {
  e.preventDefault();
  store = $("#store_id").val();
  if(store != '')
  {
      var today = new Date();
      var date =
        today.getMonth() + 1 + "-" + today.getDate() + "-" + today.getFullYear();
      var time =
        today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
      var dateTime = date + " " + time;
      var user_name = $("#user_name").val();

      var panel = $(this);
      var product_id = panel
        .find(".item-image input[name=select_product_id]")
        .val();
      var store_id = store;
      $.ajax({
        type: "post",
        dataType: "json",
        async: false,
        url: base_url+'/admin/product/add_pos_prd',
        data: {
          product_id: product_id, store_id :store_id
        },
        success: function (data) {
          if (data.item == 0) 
          {
            alert("Product not available in stock !");
          } 
          else 
          {
            $("#addinvoice tbody").append(data.item);
            $("#order-table tbody").append(data.order);
            $("#bill-table tbody").append(data.bill);

            $("#order_span").empty();
            $("#bill_span").empty();
            var styles =
              "<style>table, th, td { border-collapse:collapse; border-bottom: 1px solid #CCC; } .no-border { border: 0; } .bold { font-weight: bold; }</style>";

        
            var addSerialNumber = function () {
              var i = 1;
              $("#order-table tbody tr").each(function (index) {
                $(this)
                  .find("td:nth-child(1)")
                  .html("#" + (index + 1));
              });
              $("#bill-table tbody tr").each(function (index) {
                $(this)
                  .find("td:nth-child(1)")
                  .html("#" + (index + 1));
              });
            };
            addSerialNumber();
            buzz();
            
          }

          //Total items count
          $("#item-number").html("0");
          var count = 0;
          $(".itemNumber>tr").each(function (i) {
            $("#item-number").html(i + 1);
            count = i + 1;
            $(".item_bill").html(i + 1);
          });
          check_btn(count);
        },
        error: function (e) {
            console.log(e)
          alert("Request Failed, Please try again!");
        },
      });
    }else
    {
        swal('error', "Please Select A Shop", 'error');
        return false;
    }

    
});

function check_btn(e) 
{
   if(e >= 1)
   {
        $('#cart_submitt').attr("disabled", false);
   }
   else
   {
        $('#cart_submitt').attr("disabled", true);
   }
}

function buzz() 
{
    var i = 0;
    while (i < 2) {
        
    $("#icon-bar").animate({
        right: "15px",
    }, 50);
   
    $("#icon-bar").animate({
         right: "10px",
    }, 50);
    
    $("#icon-bar").animate({
         right: "15px",
    },50);

    $("#icon-bar").animate({
         right: "10px",
    },50);

     i++;   
    }
}

//Delete a pos row from POS table
function deletePosRow(t) {

    $("#"+t).remove();
    $("."+t).remove();

    calculateSum();
    // invoice_paidamount();

    $('#item-number').html('0');
     var count = 0;
    $(".itemNumber>tr").each(function(i){
        $('#item-number').html(i+1);
        $('.item_bill').html(i+1);
        count = i + 1;
    });
    check_btn(count);
}
//Select stock by product and variant id
    $('body').on('change', '.variant_id', function () {

        var sl = $(this).parent().parent().find(".sl").val();
        var product_id = sl;
        var avl_qntt = $('#avl_qntt_' + sl).val();
        var store_id = $('#store_id').val();
        var qty = $('#total_qntt_'+ sl).val();
        var store = $("#store_id").val();
        var tax = $('#tax_'+ sl).val();
        // var ttl_tax = $('#ttl_tax_'+ sl).val();
        
        var ttl_p = $('#total_price_'+sl).val();
        var grandTotal = $('#grandTotal').val();
        var variant_id = $(this).val();
        if(variant_id != '')
        {
            $.ajax({
               beforeSend: function() {
                  $(".loader").show();
              },
               type: "post",
               async: false,
               url: base_url+'/admin/product/product_avaliblity_check_with_price_for_sp_from_bucket_list',
               data: {product_id: product_id, variant_id: variant_id, store:store},
               success: function (data) {
                  var obj = jQuery.parseJSON(data);
                  var pri = obj.ttl_price * qty;
                  $('#price_item_'+sl).val(obj.ttl_price);
                  $('#total_price_'+sl).val(obj.ttl_price);
                  $(".loader").hide();
               },
               error: function () {
                   alert('Request Failed, Please check your code and try again!');
                    $(".loader").hide();
               }
            });
         }
         else
         {
            alert('Please Select A Varient');
             $(".loader").hide();
         }
    });
    //Quantity calculate
function quantity_calculate(item) {
    var quantity        = $("#total_qntt_" + item).val();
    var price_item      = $("#price_item_" + item).val();
    var discount        = $("#discount_" + item).val();
    var total_discount  = $("#total_discount_" + item).val();
    // var tax             = $("#tax_" + item).val();
    var tax             = 0;
    var product_id      = $('.product_id_' + item).val();
    var varient         = $('#variant_id_'+item).val();
    var store           = $("#store_id").val();

        $.ajax({
          beforeSend: function() {
             $(".loader").show();
         },
          type: "post",
          async: false,
          url: base_url+'/admin/product/product_avaliblity_check_with_price_for_sp_from_bucket_list',
          data: {product_id: product_id, variant_id: varient, store:store},
          success: function (data) {
             var obj = jQuery.parseJSON(data);
             if(obj.prd_qty >= parseInt(quantity))
             {
                $(".loader").hide();
       
             }
             else
             {
                alert("product Out of Stock");
                $('#total_qntt_'+ item).val(0);
                $(".loader").hide();

             }
          },
          error: function (e) {
              console.log(e.responseText);
          }
       });

    // var cgst        = $("#cgst_" + item).val();
    // var sgst        = $("#sgst_" + item).val();
    // var igst        = $("#igst_" + item).val();

    // var all_discount = discount * quantity;
    // $("#all_discount_" + item).val(all_discount);

    // //Tax calculation
    // var net_price = (quantity * price_item) - all_discount;
    // var cgst_tax  = (net_price * cgst);
    // var sgst_tax  = (net_price * sgst);
    // var igst_tax  = (net_price * igst);

    // //Tax calculation set
    // $("#total_cgst_" + item).val(cgst_tax);
    // $("#total_sgst_" + item).val(sgst_tax);
    // $("#total_igst_" + item).val(igst_tax);
    if (quantity > 0) {
        var reeta = price_item * quantity;
        var tot_price = (reeta * tax / 100) + reeta;
        var ttl_tax = tot_price - reeta;

        $("#ttl_tax_" + item).val(ttl_tax);
        $("#total_price_" + item).val(tot_price);
        
        $("#quantity_" + item).text('[ '+quantity+' ]');
        $(".qnt_price_" + item).text('('+quantity+' x '+price_item+')');
        $(".total_price_bill_" + item).text(n);

    }else {
        var n = quantity * price_item;
        $("#total_price_" + item).val(n);

    }
     calculateSum();
    
}


//Calculate all summation
function calculateSum() {
    var cgst = 0;
    var sgst = 0;
    var igst = 0;
    var e = 0;
    var f = 0;
    var total_discount = 0;
    var total_price = 0;
    var inv_dis = 0;
    var ser_chg = 0;
    var shipping_charge=0;
    //Total CGST
    $(".total_cgst").each(function() {
        isNaN(this.value) || 0 == this.value.length || (cgst += parseFloat(this.value))
    }),
        $("#total_cgst").val(cgst.toFixed(2)),
        $(".total_cgst_bill").text(cgst.toFixed(2)),

        //Total SGST
        $(".total_sgst").each(function() {
            isNaN(this.value) || 0 == this.value.length || (sgst += parseFloat(this.value))
        }),
        $("#total_sgst").val(sgst.toFixed(2)),
        $(".total_sgst_bill").text(sgst.toFixed(2)),

        //Total IGST
        $(".total_igst").each(function() {
            isNaN(this.value) || 0 == this.value.length || (igst += parseFloat(this.value))
        }),
        $("#total_igst").val(igst.toFixed(2)),
        $(".total_igst_bill").text(igst.toFixed(2)),

        //Total Discount
        $(".total_discount").each(function() {
            isNaN(this.value) || 0 == this.value.length || (total_discount += parseFloat(this.value))
        }),
        $("#total_discount_ammount").val(total_discount.toFixed(2)),
        $(".total_discount_bill").text(total_discount.toFixed(2)),

        //Total Price
        $(".total_price").each(function() {
            isNaN(this.value) || 0 == this.value.length || (total_price += parseFloat(this.value))
        }),

        cgst = cgst.toFixed(2),
        sgst = sgst.toFixed(2),
        igst = igst.toFixed(2),
        e    = total_price.toFixed(2),
        f    = total_discount.toFixed(2),
        inv_dis = 0,
        ser_chg = 0;
        shipping_charge = (($("#deliverCharge").val())? $("#deliverCharge").val() : 0);

    sum = +e+ - inv_dis+ +shipping_charge;
    $("#grandTotal").val(sum.toFixed(2));
    $(".total_bill").text(sum.toFixed(2));
  
    
}
$("#idForm").submit(function(e) {
   e.preventDefault(); 
   var form = $(this);
   $.ajax({
      beforeSend: function() {
         $(".preloader-ajax").show();
         $(".preloader-ajax-bg").show();
      },
      type: "POST",
      url: base_url+'/home/add_bucket_list_data',
      data: form.serialize(), 
      success: function(data)
      {
         $('#idForm').load(window.location.href + " #idForm" );
         $('#item-number').html('0');
         $("#cart_box").load(window.location.href + " #cart_box" );
         $("#footer-cart").load(window.location.href + " #footer-cart" );
         $(".preloader-ajax").hide();
         $(".preloader-ajax-bg").hide();
         swal('Wow', 'Product Successfully Added in your Cart', 'success')
      },
      error: function (e) {
        console.log(e.responseText);
      }
   });
});