/* 
Theme Name: Hello Elementor Child
Theme URI: https://github.com/elementor/hello-theme-child/
Description: Hello Elementor Child is a child theme of Hello Elementor, created by Elementor team
Author: Elementor Team
Author URI: https://elementor.com/
Template: hello-elementor
Version: 2.0.0
Text Domain: hello-elementor-child
License: GNU General Public License v3 or later.
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Tags: flexible-header, custom-colors, custom-menu, custom-logo, editor-style, featured-images, rtl-language-support, threaded-comments, translation-ready
*/

/* Add your custom styles here */

<?php
/**
 * Cantidad mínima por producto en WooCommerce
 * - Agrega el campo "Cantidad mínima" en Producto > Inventario
 * - Ajusta el selector de cantidad (ficha, carrito clásico y carrito/checkout en bloques)
 * - Valida el carrito y bloquea el pago si no se cumple el mínimo
 */

// 1. Campo en la pestaña Inventario del producto
add_action( 'woocommerce_product_options_inventory_product_data', function() {
    woocommerce_wp_text_input( array(
        'id'                => '_vanna_min_qty',
        'label'             => 'Cantidad mínima',
        'desc_tip'          => true,
        'description'       => 'Unidades mínimas por pedido. Déjalo vacío para no aplicar mínimo.',
        'type'              => 'number',
        'custom_attributes' => array( 'min' => '1', 'step' => '1' ),
    ) );
} );

// 2. Guardar el valor del campo
add_action( 'woocommerce_admin_process_product_object', function( $product ) {
    if ( isset( $_POST['_vanna_min_qty'] ) ) {
        $min = absint( wp_unslash( $_POST['_vanna_min_qty'] ) );
        if ( $min > 1 ) {
            $product->update_meta_data( '_vanna_min_qty', $min );
        } else {
            // Si está vacío o es 1, se elimina el mínimo
            $product->delete_meta_data( '_vanna_min_qty' );
        }
    }
} );

// Helper: obtiene el mínimo (en variaciones lo toma del producto padre)
function vanna_get_min_qty( $product ) {
    if ( ! $product ) {
        return 0;
    }
    $id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();
    return absint( get_post_meta( $id, '_vanna_min_qty', true ) );
}

// 3. Selector de cantidad en la ficha y en el carrito clásico
add_filter( 'woocommerce_quantity_input_args', function( $args, $product ) {
    $min = vanna_get_min_qty( $product );
    if ( $min > 1 ) {
        $args['min_value'] = $min;
        // En la ficha del producto, arrancar el selector en el mínimo
        if ( is_product() && $args['input_value'] < $min ) {
            $args['input_value'] = $min;
        }
    }
    return $args;
}, 10, 2 );

// 4. Productos variables: aplicar el mínimo a cada variación
add_filter( 'woocommerce_available_variation', function( $data, $product, $variation ) {
    $min = vanna_get_min_qty( $variation );
    if ( $min > 1 ) {
        $data['min_qty'] = $min;
    }
    return $data;
}, 10, 3 );

// 5. Botón "Añadir al carrito" en la tienda/categorías: agregar directamente el mínimo
add_filter( 'woocommerce_loop_add_to_cart_args', function( $args, $product ) {
    $min = vanna_get_min_qty( $product );
    if ( $min > 1 ) {
        $args['quantity'] = $min;
    }
    return $args;
}, 10, 2 );

// 6. Carrito y checkout en bloques (Store API)
add_filter( 'woocommerce_store_api_product_quantity_minimum', function( $value, $product, $cart_item ) {
    $min = vanna_get_min_qty( $product );
    return $min > 1 ? $min : $value;
}, 10, 3 );

// 7. Validación final: si no cumple el mínimo, muestra error y bloquea el pago
add_action( 'woocommerce_check_cart_items', function() {
    $totales = array();

    // Suma cantidades por producto (las variaciones cuentan para el padre)
    foreach ( WC()->cart->get_cart() as $item ) {
        $id             = $item['product_id'];
        $totales[ $id ] = ( $totales[ $id ] ?? 0 ) + $item['quantity'];
    }

    foreach ( $totales as $id => $qty ) {
        $product = wc_get_product( $id );
        $min     = vanna_get_min_qty( $product );
        if ( $min > 1 && $qty < $min ) {
            wc_add_notice(
                sprintf(
                    'El producto "%s" se vende con un mínimo de %d unidades. Tienes %d en el carrito.',
                    $product->get_name(),
                    $min,
                    $qty
                ),
                'error'
            );
        }
    }
} );