/*--------------------------------------------------------------
A Script For Checking Product Availability
Author: Rentopian
Website: https://rentopian.com
Copyright 2023, Rentopian Inc. All Rights Reserved.
----------------------------------------------------------------*/

jQuery(document).ready(function($) {
  var $cartBtn = $("form.cart").find(".single_add_to_cart_button");

  // single product page related
  function check_product_availability() {

    // Check if fly-in form is set and dates are not filled in, exit the function without checking the product availability. 
    let flyInForm = $("#rental_min_date_input");
    if (flyInForm.length && flyInForm.val() === '') {
        return;
    }

    // Check if horizontal is set and form dates are not filled in, exit the function without checking the product availability. 
    let horizontalForm = $("#rntp-form-holder");
    if (horizontalForm.length && !horizontalForm.data('has-start-date') && !horizontalForm.data('has-default-date')) {
      return;
    }

    if ($('div.product').length) {
      var mainProductId = $cartBtn.val();

      var product_id = 0;
      setTimeout(function() {
        if ($('form.variations_form').length) {
          product_id = $(".woocommerce-variation-add-to-cart").find('input.variation_id').val();
        } else {
          product_id = mainProductId;
        }

        block($cartBtn);
        $.ajax({
          type: 'POST',
          url: rentalObj.url,
          dataType: 'JSON',
          data: {
              action: 'rental_check_product_availability',
              product_id: product_id
          },
          success: function(data) {
          },
          error: function(data) {
            console.log('error:', data )
          },
          complete: function(data) {
            var is_available = 0;
            if (data.responseText !== '' && data.responseJSON) {
              is_available = data.responseJSON.is_available;
              // console.log('is_available:', data.responseJSON)
              
              if (is_available == 1) {
                // available
                errorMsg("");
                let err = $(".rntl-product-err");
                if (err.length > 0) {
                  err.hide();
                }
                
                $cartBtn.removeClass("disabled");
               // $cartBtn.removeAttr("disabled");
                $cartBtn.prop("disabled", false);
                
                $cartBtn.fadeIn();

                // on addon error, display addon modal
                if ($(".woocommerce-notices-wrapper .woocommerce-error").length) {
                  let addonErrorMsg = $(".woocommerce-notices-wrapper .woocommerce-error li").html();
                  let targetErrorMsg = 'Please, select from the provided addon variations.';
                  if (addonErrorMsg.trim() === targetErrorMsg) {
                    $('#rental_add_ons').data('modal_is_open', 1).show('slow');
                  }
                }

              } else if (is_available == 0) {
                let err = $(".rntl-product-err");

                // unavailable
                errorMsg("Unfortunately, the product is not available.");
                err.show();
                $([document.documentElement, document.body]).animate({
                  scrollTop: err.offset().top - 120
                }, 1000);

                $cartBtn.addClass('disabled');
                $cartBtn.attr("disabled", true);
                $cartBtn.fadeOut();
              } else {
                // rental start date must be selected
                console.log("rental start date must be selected!")
              }
            }
            unblock($cartBtn); 
          }
        });
      
      }, 300)
    }
  }


  if (!$("#_rental_is_set_identifier").length) {
    $cartBtn.addClass('disabled');
    $cartBtn.attr("disabled", true);
    // $cartBtn.fadeOut();
    let $inp_var_id = $(".woocommerce-variation-add-to-cart").find('input.variation_id');
    if ($inp_var_id.length) {
      $inp_var_id.on("change", function() {
        check_product_availability();
      });
    } else {
      check_product_availability();
    }
  }
 
});

function block($node) {
  if ( !$node.is('.processing') && !$node.parents('.processing').length) {
    $node.addClass('processing').block({
      message: null,
      overlayCSS: {
        background: '#fff',
        opacity: 0.6
      }
    });
  }
}

function unblock($node) {
  $node.removeClass('processing').unblock();
}

var errorMsg = function (msg) {
  var $div = jQuery("div.woocommerce-notices-wrapper")
  let errorBox = "";
  if (msg !== "") {
    errorBox = '<div class="rntp-notification rntp-notification--error rntl-product-err" style="margin-top:1rem">' +
      // '<a href class="rntp-notification__close color--error">×</a>' +
      '<div class="rntp-notification__status rntp-bg--gradient-red">' +
        ' &times;' +
      '</div>' +
      '<div class="rntp-notification__content">' +
          '<h4 class="rntp-notification__title"> Product Availability </h4>' +
          '<p class="rntp-notification__text"> '+ msg +' </p>' +
      '</div>' +
    '</div>';
    
    if (!(jQuery(".rntl-product-err").length > 0)) {
      $div.append(errorBox)
    }
   
  } else {
    $div.append(errorBox)
  }
  
};