$(document).ready(function () {

    $('.pro-price-remove').on('click', function() {
        var cartitem = $(this).attr("cartitem_id");
        removecartfunction(cartitem);
    });

    function removecartfunction(cartitem) {
        if(cartitem != ""){            
            $.ajax({
                type   : 'post',
                dataType: 'JSON',
                url    : '/wp-admin/admin-ajax.php',
                data   : {
                    'action': 'removecart',
                    'cartitem_id':cartitem
                },
                success: function(data) {
                    console.log(data);                    
                    $(".cartajaxtop").load("/wp-admin/admin-ajax.php?action=getajaxcart");
                    $(".rightcarttotal").load("/wp-admin/admin-ajax.php?action=ajaxcarttotal");                                        

                    console.log("cartitem: " + cartitem);
                    var defaultstorekey = $(".defaultstorekey" ).val();
                    var cart_currency = $(".cart_currency" ).val()+"D";
                    var skuid = $("#cartitem_"+cartitem+" .product_skuid" ).val();
                    var productname = $("#cartitem_"+cartitem+" .product-name" ).text();
                    var productinfo = $("#cartitem_"+cartitem+" .product-info" ).text(); 
                    var sel_quantity = $("#cartitem_"+cartitem+" .sel_quantity" ).val();           
                    var price_val = $("#cartitem_"+cartitem+" .price_value" ).val();
                    /*priceval = (parseFloat(price_val)/sel_quantity);*/
                    priceval = parseFloat(price_val); 
                    
                    dataLayer.push({ ecommerce: null });  
                    dataLayer.push({
                    'event': 'removeFromCart',
                    'ecommerce': {
                        'remove': {                              
                        'products': [{                          
                            'name': productname,
                            'id': skuid,
                            'size': productinfo,
                            'price': priceval,
                            'quantity': 1
                        }]
                        }
                    }
                    });


                    dataLayer.push({ ga4ecom: null });  
                    dataLayer.push({
                    event: "remove_from_cart",
                    user_id: sessionStorage.getItem( "customer_id" ),
                    ga4ecom: {
                        items: [
                        {
                            item_id: skuid,
                            item_name: productname.toUpperCase(),
                            currency: cart_currency,
                            index: 0,
                            item_brand: "Metal",
                            item_variant: productinfo,
                            location_id: defaultstorekey,
                            price: priceval,
                            quantity: 1
                        }
                        ]
                    }
                    });

                    console.log("name: " + productname + ", id: " + skuid + ", price: " + priceval + ", totalprice: " + price_val + ", quantity: " + sel_quantity + ", productinfo: " + productinfo + ", defaultstorekey: " + defaultstorekey + ", cart_currency: " + cart_currency);

                    $("#cartitem_"+cartitem).remove();
                    var cartpro = $( "div.order-product-container" ).length;
                    if(cartpro == 1){
                        $("div.cart-pro-panel").remove();
                        $("div.cart-note-panel").remove();   

                        window.location.href = '/cart/';            
                    }                   
                }
            });
            // event.preventDefault();
        }
        return true;
    }



    $('.secure-checkout').on('click', function() {
        var cartcomment_val = $("textarea.cartcomment").val();
        securecheckout(cartcomment_val);
    });

    function securecheckout(cartcomment_val) { 
        if(cartcomment_val != ""){  console.log(cartcomment_val + " -- cartcomment");
            $.ajax({
                type   : 'post',
                dataType: 'JSON',
                url    : '/wp-admin/admin-ajax.php',
                data   : {
                    'action': 'cartcomment',
                    'cartcomment_val':cartcomment_val
                },
                success: function(data) {
                    console.log(data); 
                    if(data.code >= 200){
                        window.location.href = '/checkout/';
                    }                   
                }
            });
            // event.preventDefault();
        }else{
            window.location.href = '/checkout/';
        }
        return true;
    }



    $('.pro_length').on('input', function() {  
        var myval = $(this).val(); 
        if (myval.indexOf('.') != -1){
            var num = parseFloat(myval);
            var cleanNum = num.toFixed(3);       
            
            var decimalval = myval.toString().split(".")[1].length; 
            if(decimalval > 4){
            $(this).val(cleanNum);
            }
        }  
        priceFunction("pro"+this.id);             
    });

    $('.pro_width').on('input', function() {  
        var myval = $(this).val(); 
        if (myval.indexOf('.') != -1){
            var num = parseFloat(myval);
            var cleanNum = num.toFixed(3);        
            var decimalval = myval.toString().split(".")[1].length;   
            if(decimalval > 4){
                $(this).val(cleanNum);
            }
            
            if(num/cleanNum < 1){ }
        }            
        priceFunction("prol"+this.id);          
    });

    $('select.sel_units').on('change', function() {        
        var selquantity = $( ".proli"+this.id+" .sel_quantity" ).val(); 
        $(".proli"+this.id+" .pro_price span").removeClass("error");  

        if(parseFloat(selquantity) < '32001'){            
        $(".proli"+this.id+" .sel_quantity" ).val("");
        $(".proli"+this.id+" .pro_price span").html(""); 
        priceFunction("proli"+this.id);
        }else{
        $( ".proli"+this.id+" .sel_quantity" ).val("");
        $(".proli"+this.id+" .pro_price span").html("select size and quantity");
        }

        var num = parseFloat($(this).val());
        var cleanNum = num.toFixed(0);
        if(!isNaN(cleanNum)){          
        $(this).val(cleanNum);          
        }
        if(num/cleanNum < 1){  }         
    });

    $(".sel_quantity").on('input', function() {  
        var selquantity = $( "."+this.id+" .sel_quantity" ).val();
        
        if (selquantity.indexOf('.') != -1){
            var num = parseFloat(selquantity);
            var cleanNum = num.toFixed(0);            
            var decimalval = selquantity.toString().split(".")[0].length; 
            if(decimalval > 0){
                $(this).val(cleanNum);
            }
        } 

        if(parseInt(selquantity) < '32001' && parseInt(selquantity) != ""){
            priceFunction(this.id);                          
        }else{
        $( "."+this.id+" .sel_quantity" ).val("");
        $("."+this.id+" .pro_price span").html("select size and quantity");
        }        
    });


    function priceFunction(prolistno) {   
        var pro_id = $( "."+prolistno+" .pro_id" ).val();
        var pro_sku = $( "."+prolistno+" .pro_sku" ).val();
        var prowidth = $( "."+prolistno+" .pro_width" ).val();
        var prolength = $( "."+prolistno+" .pro_length" ).val();
        var selunits = $( "."+prolistno+" .sel_units" ).val();
        var selquantity = $( "."+prolistno+" .sel_quantity" ).val();
        var pro_name = $( "."+prolistno+" .product-name" ).text();
        var pro_info = $( "."+prolistno+" .product-info" ).text();

        console.log(prolength + " - " + prowidth + " - " + selquantity);
        
        const store = JSON.parse( sessionStorage.getItem( "msm_store" ) );
        const store_id = store.storeID;
        const store_country = store.storeCountry;
        console.log("cartpage store_id: ",store_id);

        if((prolength != "" || prolength =="undefined") && (prowidth != "" || prowidth =="undefined") && selquantity != ""){ 
        $("."+prolistno+" .pro_price span").removeClass("error");
        $("."+prolistno+" .pro_price span").html("");
        $("."+prolistno+" .pro_price .price-loader").addClass("showloader");

            $.ajax({            
            type   : 'post',
            dataType: 'JSON',
            url    : '/wp-admin/admin-ajax.php',          
            data   : {
                'action': 'get_product_price',
                'store_id':store_id,            
                'store_country':store_country,            
                'pro_id':pro_id,            
                'pro_sku':pro_sku,            
                'prowidth':prowidth,            
                'prolength':prolength,            
                'selunits':selunits,            
                'selquantity':selquantity,            
            },
            success: function(data) {                 
                console.log("product_price: ", data);                    
                
                var storeCountry = store.storeCountry;
                var storeCurrency = "CAD";
                if(storeCountry == "Canada"){
                    storeCurrency = "CAD";
                }else{
                    storeCurrency = "USD";
                }
                
                
                if(data.productPrice != null){ 
                    $(" .proprice_"+prolistno+" span.priceval").html(storeCurrency+" $"+data.productPrice);                    

                    $("."+prolistno+" .pro_price_input").val(data.productPrice);  
                    $("."+prolistno+" .pro_price span").removeClass("error");
                    
                    $("."+prolistno+" .productbtn button").addClass("pricebutton");

                    $("."+prolistno+" .derror span.pro_error ").html("");

                    dataLayer.push({ ga4ecom: null });  
                    dataLayer.push({
                      event: "view_item",
                      user_id: sessionStorage.getItem( "customer_id" ),
                      ga4ecom: {
                        items: [
                          {
                            item_id: pro_sku,
                            item_name: pro_name.toUpperCase(),
                            currency: storeCurrency,
                            index: 0,
                            item_brand: "Metal",
                            item_variant: pro_info,
                            location_id: $(".defaultstorekey" ).val(),
                            price: parseFloat(data.productPrice),
                            affiliation: "Online Store",
                            quantity: 1
                          }
                        ]
                      }
                    });

                }else{
                    $("."+prolistno+" .pro_price span").removeClass("pricespan");

                    $("."+prolistno+" .pro_price span").addClass("error"); 
                    $(" .proprice_"+prolistno+" span.priceval").html("");
                    $("."+prolistno+" .derror span.pro_error ").html(data.message);
                    
                    $( "."+prolistno+" .pro_price_input" ).val("0");

                    $("."+prolistno+" .productbtn button").removeClass("pricebutton");
                }

                $("."+prolistno+" .pro_price .price-loader").removeClass("showloader");
                
            }                           
            }); 
        }    
        return true;     
    }  

});



