<?php
/**
 * Skincare Product Store functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package skincare-product-store
 * @since skincare-product-store 1.0
 */

add_filter('jpeg_quality', function($arg){return 100;});
add_filter('wp_editor_set_quality', function($arg){return 100;});

// Agregar a functions.php de tu tema
function show_if_mobile($atts, $content = null) {
    if (wp_is_mobile()) {
        return do_shortcode($content);
    }
    return '';
}
add_shortcode('mobile', 'show_if_mobile');

function show_if_desktop($atts, $content = null) {
    if (!wp_is_mobile()) {
        return do_shortcode($content);
    }
    return '';
}
add_shortcode('desktop', 'show_if_desktop');

function mostrar_wishlist_si_tiene_productos() {
    if (function_exists('YITH_WCWL')) {
        $wishlist_count = YITH_WCWL()->count_products();
        
        if ($wishlist_count > 0) {
            return do_shortcode('[yith_wcwl_wishlist]');
        }
    }
    return '';
}
add_shortcode('wishlist_condicional', 'mostrar_wishlist_si_tiene_productos');

if ( ! function_exists( 'skincare_product_store_support' ) ) :

	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * @since skincare-product-store 1.0
	 *
	 * @return void
	 */
	function skincare_product_store_support() {

		load_theme_textdomain( 'skincare-product-store', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		// Add support for block styles.
		add_theme_support( 'wp-block-styles' );

		add_theme_support( 'align-wide' );

		// Enqueue editor styles.
		add_editor_style( 'style.css' );

		add_theme_support( 'responsive-embeds' );
		
		// Add support for experimental link color control.
		add_theme_support( 'experimental-link-color' );
	}

endif;

add_action( 'after_setup_theme', 'skincare_product_store_support' );

if ( ! function_exists( 'skincare_product_store_styles' ) ) :

	/**
	 * Enqueue styles.
	 *
	 * @since skincare-product-store 1.0
	 *
	 * @return void
	 */
	function skincare_product_store_styles() {

		// Register theme stylesheet.
		wp_register_style(
			'skincare-product-store-style',
			get_template_directory_uri() . '/style.css',
			array(),
			wp_get_theme()->get( 'Version' )
		);

		wp_enqueue_style( 
			'skincare-product-store-animate-css',
			esc_url(get_template_directory_uri()).'/assets/css/animate.css' 
		);

		// Enqueue theme stylesheet.
		wp_enqueue_style( 'skincare-product-store-style' );

		wp_style_add_data( 'skincare-product-store-style', 'rtl', 'replace' );

		wp_enqueue_style( 'dashicons' );

		wp_enqueue_style('skincare-product-store-swiper-css',
		esc_url(get_template_directory_uri()) . '/assets/css/swiper-bundle.css',
		array()
		);
	}

endif;

add_action( 'wp_enqueue_scripts', 'skincare_product_store_styles' );

/* Enqueue Custom Js */
function skincare_product_store_scripts() {

	wp_enqueue_script( 
		'skincare-product-store-custom', esc_url(get_template_directory_uri()) . '/assets/js/custom.js', 
		array('jquery') 
	);

	wp_enqueue_script( 
		'skincare-product-store-wow', esc_url(get_template_directory_uri()) . '/assets/js/wow.js', 
		array('jquery') 
	);

	wp_enqueue_script(
        'skincare-product-store-scroll-to-top',
        esc_url(get_template_directory_uri()) . '/assets/js/scroll-to-top.js',
        array(), 
        null, 
        true // Load in footer
    );

    wp_enqueue_script(
		'skincare-product-store-swiper-js',
		esc_url(get_template_directory_uri()) . '/assets/js/swiper-bundle.js',
		array(),
		true
	);
}
add_action( 'wp_enqueue_scripts', 'skincare_product_store_scripts' );

/* Enqueue admin-notice-script js */
add_action('admin_enqueue_scripts', function ($hook) {
    if ($hook !== 'appearance_page_skincare-product-store') return;

    wp_enqueue_script('admin-notice-script', get_template_directory_uri() . '/get-started/js/admin-notice-script.js', ['jquery'], null, true);
    wp_localize_script('admin-notice-script', 'pluginInstallerData', [
        'ajaxurl'     => admin_url('admin-ajax.php'),
        'nonce'       => wp_create_nonce('install_wordclever_nonce'), // Match this with PHP nonce check
        'redirectUrl' => admin_url('themes.php?page=skincare-product-store'),
    ]);
});

add_action('wp_ajax_check_wordclever_activation', function () {
    include_once ABSPATH . 'wp-admin/includes/plugin.php';
    $skincare_product_store_plugin_file = 'wordclever-ai-content-writer/wordclever.php';

    if (is_plugin_active($skincare_product_store_plugin_file)) {
        wp_send_json_success(['active' => true]);
    } else {
        wp_send_json_success(['active' => false]);
    }
});
add_filter( 'woocommerce_enable_setup_wizard', '__return_false' );

function skincare_product_store_theme_setting() {
	// Add block patterns
	require get_template_directory() . '/inc/block-pattern.php';

	// Add block Style
	require get_template_directory() . '/inc/block-style.php';

	// TGM
	require get_template_directory() . '/inc/tgm/plugin-activation.php';

	// Get Started
	require get_template_directory() . '/get-started/getstart.php';

	// Get Notice
	require get_template_directory() . '/get-started/notice.php';

	// Get Notice
	require get_template_directory() . '/inc/customizer.php';
}	
add_action('after_setup_theme', 'skincare_product_store_theme_setting');	


function agregar_etiqueta_agotado() {
    global $product;
    
    if (!$product->is_in_stock()) {
        echo '<div class="producto-agotado-overlay">AGOTADO</div>';
    }
}
add_action('woocommerce_before_shop_loop_item_title', 'agregar_etiqueta_agotado', 10);
add_action('woocommerce_before_single_product_summary', 'agregar_etiqueta_agotado', 20);
add_action('pre_get_posts', 'ordenar_productos_por_fecha');

function ordenar_productos_por_fecha($query) {
    if (!is_admin() && $query->is_main_query()) {
        if (is_shop() || is_product_category() || is_product_tag()) {
            $query->set('orderby', 'date');
            $query->set('order', 'DESC'); // DESC = más recientes primero
        }
    }
}

add_filter('gettext', 'cambiar_recommend_products', 20, 3);
add_filter('ngettext', 'cambiar_recommend_products', 20, 3);

function cambiar_recommend_products($translated_text, $text, $domain) {
    if ($translated_text == 'Recommend Products') {
        $translated_text = 'Productos Recomendados'; // Cambia por el texto que quieras
    }
    return $translated_text;
}

add_action('wp_enqueue_scripts', 'theme_enqueue_styles', 998);

function theme_enqueue_styles() {
    wp_enqueue_style('elessi-style', get_template_directory_uri() . '/style.css');
    wp_enqueue_style('elessi-child-style', get_stylesheet_uri());
}

/**
 * @snippet       Change User Role for New Customers - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 4.6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
///////////////////////////////
//   ASSIGN NEW ROLE
  
add_filter( 'woocommerce_new_customer_data', 'bbloomer_assign_custom_role' );
  
function bbloomer_assign_custom_role( $args ) {
  $args['role'] = 'wholesale_customer';
  return $args;
}

add_action ('wp_print_scripts', function () {
	if (wp_script_is ('wc-password-strength-meter', 'enqueued'))
		wp_dequeue_script ('wc-password-strength-meter');
}, 100);

// Remove login form from checkout
add_action( 'woocommerce_before_checkout_form', 'remove_checkout_login_form', 4 );
function remove_checkout_login_form(){
    remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_login_form', 10 );
}


//Esta linea permite ver los campos personalizados nativos de wordpress	
add_filter('acf/settings/remove_wp_meta_box', '__return_false');


/**
* Add Continue Shopping Button on Cart Page
**/
 
add_action( 'woocommerce_after_cart_totals', 'my_add_continue_shopping_button_to_cart' );
 
function my_add_continue_shopping_button_to_cart() {
 $my_shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 //echo '<div class="woocommerce-message">';
 echo '<div class="wc-proceed-to-checkout"><br><br><a href="javascript: window.history.go(-1)" class="checkout-button button alt wc-forward wp-element-button">Seguir Comprando</a></div>';

// echo '<br><a href="'.$my_shop_page_url.'" class="checkout-button button alt wc-forward">Seguir Comprando</a>';
// echo '</div>';
}

add_action( 'woocommerce_review_order_after_submit', 'my_add_continue_shopping_button_to_checkout' );
function my_add_continue_shopping_button_to_checkout() {
 $my_shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 //echo '<div class="woocommerce-message">';
 echo '<div class="wc-proceed-to-checkout"><br><br><a href="javascript: window.history.go(-2)" class="checkout-button button alt wc-forward wp-element-button">Seguir Comprando</a></div>';
 //    echo '<br><br><a href="'.$my_shop_page_url.'" class="checkout-button button alt wc-forward">Sigue Comprando</a>';
 // echo '</div>';
}

function my_text_strings( $translated_text, $text, $domain ) {
    switch ( $translated_text ) {
        case 'Complemento' :
            $translated_text = __( 'Departamento', 'woocommerce' );
            break;
		case 'NIF/CIF' :
			$translated_text = __( 'RUT', 'woocommerce' );
			break;
        case 'NÃºmero de la casa y nombre de la calle' :
			$translated_text = __( 'Calle', 'woocommerce' );
			break;
        case 'Nombre de la calle' :
			$translated_text = __( 'Calle', 'woocommerce' );
			break;
        case 'Localidad / Ciudad' :
			$translated_text = __( 'Comuna', 'woocommerce' );
			break;
		case 'Realizar el pedido' :
            $translated_text = __( 'Finalizar Compra', 'woocommerce' );
            break;
		case 'CONFIGURAR TU CUENTA' :
            $translated_text = __( 'CREAR CUENTA', 'woocommerce' );
            break;
		case 'INICIAR SESIÃ"N EN SU CUENTA' :
            $translated_text = __( 'ENTRAR A MI CUENTA', 'woocommerce' );
            break;
			case 'Pedidos' :
            $translated_text = __( 'Mis Compras', 'woocommerce' );
            break;
		/*	case 'is no longer in stock so this order cannot be paid for. We apologize for any inconvenience caused.' :
            $translated_text = __( 'ya no estÃ¡ disponible y ha sido removido de tu carrito. Esperamos tenerlo pronto para ti.', 'woocommerce' );
            break;
			case 'is not in stock. Please edit your cart and try again. We apologise for any inconvenience caused.' :
            $translated_text = __( 'ya no estÃ¡ disponible y deberÃ¡s elegir otro producto para continuar o eliminarlo del pedido. Esperamos tenerlo pronto de vuelta para ti.', 'woocommerce' );
            break;*/
    }
    return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 20, 3 );






add_action('woocommerce_after_single_product_summary', 'html_below_thumbnails', 9);
function html_below_thumbnails() {
 $terms = ['colgantes'];
    if ( has_term( $terms, 'product_cat', get_the_ID() ) ) { 
       echo '<p>(*) Cadena o cuero se vende por separado.<br>(*) Imagen referencial, producto real puede tener diferencias.</p>';
    } else {		
        echo '<p>(*)Imagen referencial, producto real puede tener diferencias.</p>';  
	}
	$terms = ['insumos'];
	if ( has_term( $terms, 'product_cat', get_the_ID() ) ) { 
		
	} else {
		echo '<h3 class="nasa-title-relate text-center">Elige un empaque para tus joyas</h3>';
		echo do_shortcode('[products category="2775"]');
	}
if( current_user_can('administrator')) { 
	//echo "Esto solo lo ve el administrador";
	
$product=wc_get_product();
	$id=$product->get_id();
	$featured=$product->featured;
	if ($featured == "yes"){
	//	echo "<br>destacado";
		
 if ( has_term( '30/15', 'product_tag' ) ) {
      //echo '30/15';
   }
	}
//
//
//
////print_r($product[]);
//$id=$product->get_id();
//print_r(get_product_meta($id));
}
	
}

/**
* Add custom field to the checkout page
*/
add_action('woocommerce_after_order_notes', 'rut_facturacion');
function rut_facturacion($checkout)
{
echo '<div id="custom_checkout_field"><h3>' . __('<br>Â¿Necesitas Factura?') . '</h3><br>Ingresa el RUT de tu empresa para emitir la factura.<br>';
woocommerce_form_field('rut_facturacion', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
) ,
'label' => __('RUT para Factura:') ,
'placeholder' => __('ej. 11.111.111-1') ,
) ,
$checkout->get_value('rut_facturacion'));
echo '</div>';
}

