<?php


/*
*
* Rewrite local pickups
*
*/

add_action('woocommerce_after_shipping_rate', function () {
  $delivery_zones = WC_Shipping_Zones::get_zones(); 

    //define the array outside of the loop
    $shipping_costs = [];

    //get all costs in a loop and store them in the array
    foreach ((array) $delivery_zones as $key => $the_zone ) {

    foreach ($the_zone['shipping_methods'] as $value) {
        $shipping_costs[] = $value->cost;
        }
    }

  $rate_table = array();
  $shipping_methods = WC()->shipping->get_shipping_methods();
  foreach ($shipping_methods as $shipping_method) {
    foreach ($shipping_method->rates as $key => $val) {
      $rate_table[$key] = $val->label;
    }
  }

  $current_shipping_cost = (float) WC()->session->get('cart_totals')['shipping_total'];
    $content = '<strong>' . $shipping_costs[0] . '€ </strong>';

    if($current_shipping_cost > 0) {
  		echo '<div class="shipping-handler" id="wc-local-pickup-plus-toggle-default-handling">';
      echo '<div><a class="toggle-default-handling ship"><input checked="checked" type="radio"/></a> '. __("Spedizione","blanka") . $content .'</div>';
      echo '<div><a class="toggle-default-handling pickup"><input type="radio"/></a> '.  __("Ritiro in sede", "blanka") .'</div>';
      echo '</div>';
    } else {
      echo '<div class="shipping-handler" id="wc-local-pickup-plus-toggle-default-handling">';
      echo '<div><a class="toggle-default-handling ship"><input type="radio"/></a> '. __("Spedizione","blanka") . $content . '</div>';
      echo '<div><a class="toggle-default-handling pickup"><input checked="checked" type="radio"/></a>' .  __("Ritiro in sede", "blanka") . '</div>';
      echo '</div>';
    }
});




add_filter( 'woocommerce_cart_shipping_method_full_label', function () {
  return;
});

/*
* Change how the attributes are displayed
*
*/

add_filter('wc_display_product_attributes', 'wc_display_product_attributes_without_link',10,3);

function wc_display_product_attributes_without_link($product) {
  $product_attributes = array();

  // Display weight and dimensions before attribute list.
  $display_dimensions = apply_filters('wc_product_enable_dimensions_display', $product->has_weight() || $product->has_dimensions());

  if ($display_dimensions && $product->has_weight()) {
    $product_attributes['weight'] = array(
      'label' => __('Weight', 'woocommerce'),
      'value' => wc_format_weight($product->get_weight()),
    );
  }

  if ($display_dimensions && $product->has_dimensions()) {
    $product_attributes['dimensions'] = array(
      'label' => __('Dimensions', 'woocommerce'),
      'value' => wc_format_dimensions($product->get_dimensions(false)),
    );
  }

  // Add product attributes to list.
  $attributes = array_filter($product->get_attributes(), 'wc_attributes_array_filter_visible');

  foreach ($attributes as $attribute) {
    $values = array();

    if ($attribute->is_taxonomy()) {
      $attribute_taxonomy = $attribute->get_taxonomy_object();
      $attribute_values   = wc_get_product_terms($product->get_id(), $attribute->get_name(), array('fields' => 'all'));

      foreach ($attribute_values as $attribute_value) {
        $value_name = esc_html($attribute_value->name);
          $values[] = $value_name;
      }
    } else {
      $values = $attribute->get_options();

      foreach ($values as &$value) {
        $value = esc_html($value);
      }
    }

    $product_attributes['attribute_' . sanitize_title_with_dashes($attribute->get_name())] = array(
      'label' => wc_attribute_label($attribute->get_name()),
      'value' => apply_filters('woocommerce_attribute', wpautop(wptexturize(implode(', ', $values))), $attribute, $values),
    );
  }


  /**
   * Hook: woocommerce_display_product_attributes.
   *
   * @since 3.6.0.
   * @param array $product_attributes Array of atributes to display; label, value.
   * @param WC_Product $product Showing attributes for this product.
   */
  $product_attributes = apply_filters('woocommerce_display_product_attributes', $product_attributes, $product);

  wc_get_template(
    'single-product/product-attributes.php',
    array(
      'product_attributes' => $product_attributes,
      // Legacy params.
      'product'            => $product,
      'attributes'         => $attributes,
      'display_dimensions' => $display_dimensions,
    )
  );

}

remove_action('woocommerce_checkout_order_review', 'woocommerce_order_review', 10);
add_action('woocommerce_checkout_before_customer_details', 'woocommerce_order_review', 10);


// function my_woo_setup() {
add_theme_support('woocommerce', array(
  'gallery_thumbnail_image_width' => 1000,
  'gallery_thumbnail_image_height' => 1000,
));
// }
// add_action( 'after_theme_setup', 'my_woo_setup' );