$(".addtocart").click(function(){    
    var prolistno = $(this).attr( "pid" );
    var pro_name = $( ".prolist-"+prolistno+" .pro_sku" ).val();
    var pro_price = $( ".prolist-"+prolistno+" .pro_price_input" ).val();
    var pro_id = $( ".prolist-"+prolistno+" .pro_id" ).val();
    var pro_sku = $( ".prolist-"+prolistno+" .pro_sku" ).val();
    var prowidth = $( ".prolist-"+prolistno+" .pro_width" ).val();
    var prolength = $( ".prolist-"+prolistno+" .pro_length" ).val();
    var selunits = $( ".prolist-"+prolistno+" .sel_units" ).val();
    var selquantity = $( ".prolist-"+prolistno+" .sel_quantity" ).val();
    var thispro = $(this);
    var cartitem_id = $(this).attr("cartitem_id");
   
    const store = JSON.parse( sessionStorage.getItem( "msm_store" ) );
    const store_id = store.storeID;  

    if(prolength == "" || prowidth == "" || selquantity == ""){     
      console.log("Addtocard Error: " + prolength + " - " + prowidth + " - " + selquantity);
      $(".prolist-"+prolistno+" .pro_price span").html("select size and quantity");
      $(".prolist-"+prolistno+" .pro_price span").removeClass("pricespan");
      $(".prolist-"+prolistno+" .pro_price span").removeClass("error");
      
      return false;
    }else{
      console.log("Addtocard Added: " + prolength + " - " + prowidth + " - " + selquantity);         
    }

    
    if(prolistno != "0" || selunits != "" || prolength != "" || pro_id != ""){

      $(".prolist-"+prolistno+" .productbtn button").addClass("btnhide");
      $(".prolist-"+prolistno+" .productbtn").addClass("btnshowloader");
      $(".prolist-"+prolistno+" .productbtn.btnshowloader .price-loader").addClass("showloader");
      
        $.ajax({            
          type   : 'post',
          dataType: 'JSON',
          url    : '/wp-admin/admin-ajax.php',          
          data   : {
            'action': 'put_updatecart',
            'store_id':store_id,      
            'pro_id':pro_id,            
            'pro_sku':pro_sku,            
            'prowidth':prowidth,            
            'prolength':prolength,            
            'selunits':selunits,            
            'selquantity':selquantity,            
            'pro_price':pro_price, 
            'cartitem_id':cartitem_id           
          },
          success: function(data) { 
              if(data.cartcode == "201"){  
                thispro.addClass("addedpro");   
                thispro.html('UPDATED');  
                /*
                // $( ".prolist-"+prolistno+" .pro_width" ).val("");
                // $( ".prolist-"+prolistno+" .pro_length" ).val("");
                // $( ".prolist-"+prolistno+" .sel_quantity" ).val("");
                // $( ".prolist-"+prolistno+" .pro_price span").removeClass("pricespan");
                // $( ".prolist-"+prolistno+" .pro_price span" ).text("select size and quantity");
                // $( ".prolist-"+prolistno+" .productbtn button").removeClass("pricebutton");

                // setTimeout(function() {
                //     thispro.removeClass("addedpro");   
                //     thispro.text("UPDATE"); 
                    
                // }, 3000);
         
                // $(".cartajaxtop").load("/wp-admin/admin-ajax.php?action=getajaxcart");
                // $(".rightcarttotal").load("/wp-admin/admin-ajax.php?action=ajaxcarttotal");
                */
                window.location.href = '/cart/';
              }else{
               
                    $(".prolist-"+prolistno+" .pro_price span").removeClass("pricespan");

                    $(".prolist-"+prolistno+" .pro_price span").addClass("error"); 
                    $(" .proprice_"+prolistno+" span.priceval").html("");
                    $(".prolist-"+prolistno+" .derror span.pro_error ").html(data.cartmessage);
                    
                    $( ".prolist-"+prolistno+" .pro_price_input" ).val("0");

                    $(".prolist-"+prolistno+" .productbtn button").removeClass("pricebutton");
              }               
              
              $(".prolist-"+prolistno+" .productbtn button").removeClass("btnhide");
              $(".prolist-"+prolistno+" .productbtn").removeClass("btnshowloader");
              $(".prolist-"+prolistno+" .productbtn .price-loader").removeClass("showloader");
              
          }                           
        }); 
        // event.preventDefault();
    }else{
        alert("Please Select Size");
        return false;
    }  
    return true;
});