/**
* Update the value given in custom field
*/

add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta');
function custom_checkout_field_update_order_meta($order_id)
{
if (!empty($_POST['rut_facturacion'])) {
update_post_meta($order_id, 'rut_facturacion',sanitize_text_field($_POST['rut_facturacion']));
}
}

/*MOSTRAR EL RUT DE FACTURACION EN EL ADMIN DE PEDIDOS*/

function njengah_display_order_data_in_admin( $order ){  ?>
<div class="order_data_column">
<div class="address">
<?php
echo '<h3><strong>' . __( 'RUT FACTURA' ) . ':</strong>' . get_post_meta( $order->id, 'rut_facturacion', true ) . '</h3>';?>
</div>
<div class="edit_address">
<?php woocommerce_wp_text_input( array( 'id' => '_njengah_text_field', 'label' => __( 'RUT FACTURA' ), 'wrapper_class' => 'rut_facturacion' ) ); ?>
</div>

</div>

<?php }

add_action( 'woocommerce_admin_order_data_after_order_details', 'njengah_display_order_data_in_admin' );
function njengah_save_extra_details( $post_id, $post ){
update_post_meta( $post_id, '_njengah_text_field', wc_clean( $_POST[ '_njengah_text_field' ] ) );
}

add_action( 'woocommerce_process_shop_order_meta', 'njengah_save_extra_details', 45, 2 );


/* MOSTRAR EL RUT DE FACTURACION EN EL CORREO */

add_filter('woocommerce_email_order_meta_fields', 'njengah_email_order_meta_fields', 10, 3 );
function njengah_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
    // Usar get_id() correctamente
    $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
    
    $rut = get_post_meta( $order_id, '_billing_rut', true );
    if ( !empty($rut) ) {
        $fields['rut_facturacion'] = array(
            'label' => __( 'RUT FACTURA' ),
            'value' => $rut,
        );
    }
    
    return $fields;
}



add_filter( 'woocommerce_email_order_items_args', 'bt_email_order_items_args', 10, 1 );
/**
 * WooCommerce
 * Show thumbs in Order Email sent to customers
 */
function bt_email_order_items_args( $args ) {

    $args['show_image'] = true;
    $args['image_size'] = array( 60, 60 );

    return $args;

}


// Display the product thumbnail in order received page
add_filter( 'woocommerce_order_item_name', 'order_received_item_thumbnail_image', 10, 3 );
function order_received_item_thumbnail_image( $item_name, $item, $is_visible ) {
    // Targeting order received page only
    if( ! is_wc_endpoint_url('order-received') ) return $item_name;

    // Get the WC_Product object (from order item)
    $product = $item->get_product();

    if( $product->get_image_id() > 0 ){
        $product_image = '<span style="float:left;display:block;width:56px;">' . $product->get_image(array(48, 48)) . '</span>';
        $item_name = $product_image . $item_name;
    }

    return $item_name;
}

add_filter( 'woocommerce_product_add_to_cart_text', function( $text ) {
	global $product;
	if ( $product->is_type( 'variable' ) ) {
		$text = $product->is_purchasable() ? __( 'Elegir Medida', 'woocommerce' ) : __( 'Ver mÃ¡s', 'woocommerce' );
	}
	return $text;
}, 10, 2);

add_filter( 'gettext', 'customizing_variable_product_message', 97, 3 );
function customizing_variable_product_message( $translated_text, $untranslated_text, $domain )
{
	$domain ='FEMALE';
    if ($untranslated_text == 'Please select some product options before adding this product to your cart.') {
        $translated_text = __( 'Por favor Elige una Medida para agregar el producto al carrito.', $domain );
    }
    return $translated_text;
}

/**
 * @snippet       Change return to shop link, send to homepage instead
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=603
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_return_to_shop_redirect', 'bbloomer_change_return_shop_url' );
 
function bbloomer_change_return_shop_url() {
return home_url();
}


/**
 * Proper ob_end_flush() for all levels
 *
 * This replaces the WordPress `wp_ob_end_flush_all()` function
 * with a replacement that doesn't cause PHP notices.
 */
remove_action( 'shutdown', 'wp_ob_end_flush_all', 1 );
add_action( 'shutdown', function() {
   while ( @ob_end_flush() );
} );


/* Desactivar opciones por defecto en metodo de pago y metodo de envio */

add_filter( 'pre_option_woocommerce_default_gateway' . '__return_false', 99 );
add_filter( 'woocommerce_shipping_chosen_method', '__return_false', 99);


add_filter( 'woocommerce_email_order_meta_fields', 'filter_email_order_meta_fields_callback', 10, 3 );
function filter_email_order_meta_fields_callback( $fields, $send_to_admin, $order ) {
    if ( $order->get_meta('authorizationCode') ) {
        echo '<h2>Respuesta Webpay</h2>';

        // Defined array of meta keys (labels)
        $meta_keys = ['authorizationCode', 'paymentCodeResult', 'transactionResponse'];

        // Loop though meta keys array to set the fields
        foreach( $meta_keys as $meta_key ){
            if( $meta_value = $order->get_meta($meta_key) ){
                $fields[] = array(
                    'label' => $meta_key,
                    'value' => $meta_value,
                );
            }
        }
    }
    return $fields;
}

