<?php
/**
 * Blocksy Child Theme - Mr. Sand
 */

if ( ! function_exists( 'enqueue_styles_child_theme' ) ) {
    function enqueue_styles_child_theme() {
        wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
        wp_enqueue_style( 'child-style',
            get_stylesheet_directory_uri() . '/style.css',
            array( 'parent-style' ),
            wp_get_theme()->get('Version')
        );
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_styles_child_theme' );


// =========================================================
// ENVÍOS
// =========================================================

add_filter( 'woocommerce_package_rates', 'custom_shipping_for_selected_cities', 10, 2 );

if ( ! function_exists( 'custom_shipping_for_selected_cities' ) ) {
    function custom_shipping_for_selected_cities( $rates, $package ) {
        $destination_city  = isset( $package['destination']['city'] ) ? strtolower( trim( $package['destination']['city'] ) ) : '';
        $destination_state = isset( $package['destination']['state'] ) ? strtoupper( trim( $package['destination']['state'] ) ) : '';
        $cart_subtotal     = WC()->cart->get_subtotal();
        $new_rates = [];
        $allowed_cities = array( 'talca', 'las condes', 'ñuñoa', 'nunoa', 'providencia' );

        if ( in_array( $destination_city, $allowed_cities ) ) {
            if ( ( $destination_city === 'talca' && $destination_state === 'CL-ML' ) ||
                 ( in_array( $destination_city, array( 'las condes', 'ñuñoa', 'nunoa', 'providencia' ) ) && $destination_state === 'CL-RM' ) ) {
                if ( $cart_subtotal >= 20000 ) {
                    $new_rates['free_shipping'] = new WC_Shipping_Rate( 'free_shipping', 'Despacho a Domicilio', 0, array(), 'flat_rate' );
                } else {
                    $new_rates['flat_rate'] = new WC_Shipping_Rate( 'flat_rate', 'Despacho a Domicilio', 3000, array(), 'flat_rate' );
                }
                return $new_rates;
            }
        }

        $new_rates['contact_shipping'] = new WC_Shipping_Rate(
            'contact_shipping',
            'El envío fuera de Ñuñoa, Las Condes, Providencia y Talca se coordina de manera personalizada, te contactaremos para calcular el valor de tu envío.',
            0, array(), 'flat_rate'
        );
        return $new_rates;
    }
}

add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_label_display', 10, 2 );

if ( ! function_exists( 'custom_shipping_label_display' ) ) {
    function custom_shipping_label_display( $label, $method ) {
        if ( strpos( $method->id, 'free_shipping' ) !== false ) {
            $label = $method->get_label() . ': <span class="woocommerce-Price-amount amount"><bdi>Gratis</bdi></span>';
        }
        return $label;
    }
}


// =========================================================
// PRECIO DINÁMICO EN CARRITO
// =========================================================

add_action( 'woocommerce_before_calculate_totals', 'mrsand_dynamic_pricing_qty', 20, 1 );

if ( ! function_exists( 'mrsand_dynamic_pricing_qty' ) ) {
    function mrsand_dynamic_pricing_qty( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

        $precios_por_formato = array(
            '4kg'  => array( 250 => 2650,  100 => 2890,  20 => 3090,  1 => 4990  ),
            '8kg'  => array( 125 => 5240,   50 => 5680,  10 => 5990,  1 => 7990  ),
            '20kg' => array(  50 => 12386,  20 => 13200,  5 => 14500, 1 => 18990 ),
        );

        foreach ( $cart->get_cart() as $cart_item ) {
            $product  = $cart_item['data'];
            $cantidad = (int) $cart_item['quantity'];
            $formato  = '';

            if ( isset( $cart_item['variation'] ) ) {
                foreach ( $cart_item['variation'] as $key => $val ) {
                    if ( strpos( strtolower( $key ), 'formato' ) !== false ) {
                        $formato = strtolower( trim( $val ) );
                        break;
                    }
                }
            }

            if ( empty( $formato ) ) $formato = '8kg';
            if ( ! isset( $precios_por_formato[ $formato ] ) ) continue;

            $tabla        = $precios_por_formato[ $formato ];
            $precio_final = 0;

            foreach ( $tabla as $min_qty => $precio ) {
                if ( $cantidad >= $min_qty ) {
                    $precio_final = $precio;
                    break;
                }
            }

            if ( $precio_final > 0 ) $product->set_price( $precio_final );
        }
    }
}


// =========================================================
// JS + CSS
// =========================================================

add_action( 'wp_footer', 'mrsand_variaciones_script' );

if ( ! function_exists( 'mrsand_variaciones_script' ) ) {
    function mrsand_variaciones_script() {
        if ( ! is_product() ) return;
        ?>
        <script>
        jQuery(document).ready(function($){

            var datos = {
                '4kg':  {
                    min: '$2.650', max: '$4.990',
                    tabla: [
                        { desde:'1',   hasta:'19',  kgs:'4–76',    unidad:'$4.990',  porKg:'$1.248', top: false },
                        { desde:'20',  hasta:'99',  kgs:'80–396',  unidad:'$3.090',  porKg:'$773',   top: false },
                        { desde:'100', hasta:'249', kgs:'400–996', unidad:'$2.890',  porKg:'$723',   top: false },
                        { desde:'250', hasta:'—',   kgs:'1.000+',  unidad:'$2.650',  porKg:'$663',   top: true  }
                    ]
                },
                '8kg':  {
                    min: '$5.240', max: '$7.990',
                    tabla: [
                        { desde:'1',   hasta:'9',   kgs:'8–72',    unidad:'$7.990',  porKg:'$999',   top: false },
                        { desde:'10',  hasta:'49',  kgs:'80–392',  unidad:'$5.990',  porKg:'$749',   top: false },
                        { desde:'50',  hasta:'124', kgs:'400–992', unidad:'$5.680',  porKg:'$710',   top: false },
                        { desde:'125', hasta:'—',   kgs:'1.000+',  unidad:'$5.240',  porKg:'$655',   top: true  }
                    ]
                },
                '20kg': {
                    min: '$12.386', max: '$18.990',
                    tabla: [
                        { desde:'1',  hasta:'4',   kgs:'20–80',   unidad:'$18.990', porKg:'$950',   top: false },
                        { desde:'5',  hasta:'19',  kgs:'100–380', unidad:'$14.500', porKg:'$725',   top: false },
                        { desde:'20', hasta:'49',  kgs:'400–980', unidad:'$13.200', porKg:'$660',   top: false },
                        { desde:'50', hasta:'—',   kgs:'1.000+',  unidad:'$12.386', porKg:'$619',   top: true  }
                    ]
                }
            };

            function buildTabla(formato) {
                var d = datos[formato];
                if (!d) return '';
                var html = '<div id="mrsand-tabla">';
                html += '<table class="mrsand-t"><thead><tr>';
                html += '<th>Desde</th><th>Hasta</th><th>Kgs totales</th><th>Valor unidad</th><th>Valor por Kg</th>';
                html += '</tr></thead><tbody>';
                $.each(d.tabla, function(i, f){
                    html += '<tr' + (f.top ? ' class="mrsand-top"' : '') + '>';
                    html += '<td>'+f.desde+'</td><td>'+f.hasta+'</td><td>'+f.kgs+'</td><td>'+f.unidad+'</td><td>'+f.porKg+'</td>';
                    html += '</tr>';
                });
                html += '</tbody></table>';
                html += '<p class="mrsand-nota">Transferencia, débito, crédito, efectivo o a convenir.</p>';
                html += '</div>';
                return html;
            }

            function getFormato($select) {
                var v = ($select.val() || '').toLowerCase().replace(/\s/g, '');
                if (v === '20kg' || v.indexOf('20kg') !== -1) return '20kg';
                if (v === '4kg'  || v.indexOf('4kg')  !== -1) return '4kg';
                if (v === '8kg'  || v.indexOf('8kg')  !== -1) return '8kg';
                return null;
            }

            function actualizarPrecio(formato) {
                var d = datos[formato];
                if (!d) return;
                $('p.price, .woocommerce-variation-price').first().html(
                    '<span class="woocommerce-Price-amount">' + d.min + '</span>' +
                    ' &ndash; ' +
                    '<span class="woocommerce-Price-amount">' + d.max + '</span>'
                );
            }

            function actualizarTabla(formato) {
                $('#mrsand-tabla').remove();
                if (!formato) return;
                var $c = $('.woocommerce-product-details__short-description');
                if (!$c.length) $c = $('div.entry-summary');
                if (!$c.length) $c = $('div.summary');
                $c.append(buildTabla(formato));
            }

            function reorganizarFila() {
                var $acciones = $('.ct-cart-actions');
                var $tabla    = $('table.variations');
                if ($acciones.length && $tabla.length && !$('#mrsand-fila').length) {
                    var $fila = $('<div id="mrsand-fila"></div>');
                    $tabla.after($fila);
                    $fila.append($tabla);
                    $fila.append($acciones);
                    $('.single_variation_wrap').css({
                        position: 'absolute',
                        opacity: 0,
                        pointerEvents: 'none',
                        height: 0,
                        overflow: 'hidden'
                    });
                }
            }

            reorganizarFila();

            // Cambiar botón a "Ir al carrito" tras agregar
            $('body').on('added_to_cart', function() {
                var $btn = $('.ct-cart-actions .single_add_to_cart_button');
                $btn.text('Ir al carrito')
                    .removeClass('single_add_to_cart_button')
                    .addClass('mrsand-ir-carrito')
                    .off('click')
                    .on('click', function(e) {
                        e.preventDefault();
                        window.location.href = '<?php echo wc_get_cart_url(); ?>';
                    });
            });

            $('form.variations_form').on('change', 'select', function(){
                var $s    = $(this);
                var label = ($s.closest('tr').find('label').text() || '').toLowerCase();
                if (label.indexOf('formato') === -1) return;
                var fmt = getFormato($s);
                actualizarPrecio(fmt);
                actualizarTabla(fmt);
            });

            $('form.variations_form select').each(function(){
                var $s    = $(this);
                var label = ($s.closest('tr').find('label').text() || '').toLowerCase();
                if (label.indexOf('formato') !== -1 && $s.val()) {
                    actualizarPrecio(getFormato($s));
                    actualizarTabla(getFormato($s));
                }
            });

            $('form.variations_form').on('reset_data', function(){
                $('#mrsand-tabla').remove();
            });
        });
        </script>
        <style>
        /* --- Desktop: todo en una fila --- */
        #mrsand-fila {
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            align-items: center !important;
            gap: 10px !important;
            margin-top: 12px !important;
        }
        #mrsand-fila table.variations,
        #mrsand-fila table.variations tbody {
            display: flex !important;
            flex-direction: row !important;
            gap: 10px !important;
            align-items: center !important;
            border: none !important;
            background: transparent !important;
            margin: 0 !important;
            padding: 0 !important;
        }
        #mrsand-fila table.variations tr {
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            justify-content: flex-end !important;
            gap: 4px !important;
            width: auto !important;
            border: none !important;
            background: transparent !important;
            padding: 0 !important;
            margin: 0 !important;
        }
        #mrsand-fila table.variations td,
        #mrsand-fila table.variations th {
            display: block !important;
            padding: 0 !important;
            border: none !important;
            background: transparent !important;
            width: auto !important;
            text-align: center !important;
            line-height: 1 !important;
        }
        #mrsand-fila table.variations td.label label,
        #mrsand-fila table.variations th.label label {
            font-size: 11px !important;
            font-weight: 700 !important;
            color: #111 !important;
            text-transform: uppercase !important;
            letter-spacing: 0.06em !important;
            text-align: center !important;
            margin-bottom: 4px !important;
            display: block !important;
            height: 14px !important;
            line-height: 14px !important;
        }
        #mrsand-fila .variations select {
            min-width: 110px !important;
            max-width: 145px !important;
            height: 38px !important;
            border-radius: 50px !important;
            border: none !important;
            padding: 0 28px 0 14px !important;
            font-size: 13px !important;
            font-weight: 600 !important;
            background-color: #111111 !important;
            color: #f3ae14 !important;
            cursor: pointer !important;
            -moz-appearance: none !important;
            -webkit-appearance: none !important;
            appearance: none !important;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath fill='%23f3ae14' d='M1 1l5 5 5-5'/%3E%3C/svg%3E") !important;
            background-repeat: no-repeat !important;
            background-position: right 10px center !important;
            margin: 0 !important;
            display: block !important;
            box-sizing: border-box !important;
        }
        #mrsand-fila .variations select:focus {
            outline: 2px solid #f3ae14 !important;
            outline-offset: 2px !important;
        }
        #mrsand-fila .variations select option {
            background-color: #111 !important;
            color: #f3ae14 !important;
        }
        .reset_variations { display: none !important; }
        .ct-cart-actions {
            display: flex !important;
            flex-direction: row !important;
            align-items: center !important;
            gap: 8px !important;
            flex: 0 0 auto !important;
            margin-top: 18px !important;
        }
        .ct-cart-actions .single_add_to_cart_button,
        .ct-cart-actions .mrsand-ir-carrito {
            height: 38px !important;
            border-radius: 50px !important;
            padding: 0 18px !important;
            font-size: 13px !important;
            font-weight: 700 !important;
            white-space: nowrap !important;
            margin: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            cursor: pointer !important;
            transition: transform 0.15s ease, box-shadow 0.15s ease !important;
        }
        .ct-cart-actions .mrsand-ir-carrito {
            background-color: #111 !important;
            color: #f3ae14 !important;
            border: none !important;
        }
        .ct-cart-actions .single_add_to_cart_button:hover,
        .ct-cart-actions .mrsand-ir-carrito:hover {
            transform: translateY(-1px) !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.18) !important;
        }

        /* --- Tabla de descuentos --- */
        #mrsand-tabla { margin: 20px 0 10px; }
        .mrsand-t { width: 100%; border-collapse: collapse; font-size: 13px; }
        .mrsand-t thead tr { background: #111; color: #f3ae14; }
        .mrsand-t thead th { padding: 9px 10px; text-align: center; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
        .mrsand-t tbody tr { border-bottom: 1px solid #eee; }
        .mrsand-t tbody td { padding: 8px 10px; text-align: center; color: #333; background: #fff; }
        .mrsand-t tbody tr.mrsand-top td { background: #2ecc40; color: #fff; font-weight: 700; }
        .mrsand-nota { font-size: 12px; color: #555; text-align: center; margin-top: 6px; font-style: italic; }

        /* --- Mobile: 2 filas --- */
        @media (max-width: 540px) {
            #mrsand-fila {
                flex-wrap: wrap !important;
                gap: 8px !important;
            }
            #mrsand-fila table.variations {
                flex: 0 0 100% !important;
                width: 100% !important;
                justify-content: flex-start !important;
            }
            .ct-cart-actions {
                flex: 0 0 100% !important;
                width: 100% !important;
                margin-top: 0 !important;
                justify-content: flex-start !important;
            }
            .ct-cart-actions .single_add_to_cart_button,
            .ct-cart-actions .mrsand-ir-carrito {
                flex: 1 1 auto !important;
                justify-content: center !important;
            }
            #mrsand-fila .variations select {
                min-width: 90px !important;
                max-width: 130px !important;
            }
        }
        </style>
        <?php
    }
}

add_filter( 'show_admin_bar', '__return_false' );