/*--------------------------------------------------------------
Rentopian Sync Checkout Scripts
Author: Rentopian
Website: https://rentopian.com
Copyright 2019, Rentopian Inc. All Rights Reserved.
----------------------------------------------------------------*/

jQuery(document).ready(function($) {

  // event time picker
  var $event_time = $('#rental_event_time');
  $event_time.calentim({
    showCalendars: false,
    showTimePickers: true,
    format: 'h:mm A',
    singleDate: true,
    minDate: $event_time.attr('min'),
    minuteSteps: 15
  });

  // pick up address
  // $('#rental_different_pick_up_address').on('change', function() {
  //   $('#rental_pick_up_address_fields')[this.checked? 'show': 'hide']();
  //   $('#rental_pick_up_address_fields').find("#rental_pick_up_country").val('US').trigger('change');
  //   $('#rental_pick_up_address_fields').find("#rental_pick_up_country_field").hide();
  // });

  // damage waiver
  $('input[type=radio][name="damage_waiver"]').on('change', function() {
    var val = this.value;
    $.ajax({
      type: 'POST',
      url: rentalObj.url,
      data: {
        action: 'rental_damage_waiver',
        damage_waiver: val
      },
      success: function() {
        $('body').trigger('update_checkout');
      },
      error: function(data) {
        console.log(data);
      }
    });
  });


    // set customer input full address in checkout page
    var $city = $("#billing_city");
    var $state = $("#billing_state");
    var $country = $("#billing_country");
    var $zip = $("#billing_postcode");
    var $address = $("#billing_address_1");
    var $address_2 = $("#billing_address_2");

    var $city_shipping = $("#shipping_city");
    var $state_shipping = $("#shipping_state");
    var $country_shipping = $("#shipping_country");
    var $zip_shipping = $("#shipping_postcode");
    var $address_shipping = $("#shipping_address_1");
    var $address_2_shipping = $("#shipping_address_2");

    block($city);
    block($state);
    block($country);
    block($address);
    block($address_2);
    $.ajax({
      type: 'GET',
      url: rentalObj.url,
      data: {
        action: 'rental_replace_full_address_in_checkout',
      },
      success: function(data) {
      },
      error: function(data) {
        console.log(data);
      },complete: function(result) {

        var data = result.responseJSON;

        if (data !== undefined && data) {

            if (data.zip !== '' && data.address === '') {
              // custom zip code(not from google map)
              $zip.val(data.zip);
              $zip_shipping.val(data.zip);

            } else if (data.address === '' && data.zip === '') {
              // address data from google map
              var googleMapData = getCookie('rental_google_map_address');

              if (googleMapData !== '' && googleMapData !== undefined) {
                if (isJsonString(googleMapData)) {
                  var address_parts = JSON.parse(googleMapData);
                  if (address_parts.length) {
                    var city, state, country, zip, address, address_2;
                    for(var i in address_parts) {
                      if (address_parts[i]['key'] === 'city') {
                        city = address_parts[i]['value'];
                      } else if (address_parts[i]['key'] === 'state') {
                        state = address_parts[i]['value'];
                      } else if (address_parts[i]['key'] === 'country') {
                        country = address_parts[i]['value'];
                      } else if (address_parts[i]['key'] === 'zip') {
                        zip = address_parts[i]['value'];
                      } else if (address_parts[i]['key'] === 'address') {
                        address = address_parts[i]['value'].trim();
                      } else if (address_parts[i]['key'] === 'address_2') {
                        address_2 = address_parts[i]['value'].trim();
                      }
                    }
          
                    if (city !== undefined && city !== '') {
                      $city.val(city);
                      $city_shipping.val(city);
                    }
                    if (state !== '') {
                      $state.val(state).trigger('change');
                      $state_shipping.val(state).trigger('change');
                    }
                    if (country !== '') {
                      $country.val(country).trigger('change');
                      $country_shipping.val(country).trigger('change');
                    }
          
                    // if (data.zip != '') {
                    //   $zip.val(data.zip);
                    //   $zip_shipping.val(data.zip);
                    // } else {
                      if (zip !== undefined && zip !== '') {
                        $zip.val(zip);
                        $zip_shipping.val(zip);
                      }
                    // }
      
                    if (address !== '') {
                      $address.val(address);
                      $address_shipping.val(address);
                    }

                    if (address_2 !== '') {
                      $address_2.val(address_2);
                      $address_2_shipping.val(address_2);
                    }
                    

                  }
                }
                
              }
              

            } else {

              // custom address/zip code(not from google map) in full address delivery mode
              $city.val('');
              $state.val('').trigger('change');
              $country.val('US').trigger('change');

              if (data.zip !== '') {
                $zip.val(data.zip);
                $zip_shipping.val(data.zip);
              }
              $address.val(data.address);
              $address_shipping.val(data.address);
            }
  
            
        } else {

          // remove previous remaining data
          $city.val('');
          $state.val('').trigger('change');
          $country.val('US').trigger('change');
          $zip.val('');
          $address.val('');
          $address_2.val('');

          $city_shipping.val('');
          $state_shipping.val('').trigger('change');
          $country_shipping.val('US').trigger('change');
          $zip_shipping.val('');
          $address_shipping.val('');
          $address_2_shipping.val('');
        }

        $('body').trigger('update_checkout', { update_shipping_method: true });
        unblock($city);
        unblock($state);
        unblock($country);
        unblock($address);
        unblock($address_2);
      }
    });


    const inputSelector = "input[id^='rental_custom_fields'], select[id^='rental_custom_fields']";
    const containerSelector = ".woocommerce-additional-fields";

    function saveToLocal(element) {
      const elementId = element.attr('id');
      let elementValue;

      if (element.is('select')) {

          if (element.prop('multiple')) {

            // For multi-select, save all selected values as JSON
            elementValue = element.val(); // This returns an array
            if (elementValue) {
                localStorage.setItem(elementId, JSON.stringify(elementValue));
            } else {
                localStorage.removeItem(elementId);
            }

          } else {

            // For simple select, save the selected value
            elementValue = element.val();
            if (elementValue) {
                localStorage.setItem(elementId, elementValue);
            } else {
                localStorage.removeItem(elementId);
            }
          }

      } else {
          // For other input types
          localStorage.setItem(elementId, element.val());
      }
    }

    
    // Attach event listeners for existing and dynamically added elements
    $(document).on('change', `${containerSelector} ${inputSelector}`, function () {
        saveToLocal($(this));
    });


    setTimeout(() => {

        Object.keys(localStorage).forEach(function (key) {
            if (key.startsWith('rental_custom_fields')) {
                const storedValue = localStorage.getItem(key);

                // Escape brackets in the key for the jQuery selector
                const escapedKey = key.replace(/[\[\]]/g, '\\$&');
                const $element = $(`#${escapedKey}`);

                // console.log("Key:", key, "Stored Value:", storedValue, "Element:", $element);

                if ($element.length) {

                    if ($element.is('select')) {

                      if ($element.prop('multiple')) {

                        // Restore multi-select values
                        const values = JSON.parse(storedValue);
                        $element.val(values).trigger('change'); // Trigger change to update UI if needed

                      } else {
                        // Restore simple select value
                        $element.val(storedValue).trigger('change');
                      }

                    } else {
                        // Restore other input values
                        $element.val(storedValue);
                    }
                }
            }
        });


    }, 500);
    

    setTimeout(() => {

      $('#rental_payment_tip_id').on('change', function() {
          updateTipAmount();
      });

    }, 1000);

    updateTipAmount();

    function updateTipAmount() {
      let tipId = $('#rental_payment_tip_id').val()

      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        data: {
          action: 'rental_update_total_on_tip_amount_change',
          tip_id: tipId,
        },
        success: function(data) {
        },
        error: function(data) {
          console.log(data);
        },complete: function(result) {

          var data = result.responseJSON;

          if (data !== undefined && data) {
            
            
            let newHTML = '<span class="woocommerce-Price-amount amount">' +
                              '<bdi>' +
                                  '<span class="woocommerce-Price-currencySymbol">'+ data.currency +'</span>' + data.payment_tip_amount +
                              '</bdi>' +
                          '</span>';
            
            $('#rental-tip-amount').html(newHTML);
          }

          $('body').trigger('update_checkout');
        }
      });
    }


    function checkMinOrderNotice() {

      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        data: {
          action: 'rental_get_min_order_notice'
        },
        success: function(response) {
          
          if (response.success && response.data.message) {

        	  // Check if the message is already displayed to avoid duplicates
            if ($('.woocommerce-error:contains("' + response.data.message + '")').length === 0) {
                // $('form.checkout').prepend('<div class="woocommerce-error">' + response.data.message + '</div>');
                $('.woocommerce-terms-and-conditions-wrapper').before('<div class="woocommerce-error">' + response.data.message + '</div>');
            }
			  
          }

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

    }


    $(document.body).on('updated_checkout', function () {
        checkMinOrderNotice();
    });


    const togglePickupCheckbox = $('#rental_different_pick_up_address');

    const savedPickupState = getCookie('rental_different_pick_up_address');
    if (savedPickupState === '1') {
        togglePickupCheckbox.prop('checked', true);
        $('#rental_pick_up_address_fields').show();
        $('#rental_pick_up_address_fields').find("#rental_pick_up_country").val('US').trigger('change');
        $('#rental_pick_up_address_fields').find("#rental_pick_up_country_field").hide();
    } else {
        togglePickupCheckbox.prop('checked', false);
        $('#rental_pick_up_address_fields').hide();
    }

    // Save state when checkbox changes
    togglePickupCheckbox.on('change', function () {
        const isChecked = $(this).is(':checked') ? '1' : '0';
        setCookie('rental_different_pick_up_address', isChecked);

        if (isChecked === '1') {
            $('#rental_pick_up_address_fields').slideDown();
            $('#rental_pick_up_address_fields').find("#rental_pick_up_country").val('US').trigger('change');
            $('#rental_pick_up_address_fields').find("#rental_pick_up_country_field").hide();
        } else {
            $('#rental_pick_up_address_fields').slideUp();
        }
        
        $('body').trigger('update_checkout');
    });


    if (togglePickupCheckbox.is(":checked")) {

      // Monitor all fields that start with 'rental_pick_up_'
      $('input[name^="rental_pick_up_"], select[name^="rental_pick_up_"]').on('change blur', function() {
          const fieldName = $(this).attr('name');
          const value = $(this).val();

          if (typeof setCookie === 'function') {
              setCookie(fieldName, value);
          }
      });


      $('body').trigger('update_checkout');


      // Restore pickup values if exists in cookies
      $('input[name^="rental_pick_up_"], select[name^="rental_pick_up_"]').each(function() {
          const fieldName = $(this).attr('name');
          if (typeof getCookie === 'function') {
              const savedValue = getCookie(fieldName);
              if (savedValue) {
                  $(this).val(savedValue).trigger('change'); // also triggers select2 etc.
              }
          }
      });
    
    } else {

      $('input[name^="rental_pick_up_"], select[name^="rental_pick_up_"]').each(function() {
          const fieldName = $(this).attr('name');
          if (typeof deleteCookie === 'function') {
              deleteCookie(fieldName, "/")
          }
      });

      $('body').trigger('update_checkout');
    }


    const $deliveryTimeSelect = $('select[name="delivery_time_selections_id"]');
    function updateDeliverySelectedTime(timeId){

      if (typeof setCookie === 'function') {
        setCookie('delivery_time_selections_id', timeId);
      }

      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        data: {
          action: 'rental_update_selected_start_end_times',
          selected_time_id: timeId,
          time_type: 'delivery_time'
        },
        success: function(){},
        error: function(xhr){

          let data = xhr.responseJSON || {};
          let errorBox = '';
          if (data.error) {

            const wcBillingFields = $(".woocommerce-billing-fields");
            wcBillingFields.before(errorBox);

            errorBox = '<div class="rntp-notification rntp-notification--error">' +
              '<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"> Please check the following: </h4>' +
                  '<p class="rntp-notification__text">'+ data.error +'</p>' +
              '</div>' +
            '</div>';
            wcBillingFields.before(errorBox);


            $deliveryTimeSelect.addClass('error-input');
            $deliveryTimeSelect.val(0)
            
            // console.log(data);
          }

        },
        complete: function(xhr) {

          let data = xhr.responseJSON || {};
          if (data.success) {

            $('#rntp-rental-dates-summary-wrapper').first().replaceWith(data.checkout_dates_html);
          
            $('.rntp-notification--error').remove();
            $deliveryTimeSelect.removeClass('error-input');
          }

          $('body').trigger('update_checkout');

          if (data.update_checkout_dates === 1) {
            if ($(".rntp-start-date-block").length) {

              if (data.rental_start_date !== '') {
                $(".rntp-start-date-block").find("input#rental_start_date").val(data.rental_start_date)
              }

              if (data.rental_end_date !== '') {
                $(".rntp-start-date-block").find("input#rental_end_date").val(data.rental_end_date)
              }
            }
          }

          // hideProcessingModal();
          
          
          // console.log(" rental_update_selected_start_end_times called:", data);
        }
      });
    }


    
    $deliveryTimeSelect.on('change', function() {

      showProcessingModal();

      updateDeliverySelectedTime($(this).val());

      setTimeout(() => {
      //   hideProcessingModal();
        location.reload();
      }, 300);
    });

    const saved_delivery_time_selections_id = getCookie('delivery_time_selections_id');
    if ( saved_delivery_time_selections_id && $deliveryTimeSelect.find(`option[value="${saved_delivery_time_selections_id}"]`).length ) {
      $deliveryTimeSelect.val(saved_delivery_time_selections_id);
      updateDeliverySelectedTime(saved_delivery_time_selections_id);
    }
    

    const $pickupTimeSelect = $('select[name="pickup_time_selections_id"]');
    function updatePickupSelectedTime(timeId){

      if (typeof setCookie === 'function') {
        setCookie('pickup_time_selections_id', timeId);
      }

      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        data: {
          action: 'rental_update_selected_start_end_times',
          selected_time_id: timeId,
          time_type: 'pickup_time'
        },
        success: function(){},
        error: function(xhr){ 

          let data = xhr.responseJSON || {};
          let errorBox = '';
          if (data.error) {

            const wcBillingFields = $(".woocommerce-billing-fields");
            wcBillingFields.before(errorBox);

            errorBox = '<div class="rntp-notification rntp-notification--error">' +
              '<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"> Please check the following: </h4>' +
                  '<p class="rntp-notification__text">'+ data.error +'</p>' +
              '</div>' +
            '</div>';
            wcBillingFields.before(errorBox);
            
            $pickupTimeSelect.addClass('error-input');
            $pickupTimeSelect.val(0)

            // console.log(data);
          }

        },
        complete: function(xhr) {
          
          let data = xhr.responseJSON || {};
          if (data.success) {

            $('#rntp-rental-dates-summary-wrapper').first().replaceWith(data.checkout_dates_html);

            $('.rntp-notification--error').remove();
            $pickupTimeSelect.removeClass('error-input');
          }

          $('body').trigger('update_checkout');
          
          // hideProcessingModal();
          
          // console.log("after pickup rental_update_selected_start_end_times called:", data);
        }
      });
    }

    
    $pickupTimeSelect.on('change', function() {

      showProcessingModal();

      updatePickupSelectedTime($(this).val());

      setTimeout(() => {
        // hideProcessingModal();
          location.reload();
      }, 300);
    });

    const saved_pickup_time_selections_id = getCookie('pickup_time_selections_id');
    if ( saved_pickup_time_selections_id && $pickupTimeSelect.find(`option[value="${saved_pickup_time_selections_id}"]`).length ) {
      $pickupTimeSelect.val(saved_pickup_time_selections_id);
      updatePickupSelectedTime(saved_pickup_time_selections_id);
    }




    function overrideCheckoutFieldsLabels() {

      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        data: {
          action: 'rental_override_checkout_fields_labels'
        },
        success: function(response) {
          
          if (response.success && response.data.label) {

            let billingAddressLebel = $("label[for=billing_address_1]");
            if (billingAddressLebel.length) {
              billingAddressLebel.text(response.data.label + ' *')
            }

            let shippingAddressLebel = $("label[for=shipping_address_1]");
            if (shippingAddressLebel.length) {
              shippingAddressLebel.text(response.data.label + ' *')
            }

            let pickupAddressLebel = $("label[for=rental_pick_up_address_1]");
            if (pickupAddressLebel.length) {
              pickupAddressLebel.text(response.data.label + ' *')
            }
          }

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

    }

    setTimeout(() => {
      overrideCheckoutFieldsLabels()
    }, 500);


    // if there is dates on checkout form, the time selection must reset
    $(document).on("click", "button#submit_date" , function(e) {
      $deliveryTimeSelect.val(0)
      $pickupTimeSelect.val(0)
      updateDeliverySelectedTime(0)
      updatePickupSelectedTime(0)
    })



    $('#shipping_method').on('change', 'input[name^="shipping_method"]', function(e){
      var $input = $(this);
      var val = $input.val() || '';
      var shipping_method = (val.indexOf('local_pickup') !== -1) ? 2 : 1;
  
      $.ajax({
        type: 'POST',
        url: rentalObj.url,
        dataType: 'json',
        data: {
          action: 'rental_update_shipping_method',
          rental_shipping_method: shipping_method
          // security: rentalObj.nonce
        },
        success: function(response) {
          if (response && response.success) {

            console.log(response.data.message)
          } else {

            console.log('Could not update shipping method')
          }

          $('body').trigger('update_checkout');
          
        },
        error: function(xhr, status, err) {
          console.error('rental_update_shipping_method error:', xhr, status, err);
        }
      });

    })

    

});