/**
 * @snippet       Add Order Note @ Checkout Page - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=358
 * @author        Rodolfo Melogli
 * @compatible    WC 3.5.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_checkout_before_order_review', 'bbloomer_notice_shipping' );
 
function bbloomer_notice_shipping() {
echo '<p class="allow"><strong>El tiempo aproximado para procesar su pedido es de 5 dÃ­as HÃ¡biles. Esto aplica para retiro en tienda y despacho vÃ­a Chilexpress.</strong></p>';
}


// Shop random order. View settings drop down order by Woocommerce > Settings > Products > Display
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'random_list' == $orderby_value ) {
        $args['orderby'] = 'rand';
        $args['order'] = '';
        $args['meta_key'] = '';
    }
    return $args;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['random_list'] = 'Random';
    return $sortby;
}


////////////////////////////////////////////////HASTA AQUI TODO FUNCIONA PERFECTO//////////////////////////////

////////////////////////////////////////////////START DISPLAY DE PRECIOS EN EL CATALOGO//////////////////////////////
add_filter( 'woocommerce_get_price_html', 'wb_change_product_html',  10, 2 );

// Adding a custom field to the price markup
function wb_change_product_html( $price, $product ) {
    $price_html=0;
    $nuevo_html = '';
    if ( has_term( 'nuevo', 'product_tag', $product->get_id() ) ){
        $nuevo_html = '<table class="badge_nuevo_verde"><tr><td>NUEVO</td></table><br>';
    }

    $detalle="";
    $xmayor="";
	$descuento_mayorista = 1;
	if ( $product->is_on_sale()) {

		if ( has_term( '30/10', 'product_tag', $product->get_id() ) ) {
			$detalle="30";
			$xmayor="10";
			$descuento_mayorista = 0.9;
		}elseif ( has_term( '30/15', 'product_tag', $product->get_id() ) ){
			$detalle="30";
			$xmayor="15";
			$descuento_mayorista = 0.85;
		}elseif ( has_term( '35/15', 'product_tag', $product->get_id() ) ){
			$detalle="35";
			$xmayor="15";
			$descuento_mayorista = 0.85;
		}elseif ( has_term( '35/20', 'product_tag', $product->get_id() ) ){
			$detalle="35";
			$xmayor="20";
			$descuento_mayorista = 0.8;
		}elseif ( has_term( '40/15', 'product_tag', $product->get_id() ) ){
			$detalle="40";
			$xmayor="15";
			$descuento_mayorista = 0.85;
		}elseif ( has_term( '40/20', 'product_tag', $product->get_id() ) ){
			$detalle="40";
			$xmayor="20";
			$descuento_mayorista = 0.8;
		}elseif ( has_term( '40/25', 'product_tag', $product->get_id() ) ){
			$detalle="40";
			$xmayor="25";
			$descuento_mayorista = 0.75;
		}elseif ( has_term( '40/26', 'product_tag', $product->get_id() ) ){
			$detalle="40";
			$xmayor="26";
			$descuento_mayorista = 0.74;
		}elseif ( has_term( '40/27', 'product_tag', $product->get_id() ) ){
			$detalle="40";
			$xmayor="27";
			$descuento_mayorista = 0.73;
		}elseif ( has_term( '60/20', 'product_tag', $product->get_id() ) ){
			$detalle="60";
			$xmayor="20";
			$descuento_mayorista = 0.8;
		}elseif ( has_term( '60/30', 'product_tag', $product->get_id() ) ){
			$detalle="60";
			$xmayor="30";
			$descuento_mayorista = 0.7;
		}elseif ( has_term( '50/15', 'product_tag', $product->get_id() ) ){
			$detalle="50";
			$xmayor="15";
			$descuento_mayorista = 0.85;
		}elseif ( has_term( '50/10', 'product_tag', $product->get_id() ) ){
			$detalle="50";
			$xmayor="10";
			$descuento_mayorista = 0.9;
		}elseif ( has_term( '25/25', 'product_tag', $product->get_id() ) ){
			$detalle="25";
			$xmayor="25";
			$descuento_mayorista = 0.75;
		}elseif ( has_term( '25/5', 'product_tag', $product->get_id() ) ){
			$detalle="25";
			$xmayor="5";
			$descuento_mayorista = 0.95;            
		}elseif ( has_term( '50/10', 'product_tag', $product->get_id() ) ){
			$detalle="50";
			$xmayor="10";
			$descuento_mayorista = 0.9;
		}elseif ( has_term( '45/20', 'product_tag', $product->get_id() ) ){
			$detalle="45";
			$xmayor="20";
			$descuento_mayorista = 0.8;
		}elseif ( has_term( '50/20', 'product_tag', $product->get_id() ) ){
			$detalle="50";
			$xmayor="20";
			$descuento_mayorista = 0.8;
		}elseif ( has_term( '50/25', 'product_tag', $product->get_id() ) ){
			$detalle="50";
			$xmayor="25";
			$descuento_mayorista = 0.75;
		}elseif ( has_term( '55/35', 'product_tag', $product->get_id() ) ){
			$detalle="55";
			$xmayor="35";
			$descuento_mayorista = 0.65;
		}elseif ( has_term( '55/40', 'product_tag', $product->get_id() ) ){
			$detalle="55";
			$xmayor="40";
			$descuento_mayorista = 0.6;
		}elseif ( has_term( '60/35', 'product_tag', $product->get_id() ) ){
			$detalle="60";
			$xmayor="35";
			$descuento_mayorista = 0.65;
 		}elseif ( has_term( '60/40', 'product_tag', $product->get_id() ) ){
			$detalle="60";
			$xmayor="40";
			$descuento_mayorista = 0.6;
		}else{
			$descuento_mayorista = 0.75;
		}

    if ( $product->is_type('variable') ){
		 $variation_min_reg_price = $product->get_variation_regular_price('min', true);
   		 $variation_min_sale_price = $product->get_variation_sale_price('min', true);
		$variation_wholesale_price = get_post_meta( get_field('wholesale_customer_variations_with_wholesale_price'), 'wholesale_customer_wholesale_price', true );

		if ($descuento_mayorista == 1){
		    $price_html = $nuevo_html.'<span class="titulo-precios_detalle">Al Detalle &nbsp;</span><span class="precio-precios_detalle">$'.number_format($variation_min_sale_price,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$detalle.'%</span><br><span class="titulo-precios_detalle_antes">Antes&nbsp;</span><span class="precio-precios_detalle_antes"><del>$'.number_format($variation_min_reg_price,0,',','.').'</del></span><br><span class="titulo-precios_mayor">Por Mayor &nbsp;</span><span class="precio-precios_mayor">$'.number_format($variation_wholesale_price*$descuento_mayorista,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$xmayor.'%</span><br><span class="titulo-precios_mayor_antes">Antes&nbsp;</span><span class="precio-precios_mayor_antes"><del> $'.number_format($variation_wholesale_price,0,',','.').'</del></span><br>';
		}else{
		    $price_html = $nuevo_html.'<span class="titulo-precios_detalle">Al Detalle &nbsp;</span><span class="precio-precios_detalle">$'.number_format($variation_min_sale_price,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$detalle.'%</span><br><span class="titulo-precios_detalle_antes">Antes&nbsp;</span><span class="precio-precios_detalle_antes"><del> $'.number_format($variation_min_reg_price,0,',','.').'</del></span><br><span class="titulo-precios_mayor">Por Mayor &nbsp;</span><span class="precio-precios_mayor">$'.number_format($variation_wholesale_price*$descuento_mayorista,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$xmayor.'%</span><br><span class="titulo-precios_mayor_antes">Antes&nbsp;</span><span class="precio-precios_mayor_antes"><del> $'.number_format($variation_wholesale_price,0,',','.').'</del></span><br>';
        }
    }
    elseif ( $product->is_type('simple') ){
        $price = $product->get_sale_price(); // Float number
		$price_html = $nuevo_html.'<span class="titulo-precios_detalle">Al Detalle &nbsp;</span><span class="precio-precios_detalle">$'.number_format($price,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$detalle.'%</span><br><span class="titulo-precios_detalle_antes">Antes&nbsp;</span><span class="precio-precios_detalle_antes"><del> $'.number_format(get_field('_regular_price'),0,',','.').'</del></span><br><span class="titulo-precios_mayor">Por Mayor &nbsp;</span><span class="precio-precios_mayor">$'.number_format(get_field('wholesale_customer_wholesale_price')*$descuento_mayorista,0,',','.').'&nbsp;</span><span class="caja_porc_descuento">-'.$xmayor.'%</span><br><span class="titulo-precios_mayor_antes">Antes&nbsp;</span><span class="precio-precios_mayor_antes"><del> $'.number_format(get_field('wholesale_customer_wholesale_price'),0,',','.').'</del></span><br>';
    }
    }else{
    if ( $product->is_type('variable') ){
		 $variation_min_reg_price = $product->get_variation_regular_price('min', true);
   		 $variation_min_sale_price = $product->get_variation_sale_price('min', true);
		 $variation_wholesale_price = get_post_meta( get_field('wholesale_customer_variations_with_wholesale_price'), 'wholesale_customer_wholesale_price', true );
		 /*$price_html = '<span class="titulo-precios">Al Detalle &nbsp;</span><span class="precio-detalle-single">'. wc_price($variation_min_sale_price). '&nbsp;</span><br><span class="titulo-precios">Por Mayor &nbsp;</span><span class="precio-detalle-single">'.wc_price(get_field('mayorista_tienda')).'&nbsp;</span><br>';*/

		$price_html = $nuevo_html.'<span class="titulo-precios_detalle">Al Detalle &nbsp;</span><span class="precio-precios_detalle">$'.number_format(get_field('_regular_price'),0,',','.').'&nbsp;</span><br><span class="titulo-precios_mayor">Por Mayor &nbsp;</span><span class="precio-precios_mayor">$'.number_format(get_field('wholesale_customer_wholesale_price'),0,',','.').'&nbsp;</span><br>';

		/*	'<span class="titulo-precios">Al Detalle &nbsp;</span><span class="precio-detalle-single">'. wc_price($variation_min_sale_price). '&nbsp;</span><br><span class="titulo-precios">Por Mayor &nbsp;</span><span class="precio-detalle-single">'.wc_price($variation_wholesale_price).'&nbsp;</span><br>';*/
    }else{
		$price_html = '<span class="titulo-precios_detalle">Al Detalle &nbsp;</span><span class="precio-precios_detalle">$'.number_format(get_field('_regular_price'),0,',','.').'&nbsp;</span><br><span class="titulo-precios_mayor">Por Mayor &nbsp;</span><span class="precio-precios_mayor">$'.number_format(get_field('wholesale_customer_wholesale_price'),0,',','.').'&nbsp;</span><br>';

    }
	}

	return $price_html;
}
////////////////////////////////////////////////END DISPLAY DE PRECIOS EN EL CATALOGO//////////////////////////////