function update_woocommerce_version()
{
  if (class_exists('WooCommerce')) {
    global $woocommerce;

    if (version_compare(get_option('woocommerce_db_version', null), $woocommerce->version, '!=')) {
      update_option('woocommerce_db_version', $woocommerce->version);

      if (!wc_update_product_lookup_tables_is_running()) {
        wc_update_product_lookup_tables();
      }
    }
  }
}
add_action('init', 'update_woocommerce_version');

// hide woocommerce checkout field for company name

add_filter("woocommerce_checkout_fields", "remove_checkout_company_name");

function remove_checkout_company_name($fields) {
  unset($fields["billing"]["billing_company"]);
  return $fields;
}

//add new checkbox near to terms and condition in checkout

add_action('woocommerce_review_order_before_submit', 'blanka_add_checkout_privacy_policy', 9);

function blanka_add_checkout_privacy_policy()
{

  woocommerce_form_field('privacy_policy', array(
    'type'          => 'checkbox',
    'class'         => array('form-row privacy'),
    'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
    'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
    'required'      => true,
    'label'         => __('Your personal data will be used to process your order, support your experience throughout this website, and for other purposes described in our <a href="/privacy-policy">privacy policy</a>', 'blanka'),
  ));
}

// Show notice if customer does not tick

add_action('woocommerce_checkout_process', function () {
  if (!(int) isset($_POST['privacy_policy'])) {
    wc_add_notice(__('Please acknowledge the Privacy Policy'), 'error');
  }
});


add_action('woocommerce_default_catalog_orderby', function () {
  return 'date';
}, 10, 2);


// add a buy now button

function buy_now_submit_form()
{
?>
  <script>
    jQuery(document).ready(function() {
      // listen if someone clicks 'Buy Now' button
      jQuery('#buy_now_button').click(function() {
        // set value to 1
        jQuery('#is_buy_now').val('1');
        //submit the form
        jQuery('form.cart').submit();
      });
    });
  </script>
<?php
}
add_action('woocommerce_after_add_to_cart_form', 'buy_now_submit_form');

add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($redirect_url)
{
  if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
    global $woocommerce;
    $redirect_url = wc_get_checkout_url();
  }
  return $redirect_url;
}

// DIFFERENT ADDRESS IN CHECKOUT
add_filter('woocommerce_ship_to_different_address_checked', '__return_false');

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter('loop_shop_per_page', 'new_loop_shop_per_page', 20);

function new_loop_shop_per_page($cols)
{
  // $cols contains the current number of products per page based on the value stored on Options -> Reading
  // Return the number of products you wanna show per page.
  $cols = 24;
  return $cols;
}

add_filter('woocommerce_single_product_image_thumbnail_html', 'wc_remove_link_on_thumbnails');

function wc_remove_link_on_thumbnails($html)
{
  return strip_tags($html, '<img>');
}

/**
 * Insert/Remove the endpoint into the My Account menu.
 *
 * @param array $items
 * @return array
 */
function my_custom_my_account_menu_items($items)
{
  // Remove the menu item.
  $downloads = $items['downloads'];
  unset($items['downloads']);
  $customer_logout = $items['customer-logout'];
  unset($items['customer-logout']);
  // var_dump($items);
  $items['tinv_wishlist'] = "Portagioie";
  // Insert your custom endpoint.
  // $items['my-custom-endpoint'] = __( 'My Custom Endpoint', 'woocommerce' );

  // Insert back the item.
  // $items['downloads'] = $downloads;

  return $items;
}

add_filter('woocommerce_account_menu_items', 'my_custom_my_account_menu_items');

add_action('widgets_init', 'BLANKA_add_all_products');
function BLANKA_add_all_products()
{
  if (class_exists('WC_Widget_Product_Categories')) {
    unregister_widget('WC_Widget_Product_Categories');
    include_once(get_template_directory() . '/inc/widgets/_custom-product-categories.php'); //link to my theme widget path
    register_widget('BLANKA_add_all_products');
  }
}

add_filter('woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability($availability, $_product)
{
  // Change In Stock Text
  if ($_product->is_in_stock()) {
    $availability['availability'] = '';
  }
  // Change Out of Stock Text
  if (!$_product->is_in_stock()) {
    $availability['availability'] = __('Venduto', 'woocommerce');
  }
  return $availability;
}

// if(!function_exists('my_custom_checkout_field')) {
//   function my_custom_checkout_field( $checkout ) {
//     woocommerce_form_field( 'ID_card', array(
//       'type'          => 'file',
//       'required'      => true,
//       'class'         => array('my-field-class form-row-wide'),
//       'label'         => __('ID card'),
//       'placeholder'   => __('Enter your front & back photo'),
//     ), $checkout->get_value( 'ID_card' ));
//   }
//   add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
// }
// if(!function_exists('my_custom_checkout_field_process')) {
//   /**
//    * Process the checkout
//    */
//   function my_custom_checkout_field_process() {
//     // Check if set, if its not set add an error.
//     if ( ! $_POST['ID_card'] )
//       wc_add_notice( __( 'Please enter a valid photo of you document.' ), 'error' );
//   }
//   add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
// }