function QuantityBasedPricing( $cart ) {
    // Prevenir ejecución múltiple


    // Obtener cantidad total de productos en el carrito
    
    // VALIDACIÓN CRÍTICA: Solo aplicar precios mayoristas si hay 5 o más productos

    
    // Si llegamos aquí: HAY 5+ PRODUCTOS - APLICAR PRECIOS MAYORISTAS
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
    	$cart_items = WC()->cart->get_cart_contents_count();
		//echo 'items..:'.$cart_items;

		if ($cart_items < 5) {
			$price = get_field('_regular_price', $product->get_id());
	        $cart_item['data']->set_price( $price );
			//echo $price;
			
		} else {
	        $price = get_field('wholesale_customer_wholesale_price', $product->get_id());
			//echo $price;

        
        // Si no hay precio mayorista configurado, saltar este producto
        if (empty($price)) {
            continue;
        }
        
        // Si el producto está en OFERTA, aplicar descuento adicional según tag
        if( $product->is_on_sale() ) {
            // Determinar descuento mayorista según tag
            $descuento_mayorista = 1; // Por defecto 15% descuento
            
            if ( has_term( '30/10', 'product_tag', $product->get_id() ) ) {
                $descuento_mayorista = 0.9;
            }elseif ( has_term( '30/15', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.85;
            }elseif ( has_term( '35/15', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.85;
            }elseif ( has_term( '35/20', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.8;
            }elseif ( has_term( '40/15', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.85;
            }elseif ( has_term( '40/20', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.8;
            }elseif ( has_term( '40/25', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.75;
            }elseif ( has_term( '40/26', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.74;
            }elseif ( has_term( '60/20', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.8;
            }elseif ( has_term( '60/30', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.7;
            }elseif ( has_term( '50/15', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.85;
            }elseif ( has_term( '50/10', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.9;
            }elseif ( has_term( '25/25', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.75;
            }elseif ( has_term( '25/5', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.95;
            }elseif ( has_term( '45/20', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.8;
            }elseif ( has_term( '50/20', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.8;
            }elseif ( has_term( '50/25', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.75;
            }elseif ( has_term( '55/35', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.65;
            }elseif ( has_term( '55/40', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.6;
            }elseif ( has_term( '60/35', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.65;
            }elseif ( has_term( '60/40', 'product_tag', $product->get_id() ) ){
                $descuento_mayorista = 0.6;
            }
            
            // Aplicar descuento adicional al precio mayorista
            $price = $price * $descuento_mayorista;
        }
		}        
        // Establecer el precio final
        $cart_item['data']->set_price( $price );			
        // 
    }
}
add_filter('woocommerce_before_calculate_totals','QuantityBasedPricing');

add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_sold_out_loop_woocommerce' );
 
function bbloomer_display_sold_out_loop_woocommerce() {
    global $product;
    if ( has_term( 'nuevo', 'product_tag', $product->get_id() ) ) {
        echo '<span class="badge nuevo-label nuevo-variable onsale" style="background-color: #CF2E2E !important;">Nuevoq</span>';
    }
} 


add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_badge_loop_woocommerce' );
 
function bbloomer_display_badge_loop_woocommerce() {
    global $product;
    if ( has_term( 'nuevo', 'product_tag', $product->get_id() ) ) {
        echo '<span class="badge nuevo-label nuevo-variable onsale" style="background-color: #CF2E2E !important;">Nuevo</span>';
    }
} 

add_action( 'woocommerce_before_single_product_summary', 'bbloomer_display_badge_single_woocommerce' );
 
function bbloomer_display_badge_single_woocommerce() {
    global $product;
}

function remove_product_editor() {
  remove_post_type_support( 'product', 'editor' );
}
add_action( 'init', 'remove_product_editor' );

/**
 * This code will automatically remove any out of stock items from a shopping cart.
 * This would be in cases when users add products to their cart and come back to it later.
*
*/
function orb_check_for_out_of_stock_products() {
if ( WC()->cart->is_empty() ) {
    return;
}

$removed_products = [];

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product_obj = $cart_item['data'];

    if ( ! $product_obj->is_in_stock() ) {
        WC()->cart->remove_cart_item( $cart_item_key );
        $removed_products[] = $product_obj;
    }
}

if (!empty($removed_products)) {
    wc_clear_notices(); // remove any WC notice about sorry about out of stock products to be removed from cart.

    foreach ( $removed_products as $idx => $product_obj ) {
        $product_name = $product_obj->get_title();
        $msg = sprintf( __( "El producto '%s' se ha agotado, no es posible incluirlo en el pedido. Sentimos mucho que no lo puedas tener por ahora.", 'woocommerce' ), $product_name);

        wc_add_notice( $msg, 'error' );
    }
}

}
add_action('woocommerce_before_cart', 'orb_check_for_out_of_stock_products');

/**
 * @snippet       Save & Show Product Stock History
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */
 
add_action( 'woocommerce_product_before_set_stock', 'bbloomer_historical_stock_product_parent' );
add_action( 'woocommerce_variation_before_set_stock', 'bbloomer_historical_stock_product_parent' );
 
function bbloomer_historical_stock_product_parent( $product ) {
   $stock_history = get_post_meta( $product->get_id(), '_stock_history', true ) ? get_post_meta( $product->get_id(), '_stock_history', true ) : array();
   $stock_history[time()] = (int)get_post_meta( $product->get_id(), '_stock', true );
   update_post_meta( $product->get_id(), '_stock_history', $stock_history );
}
 
add_action( 'add_meta_boxes', 'bbloomer_product_meta_box' );
 
function bbloomer_product_meta_box() {
    add_meta_box( 'stock_history', 'Stock History', 'bbloomer_display_stock_history', 'product', 'advanced', 'high' );
}
 
function bbloomer_display_stock_history() {
   global $post;
   $product = wc_get_product( $post->ID );
 
   if ( $product->get_type() == 'variable' ) {
        foreach ( $product->get_available_variations() as $key ) {
            $products[] = $key['variation_id'];
      }
   } else $products[] = $post->ID;
    
   foreach ( $products as $product_id ) {
      $product = wc_get_product( $product_id );
      echo '<h3>' . $product->get_name() . '</h3>';
      $stock_history = get_post_meta( $product_id, '_stock_history', true );
      if ( $stock_history ) {
         foreach ( $stock_history as $timestamp => $stockvalue ) {
            if ( ! $stockvalue ) continue;
            echo '<p>' . date( DATE_COOKIE, $timestamp ) . ': <b>' . $stockvalue . '</b></p>';
         }
      }; 
      echo '<p>Current Stock: <b>' . $product->get_stock_quantity() . '</b></p>';   
   }
    
}

/*******************************************
 * SISTEMA DE REGIONES Y COMUNAS DE CHILE 
 * Personalizar campos de checkout para Chile - Regiones y Comunas
 *******************************************/

// 1. Definir todas las comunas por región de Chile (con códigos exactos de WooCommerce)
function get_chile_states_cities() {
    return array(
        // R15: Región de Arica y Parinacota
        'R15' => array(
            'arica' => 'Arica',
            'camarones' => 'Camarones',
            'general-lagos' => 'General Lagos',
            'putre' => 'Putre'
        ),
        
        // R1: Región de Tarapacá
        'R1' => array(
            'iquique' => 'Iquique',
            'alto-hospicio' => 'Alto Hospicio',
            'camiña' => 'Camiña',
            'colchane' => 'Colchane',
            'huara' => 'Huara',
            'pica' => 'Pica',
            'pozo-almonte' => 'Pozo Almonte'
        ),
        
        // R2: Región de Antofagasta
        'CL-R2' => array(
            'antofagasta' => 'Antofagasta',
            'calama' => 'Calama',
            'tocopilla' => 'Tocopilla',
            'mejillones' => 'Mejillones',
            'taltal' => 'Taltal',
            'ollague' => 'Ollagüe',
            'san-pedro-de-atacama' => 'San Pedro de Atacama',
            'maria-elena' => 'María Elena',
            'sierra-gorda' => 'Sierra Gorda'
        ),
        
        // R3: Región de Atacama
        'R3' => array(
            'copiapo' => 'Copiapó',
            'caldera' => 'Caldera',
            'tierra-amarilla' => 'Tierra Amarilla',
            'chanaral' => 'Chañaral',
            'diego-de-almagro' => 'Diego de Almagro',
            'vallenar' => 'Vallenar',
            'alto-del-carmen' => 'Alto del Carmen',
            'freirina' => 'Freirina',
            'huasco' => 'Huasco'
        ),
        
        // R4: Región de Coquimbo
        'R4' => array(
            'la-serena' => 'La Serena',
            'coquimbo' => 'Coquimbo',
            'ovalle' => 'Ovalle',
            'illapel' => 'Illapel',
            'andacollo' => 'Andacollo',
            'la-higuera' => 'La Higuera',
            'paiguano' => 'Paiguano',
            'vicuna' => 'Vicuña',
            'combarbala' => 'Combarbalá',
            'monte-patria' => 'Monte Patria',
            'punitaqui' => 'Punitaqui',
            'rio-hurtado' => 'Río Hurtado',
            'canela' => 'Canela',
            'los-vilos' => 'Los Vilos',
            'mincha' => 'Mincha',
            'salamanca' => 'Salamanca'
        ),
        
        // R5: Región de Valparaíso
        'R5' => array(
            'valparaiso' => 'Valparaíso',
            'vina-del-mar' => 'Viña del Mar',
            'quilpue' => 'Quilpué',
            'villa-alemana' => 'Villa Alemana',
            'casablanca' => 'Casablanca',
            'concon' => 'Concón',
            'juan-fernandez' => 'Juan Fernández',
            'puchuncavi' => 'Puchuncaví',
            'quintero' => 'Quintero',
            'san-antonio' => 'San Antonio',
            'algarrobo' => 'Algarrobo',
            'cartagena' => 'Cartagena',
            'el-quisco' => 'El Quisco',
            'el-tabo' => 'El Tabo',
            'santo-domingo' => 'Santo Domingo',
            'quillota' => 'Quillota',
            'calera' => 'Calera',
            'hijuelas' => 'Hijuelas',
            'la-cruz' => 'La Cruz',
            'limache' => 'Limache',
            'nogales' => 'Nogales',
            'olmue' => 'Olmué',
            'san-felipe' => 'San Felipe',
            'catemu' => 'Catemu',
            'llaillay' => 'Llaillay',
            'panquehue' => 'Panquehue',
            'putaendo' => 'Putaendo',
            'santa-maria' => 'Santa María',
            'los-andes' => 'Los Andes',
            'calle-larga' => 'Calle Larga',
            'rinconada' => 'Rinconada',
            'san-esteban' => 'San Esteban',
            'la-ligua' => 'La Ligua',
            'cabildo' => 'Cabildo',
            'papudo' => 'Papudo',
            'petorca' => 'Petorca',
            'zapallar' => 'Zapallar',
            'isla-de-pascua' => 'Isla de Pascua'
        ),
        
        // RM: Región Metropolitana
        'RM' => array(
            'santiago' => 'Santiago',
            'cerrillos' => 'Cerrillos',
            'cerro-navia' => 'Cerro Navia',
            'conchali' => 'Conchalí',
            'el-bosque' => 'El Bosque',
            'estacion-central' => 'Estación Central',
            'huechuraba' => 'Huechuraba',
            'independencia' => 'Independencia',
            'la-cisterna' => 'La Cisterna',
            'la-florida' => 'La Florida',
            'la-granja' => 'La Granja',
            'la-pintana' => 'La Pintana',
            'la-reina' => 'La Reina',
            'las-condes' => 'Las Condes',
            'lo-barnechea' => 'Lo Barnechea',
            'lo-espejo' => 'Lo Espejo',
            'lo-prado' => 'Lo Prado',
            'macul' => 'Macul',
            'maipu' => 'Maipú',
            'nunoa' => 'Ñuñoa',
            'pedro-aguirre-cerda' => 'Pedro Aguirre Cerda',
            'penalolen' => 'Peñalolén',
            'providencia' => 'Providencia',
            'pudahuel' => 'Pudahuel',
            'quilicura' => 'Quilicura',
            'quinta-normal' => 'Quinta Normal',
            'recoleta' => 'Recoleta',
            'renca' => 'Renca',
            'san-joaquin' => 'San Joaquín',
            'san-miguel' => 'San Miguel',
            'san-ramon' => 'San Ramón',
            'vitacura' => 'Vitacura',
            'puente-alto' => 'Puente Alto',
            'pirque' => 'Pirque',
            'san-jose-de-maipo' => 'San José de Maipo',
            'colina' => 'Colina',
            'lampa' => 'Lampa',
            'tiltil' => 'Tiltil',
            'san-bernardo' => 'San Bernardo',
            'buin' => 'Buin',
            'calera-de-tango' => 'Calera de Tango',
            'paine' => 'Paine',
            'melipilla' => 'Melipilla',
            'alhue' => 'Alhué',
            'curacavi' => 'Curacaví',
            'maria-pinto' => 'María Pinto',
            'san-pedro' => 'San Pedro',
            'talagante' => 'Talagante',
            'el-monte' => 'El Monte',
            'isla-de-maipo' => 'Isla de Maipo',
            'padre-hurtado' => 'Padre Hurtado',
            'penaflor' => 'Peñaflor'
        ),
        
        // R6: Región del Libertador Bernardo O'Higgins
        'R6' => array(
            'rancagua' => 'Rancagua',
            'codegua' => 'Codegua',
            'coinco' => 'Coinco',
            'coltauco' => 'Coltauco',
            'donihue' => 'Doñihue',
            'graneros' => 'Graneros',
            'las-cabras' => 'Las Cabras',
            'machali' => 'Machalí',
            'malloa' => 'Malloa',
            'mostazal' => 'Mostazal',
            'olivar' => 'Olivar',
            'peumo' => 'Peumo',
            'pichidegua' => 'Pichidegua',
            'quinta-de-tilcoco' => 'Quinta de Tilcoco',
            'rengo' => 'Rengo',
            'requinoa' => 'Requínoa',
            'san-vicente-de-tagua-tagua' => 'San Vicente de Tagua Tagua',
            'pichilemu' => 'Pichilemu',
            'la-estrella' => 'La Estrella',
            'litueche' => 'Litueche',
            'marchihue' => 'Marchigüe',
            'navidad' => 'Navidad',
            'paredones' => 'Paredones',
            'san-fernando' => 'San Fernando',
            'chepica' => 'Chépica',
            'chimbarongo' => 'Chimbarongo',
            'lolol' => 'Lolol',
            'nancagua' => 'Nancagua',
            'palmilla' => 'Palmilla',
            'peralillo' => 'Peralillo',
            'placilla' => 'Placilla',
            'pumanque' => 'Pumanque',
            'santa-cruz' => 'Santa Cruz'
        ),
        
        // R7: Región del Maule
        'R7' => array(
            'talca' => 'Talca',
            'constitucion' => 'Constitución',
            'curepto' => 'Curepto',
            'empedrado' => 'Empedrado',
            'maule' => 'Maule',
            'pelarco' => 'Pelarco',
            'pencahue' => 'Pencahue',
            'rio-claro' => 'Río Claro',
            'san-clemente' => 'San Clemente',
            'san-rafael' => 'San Rafael',
            'cauquenes' => 'Cauquenes',
            'chanco' => 'Chanco',
            'pelluhue' => 'Pelluhue',
            'curico' => 'Curicó',
            'hualane' => 'Hualañé',
            'licanten' => 'Licantén',
            'molina' => 'Molina',
            'rauco' => 'Rauco',
            'romeral' => 'Romeral',
            'sagrada-familia' => 'Sagrada Familia',
            'teno' => 'Teno',
            'vichuquen' => 'Vichuquén',
            'linares' => 'Linares',
            'colbun' => 'Colbún',
            'longavi' => 'Longaví',
            'parral' => 'Parral',
            'retiro' => 'Retiro',
            'san-javier' => 'San Javier',
            'villa-alegre' => 'Villa Alegre',
            'yerbas-buenas' => 'Yerbas Buenas'
        ),
        
        // R16: Región de Ñuble
        'R16' => array(
            'chillan' => 'Chillán',
            'bulnes' => 'Bulnes',
            'cobquecura' => 'Cobquecura',
            'coelemu' => 'Coelemu',
            'coihueco' => 'Coihueco',
            'chillan-viejo' => 'Chillán Viejo',
            'el-carmen' => 'El Carmen',
            'ninhue' => 'Ñinhue',
            'pemuco' => 'Pemuco',
            'pinto' => 'Pinto',
            'portezuelo' => 'Portezuelo',
            'quillon' => 'Quillón',
            'quirihue' => 'Quirihue',
            'ranquil' => 'Ránquil',
            'san-carlos' => 'San Carlos',
            'san-fabian' => 'San Fabián',
            'san-ignacio' => 'San Ignacio',
            'san-nicolas' => 'San Nicolás',
            'treguaco' => 'Trehuaco',
            'yungay' => 'Yungay'
        ),
        
        // R8: Región del Biobío
        'R8' => array(
            'concepcion' => 'Concepción',
            'coronel' => 'Coronel',
            'chiguayante' => 'Chiguayante',
            'florida' => 'Florida',
            'hualqui' => 'Hualqui',
            'lota' => 'Lota',
            'penco' => 'Penco',
            'san-pedro-de-la-paz' => 'San Pedro de la Paz',
            'santa-juana' => 'Santa Juana',
            'talcahuano' => 'Talcahuano',
            'tome' => 'Tomé',
            'hualpen' => 'Hualpén',
            'lebu' => 'Lebu',
            'arauco' => 'Arauco',
            'canete' => 'Cañete',
            'contulmo' => 'Contulmo',
            'curanilahue' => 'Curanilahue',
            'los-alamos' => 'Los Álamos',
            'tirua' => 'Tirúa',
            'los-angeles' => 'Los Ángeles',
            'antuco' => 'Antuco',
            'cabrero' => 'Cabrero',
            'laja' => 'Laja',
            'mulchen' => 'Mulchén',
            'nacimiento' => 'Nacimiento',
            'negrete' => 'Negrete',
            'quilaco' => 'Quilaco',
            'quilleco' => 'Quilleco',
            'san-rosendo' => 'San Rosendo',
            'santa-barbara' => 'Santa Bárbara',
            'tucapel' => 'Tucapel',
            'yumbel' => 'Yumbel'
        ),
        
        // R9: Región de La Araucanía
        'R9' => array(
            'temuco' => 'Temuco',
            'carahue' => 'Carahue',
            'cunco' => 'Cunco',
            'curarrehue' => 'Curarrehue',
            'freire' => 'Freire',
            'galvarino' => 'Galvarino',
            'gorbea' => 'Gorbea',
            'lautaro' => 'Lautaro',
            'loncoche' => 'Loncoche',
            'melipeuco' => 'Melipeuco',
            'nueva-imperial' => 'Nueva Imperial',
            'padre-las-casas' => 'Padre Las Casas',
            'perquenco' => 'Perquenco',
            'pitrufquen' => 'Pitrufquén',
            'pucon' => 'Pucón',
            'saavedra' => 'Saavedra',
            'teodoro-schmidt' => 'Teodoro Schmidt',
            'tolten' => 'Toltén',
            'vilcun' => 'Vilcún',
            'villarrica' => 'Villarrica',
            'cholchol' => 'Cholchol',
            'angol' => 'Angol',
            'collipulli' => 'Collipulli',
            'curacautin' => 'Curacautín',
            'ercilla' => 'Ercilla',
            'lonquimay' => 'Lonquimay',
            'los-sauces' => 'Los Sauces',
            'lumaco' => 'Lumaco',
            'puren' => 'Purén',
            'renaico' => 'Renaico',
            'traiguen' => 'Traiguén',
            'victoria' => 'Victoria'
        ),
        
        // R14: Región de Los Ríos
        'R14' => array(
            'valdivia' => 'Valdivia',
            'corral' => 'Corral',
            'lanco' => 'Lanco',
            'los-lagos' => 'Los Lagos',
            'mafil' => 'Máfil',
            'mariquina' => 'Mariquina',
            'paillaco' => 'Paillaco',
            'panguipulli' => 'Panguipulli',
            'la-union' => 'La Unión',
            'futrono' => 'Futrono',
            'lago-ranco' => 'Lago Ranco',
            'rio-bueno' => 'Río Bueno'
        ),
        
        // R10: Región de Los Lagos
        'R10' => array(
            'puerto-montt' => 'Puerto Montt',
            'calbuco' => 'Calbuco',
            'cochamo' => 'Cochamó',
            'fresia' => 'Fresia',
            'frutillar' => 'Frutillar',
            'los-muermos' => 'Los Muermos',
            'llanquihue' => 'Llanquihue',
            'maulla' => 'Maullín',
            'puerto-varas' => 'Puerto Varas',
            'castro' => 'Castro',
            'ancud' => 'Ancud',
            'chonchi' => 'Chonchi',
            'curaco-de-velez' => 'Curaco de Vélez',
            'dalcahue' => 'Dalcahue',
            'puqueldon' => 'Puqueldón',
            'queilen' => 'Queilén',
            'quellon' => 'Quellón',
            'quinchao' => 'Quinchao',
            'osorno' => 'Osorno',
            'puerto-octay' => 'Puerto Octay',
            'purranque' => 'Purranque',
            'puyehue' => 'Puyehue',
            'rio-negro' => 'Río Negro',
            'san-juan-de-la-costa' => 'San Juan de la Costa',
            'san-pablo' => 'San Pablo',
            'chaiten' => 'Chaitén',
            'futaleufu' => 'Futaleufú',
            'hualaihue' => 'Hualaihué',
            'palena' => 'Palena'
        ),
        
        // R11: Región Aysén del General Carlos Ibáñez del Campo
        'R11' => array(
            'coyhaique' => 'Coyhaique',
            'lago-verde' => 'Lago Verde',
            'aysen' => 'Aysén',
            'cisnes' => 'Cisnes',
            'guaitecas' => 'Guaitecas',
            'cochrane' => 'Cochrane',
            'ohiggins' => 'O\'Higgins',
            'tortel' => 'Tortel',
            'chile-chico' => 'Chile Chico',
            'rio-ibanez' => 'Río Ibáñez'
        ),
        
        // R12: Región de Magallanes y de la Antártica Chilena
        'R12' => array(
            'punta-arenas' => 'Punta Arenas',
            'laguna-blanca' => 'Laguna Blanca',
            'rio-verde' => 'Río Verde',
            'san-gregorio' => 'San Gregorio',
            'cabo-de-hornos' => 'Cabo de Hornos',
            'antartica' => 'Antártica',
            'porvenir' => 'Porvenir',
            'primavera' => 'Primavera',
            'timaukel' => 'Timaukel',
            'natales' => 'Natales',
            'torres-del-paine' => 'Torres del Paine'
        )
    );
}

// 2. Modifica los campos de checkout para eliminar la función conflictiva
add_filter( 'woocommerce_checkout_fields' , 'override_billing_checkout_fields_with_cities', 50, 1 );
function override_billing_checkout_fields_with_cities( $fields ) {
    // Modificar el campo de email de envío
    $fields['shipping']['shipping_email']['placeholder'] = 'Email';
    $fields['shipping']['shipping_email']['label'] = 'Email';
    
    // Configurar campos de ciudad como select - FACTURACIÓN
    $fields['billing']['billing_city']['label'] = 'Comuna'; // AGREGAR LABEL
    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = array('' => 'Selecciona una comuna...');
    $fields['billing']['billing_city']['class'] = array('form-row-wide', 'update_totals_on_change', 'address-field');
    
    // Configurar campos de ciudad como select - ENVÍO
    $fields['shipping']['shipping_city']['label'] = 'Comuna'; // AGREGAR LABEL
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = array('' => 'Selecciona una comuna...');
    $fields['shipping']['shipping_city']['class'] = array('form-row-wide', 'update_totals_on_change', 'address-field');
    
    return $fields;
}


// 4. Validar que la ciudad seleccionada sea válida
add_action( 'woocommerce_checkout_process', 'validate_chile_city' );
function validate_chile_city() {
    $cities = get_chile_states_cities();
    
    // Validar ciudad de facturación
    if ( ! empty( $_POST['billing_state'] ) && ! empty( $_POST['billing_city'] ) ) {
        $state = sanitize_text_field( $_POST['billing_state'] );
        $city = sanitize_text_field( $_POST['billing_city'] );
        
        if ( isset( $cities[$state] ) && ! array_key_exists( $city, $cities[$state] ) ) {
            wc_add_notice( __( 'Por favor selecciona una comuna válida para la facturación.' ), 'error' );
        }
    }
    
    // Validar ciudad de envío si es diferente a facturación
    if ( ! empty( $_POST['ship_to_different_address'] ) ) {
        if ( ! empty( $_POST['shipping_state'] ) && ! empty( $_POST['shipping_city'] ) ) {
            $state = sanitize_text_field( $_POST['shipping_state'] );
            $city = sanitize_text_field( $_POST['shipping_city'] );
            
            if ( isset( $cities[$state] ) && ! array_key_exists( $city, $cities[$state] ) ) {
                wc_add_notice( __( 'Por favor selecciona una comuna válida para el envío.' ), 'error' );
            }
        }
    }
}

// 5. Mostrar nombre completo de la ciudad en lugar del slug
add_filter( 'woocommerce_order_formatted_billing_address', 'format_billing_address_city', 10, 2 );
add_filter( 'woocommerce_order_formatted_shipping_address', 'format_shipping_address_city', 10, 2 );
add_filter( 'woocommerce_formatted_address_replacements', 'format_address_replacements', 10, 2 );

function format_billing_address_city( $address, $order ) {
    return format_address_city_display( $address );
}

function format_shipping_address_city( $address, $order ) {
    return format_address_city_display( $address );
}

function format_address_replacements( $replacements, $args ) {
    if ( ! empty( $args['city'] ) && ! empty( $args['state'] ) ) {
        $cities = get_chile_states_cities();
        if ( isset( $cities[$args['state']][$args['city']] ) ) {
            $replacements['{city}'] = $cities[$args['state']][$args['city']];
        }
    }
    return $replacements;
}

function format_address_city_display( $address ) {
    if ( ! empty( $address['city'] ) && ! empty( $address['state'] ) ) {
        $cities = get_chile_states_cities();
        if ( isset( $cities[$address['state']][$address['city']] ) ) {
            $address['city'] = $cities[$address['state']][$address['city']];
        }
    }
    return $address;
}

// 6. Formato de dirección para Chile
add_filter( 'woocommerce_localisation_address_formats', 'custom_address_formats_chile' );
function custom_address_formats_chile( $formats ) {
    $formats['CL'] = "{name}\n{company}\n{address_1}\n{address_2}\n{city}, {state}\n{country}";
    return $formats;
}

// 7. Personalizar etiquetas de los campos
add_filter( 'woocommerce_default_address_fields', 'customize_address_fields_labels' );
function customize_address_fields_labels( $fields ) {
    $fields['state']['label'] = __( 'Región' );
    $fields['city']['label'] = __( 'Comuna' );
    return $fields;
}

// Badge de descuento en página principal y tienda


function badge_descuento_principal() {
    global $product;
    
    if (!$product->is_on_sale()) {
        return;
    }
    
    $regular_price = (float) $product->get_regular_price();
    $sale_price = (float) $product->get_sale_price();
    
    if ($regular_price > 0 && $sale_price > 0) {
        $percentage = round((($regular_price - $sale_price) / $regular_price) * 100);
        
        echo '<div class="badge-descuento-custom">-' . $percentage . '% Detalle</div>';
    }
	if( $product->is_on_sale() ) {
		 if ( has_term( '30/10', 'product_tag', $product->get_id() ) ) {
			$descuento_mayorista = 10;
		}elseif ( has_term( '30/15', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 15;
		}elseif ( has_term( '35/15', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 15;
		}elseif ( has_term( '35/20', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 20;
		}elseif ( has_term( '40/15', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 15;
		}elseif ( has_term( '40/20', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 20;
		}elseif ( has_term( '40/25', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 25;
		}elseif ( has_term( '40/26', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 26;			 
		}elseif ( has_term( '60/20', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 20;
		}elseif ( has_term( '60/30', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 30;
		}elseif ( has_term( '50/15', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 15;
		}elseif ( has_term( '50/10', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 10;
		}elseif ( has_term( '25/5', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 5;
		}elseif ( has_term( '25/25', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 25;
		}elseif ( has_term( '50/10', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 10;
		}elseif ( has_term( '45/20', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 20;		
		}elseif ( has_term( '50/20', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 20;
		}elseif ( has_term( '50/25', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 25;
		}elseif ( has_term( '55/35', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 35;
		}elseif ( has_term( '55/40', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 40;
		}elseif ( has_term( '60/35', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 35;
		}elseif ( has_term( '60/40', 'product_tag', $product->get_id() ) ){
			$descuento_mayorista = 40;
		}
        echo '<div class="badge-descuento-customw">-' . $descuento_mayorista . '% x Mayor</div>';		
	}
}

// Estilos del badge
add_action('wp_head', 'estilos_badge_principal');
function estilos_badge_principal() {
    ?>
    <style>
        /* Asegurar que el contenedor del producto sea relativo */
        .products .product,
        li.product,
        .woocommerce ul.products li.product {
            position: relative !important;
        }
		
        /* Badge de descuento */
        .badge-descuento-custom {
            position: absolute !important;
            top: 10px !important;
            left: 10px !important;
            background: #9B51E0 !important;
            color: white !important;
            padding: 10px 12px !important;
            font-weight: bold !important;
            font-size: 12px !important;
            z-index: 999 !important;
            box-shadow: 0 3px 10px rgba(231, 76, 60, 0.5) !important;
            min-width: 55px !important;
            min-height: 20px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            line-height: 1 !important;
        }

        .badge-descuento-customw {
            position: absolute !important;
            top: 50px !important;
            left: 10px !important;
            background: #9B51E0 !important;
            color: white !important;
            padding: 10px 12px !important;
            font-weight: bold !important;
            font-size: 12px !important;
            z-index: 999 !important;
            box-shadow: 0 3px 10px rgba(231, 76, 60, 0.5) !important;
            min-width: 55px !important;
            min-height: 20px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            line-height: 1 !important;
        }		
        /* Ocultar el badge OFERTA original si quieres */
        .onsale {
            display: none !important;
        }
    </style>
    <?php
}

add_action('wp_footer', 'forzar_dos_columnas_movil_universal');
function forzar_dos_columnas_movil_universal() {
    ?>
    <style>
        @media (max-width: 800px) {
            /* Remover padding de contenedores */
            .wp-site-blocks,
            .woocommerce-page,
            .wp-block-group {
                padding-left: 0 !important;
                padding-right: 0 !important;
            }
            
            .wc-block-product-collection,
            .wp-block-woocommerce-product-collection {
                padding-left: 5px !important;
                padding-right: 5px !important;
            }
            
            /* Contenedor de productos */
            ul.wc-block-product-template,
            .wc-block-product-template {
                display: grid !important;
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 5px !important;
                width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            /* Productos individuales */
            li.wc-block-product,
            .wc-block-product {
                width: 100% !important;
                max-width: 100% !important;
                margin: 0 !important;
                padding: 5px !important;
                box-sizing: border-box !important;
            }
            
            /* Imágenes */
            .wc-block-product img {
                width: 100% !important;
                height: auto !important;
            }
        }
    </style>
    
    <script>
    (function() {
        if (window.innerWidth <= 800) {
            function aplicarDobleColumna() {
                // Remover padding de contenedores principales
                var containers = document.querySelectorAll('.wp-site-blocks, .woocommerce-page, .wp-block-group');
                containers.forEach(function(c) {
                    c.style.setProperty('padding-left', '0', 'important');
                    c.style.setProperty('padding-right', '0', 'important');
                });
                
                // Aplicar a contenedores de colección
                var collections = document.querySelectorAll('.wc-block-product-collection, .wp-block-woocommerce-product-collection');
                collections.forEach(function(c) {
                    c.style.setProperty('padding-left', '5px', 'important');
                    c.style.setProperty('padding-right', '5px', 'important');
                });
                
                // Productos template
                var productTemplates = document.querySelectorAll('ul.wc-block-product-template, .wc-block-product-template');
                productTemplates.forEach(function(template) {
                    template.style.setProperty('display', 'grid', 'important');
                    template.style.setProperty('grid-template-columns', 'repeat(2, 1fr)', 'important');
                    template.style.setProperty('gap', '5px', 'important');
                    template.style.setProperty('width', '100%', 'important');
                    template.style.setProperty('padding', '0', 'important');
                    template.style.setProperty('margin', '0', 'important');
                    
                    var products = template.querySelectorAll('li.wc-block-product, .wc-block-product');
                    products.forEach(function(product) {
                        product.style.setProperty('width', '100%', 'important');
                        product.style.setProperty('max-width', '100%', 'important');
                        product.style.setProperty('margin', '0', 'important');
                        product.style.setProperty('padding', '5px', 'important');
                        product.style.setProperty('box-sizing', 'border-box', 'important');
                    });
                });
            }
            
            aplicarDobleColumna();
            setTimeout(aplicarDobleColumna, 100);
            setTimeout(aplicarDobleColumna, 500);
            window.addEventListener('load', aplicarDobleColumna);
            
            var observer = new MutationObserver(aplicarDobleColumna);
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    })();
    </script>
    <?php
}

?>
<?php
// Crear shortcode para mostrar productos relacionados en carrusel centrado
add_shortcode('productos_relacionados_carrito', 'mostrar_productos_relacionados_carrito');

function mostrar_productos_relacionados_carrito() {
    if (!is_cart()) {
        return '';
    }
    
    $cart = WC()->cart->get_cart();
    if (empty($cart)) {
        return '';
    }
    
    $productos_relacionados = array();
    
    // Recorrer productos del carrito
    foreach ($cart as $cart_item) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);
        
        if (!$product) continue;
        
        $product_name = $product->get_name();
        
        // Extraer los 6 números del nombre
        preg_match('/^[A-Z]{2,4}(\d{6,})/', $product_name, $matches);
        
        if (!empty($matches[1])) {
            $numero_comun = $matches[1];
            
            // Buscar productos con los mismos números
            $args = array(
                'post_type' => 'product',
                'posts_per_page' => 12,
                'post_status' => 'publish',
                'post__not_in' => array($product_id),
                's' => $numero_comun,
                'meta_query' => array(
                    array(
                        'key' => '_stock_status',
                        'value' => 'instock'
                    )
                )
            );
            
            $related_query = new WP_Query($args);
            
            if ($related_query->have_posts()) {
                while ($related_query->have_posts()) {
                    $related_query->the_post();
                    $productos_relacionados[get_the_ID()] = get_the_ID();
                }
            }
            wp_reset_postdata();
        }
    }
    
    // Eliminar productos que ya están en el carrito
    foreach ($cart as $cart_item) {
        unset($productos_relacionados[$cart_item['product_id']]);
    }
    
    if (empty($productos_relacionados)) {
        return '';
    }
    
    // Generar ID único para este carrusel
    $carousel_id = 'carousel-' . uniqid();
    
    // Mostrar productos relacionados en carrusel centrado
    ob_start();
    ?>
    <style>
    /* Estilos generales del carrusel */
    .productos-relacionados-carrito-wrapper-<?php echo $carousel_id; ?> {
        position: relative;
        width: 100%;
        max-width: 1200px;
        margin: 2rem auto;
        padding: 0 20px;
    }
    
    .productos-relacionados-carousel-<?php echo $carousel_id; ?> {
        overflow-x: auto;
        scroll-behavior: smooth;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none;
        -ms-overflow-style: none;
    }
    
    .productos-relacionados-carousel-<?php echo $carousel_id; ?>::-webkit-scrollbar {
        display: none;
    }
    
    /* Reducir imágenes SOLO en este carrusel */
    .productos-relacionados-carousel-<?php echo $carousel_id; ?> .carrusel-producto-img {
        width: 100px !important;
        max-width: 100px !important;
        height: 100px !important;
        object-fit: cover !important;
        margin: 0 auto !important;
        display: block !important;
    }
    
    .productos-relacionados-carousel-<?php echo $carousel_id; ?> .carrusel-imagen-box {
        min-height: 120px;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        margin-bottom: 1rem;
    }
    
    .productos-relacionados-carousel-<?php echo $carousel_id; ?> .productos-list {
        display: flex;
        gap: 1rem;
        padding: 0;
        margin: 0;
        list-style: none;
        justify-content: flex-start;
    }
    
    .productos-relacionados-carousel-<?php echo $carousel_id; ?> .producto-item {
        flex: 0 0 auto;
        min-width: 160px;
        max-width: 180px;
        text-align: center;
        background: #fff;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        padding: 15px;
    }
    
    .carousel-buttons-<?php echo $carousel_id; ?> {
        position: absolute;
        right: 20px;
        top: 0;
        display: flex;
        gap: 8px;
    }
    
    .carousel-btn-<?php echo $carousel_id; ?> {
        background: transparent;
        border: 1px solid #ddd;
        padding: 8px 12px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s;
    }
    
    .carousel-btn-<?php echo $carousel_id; ?>:hover {
        background: #f5f5f5;
    }
    
    /* Responsive */
    @media (max-width: 768px) {
        .productos-relacionados-carrito-wrapper-<?php echo $carousel_id; ?> {
            padding: 0 10px;
        }
        
        .carousel-buttons-<?php echo $carousel_id; ?> {
            position: static;
            justify-content: center;
            margin-top: 10px;
        }
        
        .productos-relacionados-carousel-<?php echo $carousel_id; ?> .producto-item {
            min-width: 140px;
            max-width: 160px;
        }
    }
    </style>
    
    <div class="productos-relacionados-carrito-wrapper-<?php echo $carousel_id; ?>">
        <div style="margin-bottom: 1.5rem; position: relative;">
            <h2 style="margin: 0; text-align: center;">Productos Relacionados</h2>
            
            <div class="carousel-buttons-<?php echo $carousel_id; ?>">
                <button class="carousel-btn-<?php echo $carousel_id; ?> carousel-prev-<?php echo $carousel_id; ?>" aria-label="Anterior">
                    <svg xmlns="http://www.w3.org/2000/svg" width="8" height="12" fill="none">
                        <path fill="currentColor" fill-rule="evenodd" d="M6.445 12.005.986 6 6.445-.005l1.11 1.01L3.014 6l4.54 4.995-1.109 1.01Z" clip-rule="evenodd"></path>
                    </svg>
                </button>
                <button class="carousel-btn-<?php echo $carousel_id; ?> carousel-next-<?php echo $carousel_id; ?>" aria-label="Siguiente">
                    <svg xmlns="http://www.w3.org/2000/svg" width="8" height="12" fill="none">
                        <path fill="currentColor" fill-rule="evenodd" d="M1.555-.004 7.014 6l-5.459 6.005-1.11-1.01L4.986 6 .446 1.005l1.109-1.01Z" clip-rule="evenodd"></path>
                    </svg>
                </button>
            </div>
        </div>
        
        <div class="productos-relacionados-carousel-<?php echo $carousel_id; ?>">
            <ul class="productos-list">
                <?php
                $loop = new WP_Query(array(
                    'post_type' => 'product',
                    'posts_per_page' => 12,
                    'post__in' => array_values($productos_relacionados),
                    'orderby' => 'post__in'
                ));
                
                if ($loop->have_posts()) {
                    while ($loop->have_posts()) {
                        $loop->the_post();
                        $product = wc_get_product(get_the_ID());
                        $image = $product->get_image('woocommerce_thumbnail');
                        ?>
                        <li class="producto-item">
                            <div class="carrusel-imagen-box">
                                <a href="<?php echo get_permalink(); ?>">
                                    <?php 
                                    // Extraer la URL de la imagen y crear una versión con clase personalizada
                                    if (preg_match('/<img[^>]+src="([^"]+)"[^>]*>/i', $image, $match)) {
                                        echo '<img src="' . esc_url($match[1]) . '" alt="' . esc_attr(get_the_title()) . '" class="carrusel-producto-img">';
                                    }
                                    ?>
                                </a>
                            </div>
                            
                            <h3 style="font-size: 0.9rem; margin: 0.5rem 0; line-height: 1.3;">
                                <a href="<?php echo get_permalink(); ?>" style="text-decoration: none; color: inherit;">
                                    <?php echo get_the_title(); ?>
                                </a>
                            </h3>
                            
                            <div style="font-size: 0.85rem; margin-bottom: 1rem;">
                                <div><strong>Al Detalle:</strong> <span style="color: #e74c3c;"><?php echo wc_price($product->get_regular_price()); ?></span></div>
                                <div><strong>Por Mayor:</strong> <span style="color: #e74c3c;"><?php echo wc_price($product->get_sale_price() ? $product->get_sale_price() : $product->get_regular_price()); ?></span></div>
                            </div>
                            
                            <a href="<?php echo esc_url($product->add_to_cart_url()); ?>" 
                               class="button add_to_cart_button" 
                               data-product_id="<?php echo get_the_ID(); ?>"
                               style="display: inline-block; padding: 8px 16px; background: #2c5f5f; color: #fff; text-decoration: none; border-radius: 4px; font-size: 0.85rem;">
                                Añadir al carrito
                            </a>
                        </li>
                        <?php
                    }
                }
                wp_reset_postdata();
                ?>
            </ul>
        </div>
    </div>
    
    <script>
    (function() {
        var prevBtn = document.querySelector('.carousel-prev-<?php echo $carousel_id; ?>');
        var nextBtn = document.querySelector('.carousel-next-<?php echo $carousel_id; ?>');
        var carousel = document.querySelector('.productos-relacionados-carousel-<?php echo $carousel_id; ?>');
        
        if (prevBtn && nextBtn && carousel) {
            prevBtn.addEventListener('click', function() {
                carousel.scrollBy({left: -300, behavior: 'smooth'});
            });
            
            nextBtn.addEventListener('click', function() {
                carousel.scrollBy({left: 300, behavior: 'smooth'});
            });
        }
    })();
    </script>
    <?php
    return ob_get_clean();
}
?>

<?php
// Mostrar productos relacionados en la página del producto
add_action('woocommerce_after_single_product_summary', 'mostrar_productos_relacionados_pagina_producto', 25);

function mostrar_productos_relacionados_pagina_producto() {
    global $product;
    
    if (!$product) return;
    
    $product_name = $product->get_name();
    
    // Extraer los 6 números del nombre
    preg_match('/^[A-Z]{2,4}(\d{6,})/', $product_name, $matches);
    
    if (empty($matches[1])) {
        return; // Si no encuentra el patrón, no muestra nada
    }
    
    $numero_comun = $matches[1];
    
    // Buscar productos con los mismos números
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 12,
        'post_status' => 'publish',
        'post__not_in' => array($product->get_id()),
        's' => $numero_comun,
        'meta_query' => array(
            array(
                'key' => '_stock_status',
                'value' => 'instock'
            )
        )
    );
    
    $related_query = new WP_Query($args);
    
    if (!$related_query->have_posts()) {
        return; // No hay productos relacionados
    }
    
    ?>
    <div class="productos-relacionados-single-wrapper" style="width: 100%; max-width: 1200px; margin: 3rem auto; padding: 0 20px;">
        <div class="wp-block-group is-content-justification-space-between is-nowrap is-layout-flex" style="margin-bottom: 1.5rem; position: relative;">
            <h2 class="wp-block-heading" style="margin: 0; flex-grow: 1; text-align: center;">Productos Relacionados</h2>
            
            <div class="wc-block-next-previous-buttons is-nowrap is-layout-flex" style="position: absolute; right: 0;">
                <button class="wc-block-next-previous-buttons__button carousel-single-prev" aria-label="Anterior">
                    <svg class="wc-block-next-previous-buttons__icon wc-block-next-previous-buttons__icon--left" xmlns="http://www.w3.org/2000/svg" width="8" height="12" fill="none">
                        <path fill="currentColor" fill-rule="evenodd" d="M6.445 12.005.986 6 6.445-.005l1.11 1.01L3.014 6l4.54 4.995-1.109 1.01Z" clip-rule="evenodd"></path>
                    </svg>
                </button>
                <button class="wc-block-next-previous-buttons__button carousel-single-next" aria-label="Siguiente">
                    <svg class="wc-block-next-previous-buttons__icon wc-block-next-previous-buttons__icon--right" xmlns="http://www.w3.org/2000/svg" width="8" height="12" fill="none">
                        <path fill="currentColor" fill-rule="evenodd" d="M1.555-.004 7.014 6l-5.459 6.005-1.11-1.01L4.986 6 .446 1.005l1.109-1.01Z" clip-rule="evenodd"></path>
                    </svg>
                </button>
            </div>
        </div>
        
        <div class="productos-relacionados-single-carousel" style="overflow-x: auto; scroll-behavior: smooth; -webkit-overflow-scrolling: touch;">
            <ul class="is-product-collection-layout-carousel wc-block-product-template wp-block-woocommerce-product-template is-horizontal is-content-justification-center is-nowrap is-layout-flex" style="display: flex; gap: 1rem; padding: 0; margin: 0; list-style: none; justify-content: center;">
                <?php
                while ($related_query->have_posts()) {
                    $related_query->the_post();
                    $related_product = wc_get_product(get_the_ID());
                    ?>
                    <li class="wc-block-product product carrusel-single-producto-item" style="flex: 0 0 auto; min-width: 180px; max-width: 200px; text-align: center;">
                        <div class="wc-block-components-product-image wc-block-grid__product-image carrusel-single-imagen-container" style="display: flex; justify-content: center; align-items: center; margin-bottom: 1rem;">
                            <a href="<?php echo get_permalink(); ?>" style="display: block;">
                                <?php echo $related_product->get_image('woocommerce_thumbnail'); ?>
                            </a>
                        </div>
                        
                        <h2 class="has-text-align-center wp-block-post-title has-medium-font-size" style="line-height:1.4; margin-bottom:0.75rem;margin-top:0; font-size: 1rem;">
                            <a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
                        </h2>
                        
                        <div class="wc-block-components-product-price wc-block-grid__product-price has-text-align-center has-font-size has-small-font-size">
                            <span class="titulo-precios_detalle">Al Detalle &nbsp;</span>
                            <span class="precio-precios_detalle"><?php echo wc_price($related_product->get_regular_price()); ?>&nbsp;</span><br>
                            <span class="titulo-precios_mayor">Por Mayor &nbsp;</span>
                            <span class="precio-precios_mayor"><?php echo wc_price($related_product->get_sale_price() ? $related_product->get_sale_price() : $related_product->get_regular_price()); ?>&nbsp;</span><br>
                        </div>
                        
                        <div class="wp-block-button wc-block-components-product-button align-center">
                            <a class="wp-block-button__link wp-element-button add_to_cart_button" 
                               href="<?php echo esc_url($related_product->add_to_cart_url()); ?>" 
                               data-product_id="<?php echo get_the_ID(); ?>">
                                <span>Añadir al carrito</span>
                            </a>
                        </div>
                    </li>
                    <?php
                }
                wp_reset_postdata();
                ?>
            </ul>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('.carousel-single-prev').click(function() {
            var carousel = $(this).closest('.productos-relacionados-single-wrapper').find('.productos-relacionados-single-carousel');
            carousel.animate({scrollLeft: carousel.scrollLeft() - 400}, 300);
        });
        
        $('.carousel-single-next').click(function() {
            var carousel = $(this).closest('.productos-relacionados-single-wrapper').find('.productos-relacionados-single-carousel');
            carousel.animate({scrollLeft: carousel.scrollLeft() + 400}, 300);
        });
    });
    </script>
    
    <style>
    .productos-relacionados-single-wrapper {
        position: relative;
    }
    .productos-relacionados-single-carousel {
        scrollbar-width: none;
        -ms-overflow-style: none;
    }
    .productos-relacionados-single-carousel::-webkit-scrollbar {
        display: none;
    }
    
    /* Reducir imágenes SOLO en este carrusel de página de producto */
    .carrusel-single-producto-item .carrusel-single-imagen-container img {
        width: 100px !important;
        max-width: 100px !important;
        height: 100px !important;
        object-fit: cover !important;
        margin: 0 auto !important;
        display: block !important;
    }
    
    .carrusel-single-imagen-container {
        min-height: 120px;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
    }
    </style>
    <?php
}

function ocultar_bloque_descuentos_si_vacio($block_content, $block) {
    if ($block['blockName'] === 'woocommerce/product-collection' && 
        isset($block['attrs']['queryId']) && 
        $block['attrs']['queryId'] === 100) {
        
        // Tags específicos de descuentos
        $tags = [2845, 2873, 2918, 2920, 2968];
        
        // Obtener productos con esos tags
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1, // Obtener todos
            'post_status' => 'publish',
            'fields' => 'ids', // Solo IDs para optimizar
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_tag',
                    'field' => 'term_id',
                    'terms' => $tags,
                    'operator' => 'IN'
                )
            )
        );
        
        $product_ids = get_posts($args);
        
        // Verificar si alguno está en oferta
        $hay_ofertas = false;
        foreach ($product_ids as $product_id) {
            $product = wc_get_product($product_id);
            if ($product && $product->is_on_sale() && $product->is_in_stock()) {
                $hay_ofertas = true;
                break; // Encontramos al menos uno, no necesitamos seguir
            }
        }
        
        // Si no hay productos con descuento, ocultar todo el bloque
        if (!$hay_ofertas) {
            return '<!-- Bloque de descuentos oculto: no hay productos en oferta -->';
        }
    }
    
    return $block_content;
}
add_filter('render_block', 'ocultar_bloque_descuentos_si_vacio', 10, 2);


add_action('wp_footer', 'forzar_expansion_cupones', 999);
function forzar_expansion_cupones() {
    if (is_checkout()) {
        ?>
        <script>
        (function() {
            function mostrarCampoCupon() {
                // Buscar el botón "Añadir cupones"
                const botonCupon = document.querySelector('.wc-block-components-totals-coupon .wc-block-components-panel__button');
                
                if (botonCupon) {
                    const panel = botonCupon.closest('.wc-block-components-totals-coupon');
                    const estaExpandido = panel && panel.querySelector('[aria-expanded="true"]');
                    
                    // Si no está expandido, hacer clic
                    if (!estaExpandido) {
                        botonCupon.click();
                    }
                }
            }
            
            // Ejecutar cuando cargue el DOM
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    setTimeout(mostrarCampoCupon, 300);
                    setTimeout(mostrarCampoCupon, 800);
                    setTimeout(mostrarCampoCupon, 1500);
                });
            } else {
                setTimeout(mostrarCampoCupon, 300);
                setTimeout(mostrarCampoCupon, 800);
            }
            
            // También observar cambios en el DOM por si WooCommerce recarga
            const observer = new MutationObserver(function() {
                mostrarCampoCupon();
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        })();
        </script>
        <style>
        /* Asegurar visibilidad del formulario cuando esté expandido */
        .wc-block-components-totals-coupon .wc-block-components-panel__content {
            display: block !important;
        }
        </style>
        <?php
    }
}

// Ocultar productos del catálogo cuando quedan 2 o menos unidades
add_filter('woocommerce_product_is_visible', 'ocultar_productos_stock_minimo', 10, 2);

function ocultar_productos_stock_minimo($visible, $product_id) {
    $product = wc_get_product($product_id);
    
    if (!$product) {
        return $visible;
    }
    
    // Si el producto maneja stock
    if ($product->managing_stock()) {
        $stock = $product->get_stock_quantity();
        
        // Ocultar si quedan 2 o menos unidades
        if ($stock <= 0) {
            return false;
        }
    }
    
    return $visible;
}

// Marcar como "sin stock" en el frontend cuando quedan 2 o menos
add_filter('woocommerce_product_is_in_stock', 'marcar_sin_stock_minimo', 10, 2);

function marcar_sin_stock_minimo($is_in_stock, $product) {
    if ($product->managing_stock()) {
        $stock = $product->get_stock_quantity();
        
        if ($stock <= 0) {
            return false;
        }
    }
    
    return $is_in_stock;
}



// Cambiar "Oferta" por "BLACK" en badges de productos en oferta
/*
add_filter('woocommerce_sale_flash', 'cambiar_oferta_por_black', 10, 3);
function cambiar_oferta_por_black($html, $post, $product) {
    return str_replace('Oferta', 'BLACK', $html);
}

// También para los bloques de Gutenberg
add_filter('render_block', 'cambiar_oferta_en_bloques', 10, 2);
function cambiar_oferta_en_bloques($block_content, $block) {
    if (isset($block['blockName']) && $block['blockName'] === 'woocommerce/product-sale-badge') {
        $block_content = str_replace('Oferta', 'BLACK', $block_content);
        $block_content = str_replace('Producto rebajado', 'Producto en BLACK', $block_content);
    }
    return $block_content;
}
*/

// ============================================
// CAMPO RUT OBLIGATORIO - MODO LEGACY
// ============================================

// 1. Agregar campo RUT obligatorio al checkout
add_filter('woocommerce_checkout_fields', 'agregar_campo_rut_obligatorio', 999);
function agregar_campo_rut_obligatorio($fields) {
    $fields['billing']['billing_rut'] = array(
        'label' => 'RUT *',
        'placeholder' => 'Ej: 12.345.678-9',
        'required' => true,
        'class' => array('form-row-wide'),
        'priority' => 25,
        'type' => 'text',
        'clear' => true,
        'custom_attributes' => array(
            'pattern' => '[0-9]{1,2}\.[0-9]{3}\.[0-9]{3}-[0-9kK]{1}',
            'title' => 'Formato válido: 12.345.678-9'
        )
    );
    return $fields;
}

// 2. Validar RUT en el proceso de checkout
add_action('woocommerce_after_checkout_validation', 'validar_rut_obligatorio', 10, 2);
function validar_rut_obligatorio($data, $errors) {
    // Verificar que el campo exista y no esté vacío
    if (empty($_POST['billing_rut'])) {
        $errors->add('billing_rut', 'El campo RUT es obligatorio.');
        return;
    }
    
    $rut = sanitize_text_field($_POST['billing_rut']);
    
    // Validar formato básico (XX.XXX.XXX-X)
    if (!preg_match('/^[0-9]{1,2}\.[0-9]{3}\.[0-9]{3}-[0-9kK]{1}$/', $rut)) {
        $errors->add('billing_rut', 'El RUT debe tener el formato válido: 12.345.678-9');
        return;
    }
    
    // Validación adicional del dígito verificador (opcional pero recomendado)
    $rut_limpio = str_replace(['.', '-'], '', $rut);
    $rut_numeros = substr($rut_limpio, 0, -1);
    $dv = strtoupper(substr($rut_limpio, -1));
    
    $suma = 0;
    $multiplo = 2;
    
    for ($i = strlen($rut_numeros) - 1; $i >= 0; $i--) {
        $suma += $rut_numeros[$i] * $multiplo;
        $multiplo = $multiplo < 7 ? $multiplo + 1 : 2;
    }
    
    $resto = $suma % 11;
    $dv_calculado = 11 - $resto;
    
    if ($dv_calculado == 11) {
        $dv_calculado = '0';
    } elseif ($dv_calculado == 10) {
        $dv_calculado = 'K';
    } else {
        $dv_calculado = (string)$dv_calculado;
    }
    
    if ($dv !== $dv_calculado) {
        $errors->add('billing_rut', 'El RUT ingresado no es válido. Verifica el número y el dígito verificador.');
    }
}

// 3. Guardar el RUT en la orden
add_action('woocommerce_checkout_update_order_meta', 'guardar_rut_en_orden', 10, 1);
function guardar_rut_en_orden($order_id) {
    if (!empty($_POST['billing_rut'])) {
        $rut = sanitize_text_field($_POST['billing_rut']);
        update_post_meta($order_id, 'billing_rut', $rut);
        
        // También guardarlo como meta del pedido (para WC 3.0+)
        $order = wc_get_order($order_id);
        if ($order) {
            $order->update_meta_data('billing_rut', $rut);
            $order->save();
        }
    }
}

// 4. Mostrar RUT en el panel de administración del pedido
add_action('woocommerce_admin_order_data_after_billing_address', 'mostrar_rut_en_admin_pedido', 10, 1);
function mostrar_rut_en_admin_pedido($order) {
    $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
    $rut = get_post_meta($order_id, 'billing_rut', true);
    
    if ($rut) {
        echo '<div class="address">';
        echo '<p><strong>RUT:</strong> ' . esc_html($rut) . '</p>';
        echo '</div>';
    }
}

// 5. Agregar RUT a los emails de WooCommerce
add_filter('woocommerce_email_order_meta_fields', 'agregar_rut_a_emails_pedido', 10, 3);
function agregar_rut_a_emails_pedido($fields, $sent_to_admin, $order) {
    $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
    $rut = get_post_meta($order_id, 'billing_rut', true);
    
    if ($rut) {
        $fields['billing_rut'] = array(
            'label' => 'RUT',
            'value' => $rut
        );
    }
    
    return $fields;
}

// 6. Mostrar RUT en la página "Ver Pedido" del cliente
add_action('woocommerce_order_details_after_customer_details', 'mostrar_rut_en_detalle_pedido', 10, 1);
function mostrar_rut_en_detalle_pedido($order) {
    $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
    $rut = get_post_meta($order_id, 'billing_rut', true);
    
    if ($rut) {
        echo '<p><strong>RUT:</strong> ' . esc_html($rut) . '</p>';
    }
}

?>


