<?php
/**
 * Show SIZE next to price on Flatsome/Woo product cards (all loops/widgets)
 * + Sale/real price first, regular/cut price after
 * — prints at most ONCE per product card (no duplicates).
 */

/* =========================================================
   1) SIZE COLLECTOR (SUPER ROBUST)
   - Detects ANY attribute containing "size" in its key/slug/name
   - Works for: pa_size, size, pa_shoe-size, pa_sizes, etc.
   - Works for variable products + variation children
========================================================= */
function wabi_is_size_key($key) {
    $k = strtolower((string)$key);
    return (strpos($k, 'size') !== false); // matches pa_size, size, pa_shoe-size, etc.
}

function wabi_read_attribute_value_to_label($tax_or_key, $raw) {
    $raw = trim((string)$raw);
    if ($raw === '') return '';

    // If taxonomy attribute like pa_size / pa_shoe-size
    if (strpos($tax_or_key, 'pa_') === 0 && taxonomy_exists($tax_or_key)) {
        // raw can be slug OR term name; try slug->name
        $term = get_term_by('slug', $raw, $tax_or_key);
        if ($term && !is_wp_error($term)) return trim($term->name);
    }

    return $raw;
}

function wabi_collect_sizes_any($product) {
    $names = [];
    if (!$product || !is_a($product, 'WC_Product')) return $names;

    // ---- A) Read from product attributes (works for simple + variable parent) ----
    $attrs = $product->get_attributes();

    // For simple: $attrs is array of WC_Product_Attribute objects
    foreach ((array)$attrs as $key => $attr_obj) {
        $attr_key = is_string($key) ? $key : '';

        // WC_Product_Attribute object
        if (is_object($attr_obj) && method_exists($attr_obj, 'get_name')) {
            $name = $attr_obj->get_name(); // like pa_size or "Size"
            if (!wabi_is_size_key($name) && !wabi_is_size_key($attr_key)) continue;

            // taxonomy attribute
            if ($attr_obj->is_taxonomy()) {
                $tax = $name; // usually pa_xxx
                $terms = wc_get_product_terms($product->get_id(), $tax, ['fields' => 'names']);
                foreach ((array)$terms as $t) {
                    $t = trim((string)$t);
                    if ($t !== '') $names[$t] = $t;
                }
            } else {
                // custom attribute value like "6 | 7 | 8"
                $val = $attr_obj->get_options();
                if (is_array($val)) {
                    foreach ($val as $v) {
                        $v = trim((string)$v);
                        if ($v !== '') $names[$v] = $v;
                    }
                }
            }
        }
        // sometimes simple products return string values
        elseif (is_string($attr_obj) && (wabi_is_size_key($attr_key))) {
            $label = wabi_read_attribute_value_to_label($attr_key, $attr_obj);
            if ($label !== '') $names[$label] = $label;
        }
    }

    // ---- B) Variable products: read from variation attributes + children (BEST) ----
    if ($product->is_type('variable')) {

        // 1) Parent-level variation attributes
        $va = $product->get_variation_attributes(); // keys like attribute_pa_size
        foreach ((array)$va as $k => $vals) {
            if (!wabi_is_size_key($k)) continue; // attribute_pa_size, attribute_pa_shoe-size etc

            // Convert "attribute_pa_xxx" -> "pa_xxx"
            $tax = preg_replace('/^attribute_/', '', (string)$k);

            foreach ((array)$vals as $v) {
                $label = wabi_read_attribute_value_to_label($tax, $v);
                if ($label !== '') $names[$label] = $label;
            }
        }

        // 2) Hard fallback: scan variation children attributes
        if (!$names) {
            foreach ((array)$product->get_children() as $vid) {
                $v = wc_get_product($vid);
                if (!$v) continue;

                // Variation raw attributes (keys may be pa_size OR attribute_pa_size etc.)
                $vattrs = $v->get_attributes();

                foreach ((array)$vattrs as $vk => $vv) {
                    if (!wabi_is_size_key($vk)) continue;

                    $tax = (string)$vk;
                    $tax = preg_replace('/^attribute_/', '', $tax); // normalize

                    $label = wabi_read_attribute_value_to_label($tax, $vv);
                    if ($label !== '') $names[$label] = $label;
                }

                // also try getter (sometimes returns value even if array keys differ)
                $all_possible = ['pa_size','size','pa_sizes','pa_shoe-size'];
                foreach ($all_possible as $try) {
                    $val = trim((string)$v->get_attribute($try));
                    if ($val !== '') {
                        $parts = array_map('trim', explode('|', $val));
                        foreach ($parts as $p) if ($p !== '') $names[$p] = $p;
                    }
                }
            }
        }
    }

    return array_values($names);
}

/* =========================================================
   2) DE-DUPE GUARD
========================================================= */
function wabi_size_mark_printed($product_id) {
    if (!isset($GLOBALS['wabi_size_printed'])) $GLOBALS['wabi_size_printed'] = [];
    $GLOBALS['wabi_size_printed'][$product_id] = true;
}
function wabi_size_has_printed($product_id) {
    return !empty($GLOBALS['wabi_size_printed'][$product_id]);
}

/* =========================================================
   3) SIZE HTML RENDERER
========================================================= */
function wabi_size_html_for($product) {
    if (is_admin() || is_product() || !$product) return '';

    $pid = $product->get_id();
    if (wabi_size_has_printed($pid)) return '';

    $sizes = wabi_collect_sizes_any($product);
    if (!$sizes) return '';

    wabi_size_mark_printed($pid);

    return '<span class="wabi-size-after-price"> — <strong>Size:</strong> ' .
           esc_html(implode(', ', $sizes)) .
           '</span>';
}

/* =========================================================
   4) FLATSOME + WOO HOOKS (PRINT SIZE)
========================================================= */
add_action('flatsome_product_box_after_price', function () {
    global $product;
    $html = wabi_size_html_for($product);
    if ($html) echo $html;
}, 10);

add_action('woocommerce_after_shop_loop_item_title', function () {
    global $product;
    $pid = $product ? $product->get_id() : 0;
    if (!$product || wabi_size_has_printed($pid)) return;

    $sizes = wabi_collect_sizes_any($product);
    if (!$sizes) return;

    wabi_size_mark_printed($pid);
    echo '<div class="wabi-size-after-price-inline"><strong>Size:</strong> ' .
         esc_html(implode(', ', $sizes)) .
         '</div>';
}, 11);

/* =========================================================
   5) PRICE ORDER FIX (SALE FIRST)
========================================================= */
function wabi_price_sale_first_html($product) {
    if (!$product || !is_a($product, 'WC_Product')) return '';
    if (!$product->is_on_sale()) return '';

    if ($product->is_type('variable')) {
        $regular_min = $product->get_variation_regular_price('min', true);
        $sale_min    = $product->get_variation_sale_price('min', true);
        if (!$regular_min || !$sale_min) return '';
        return '<span class="price"><ins>' . wc_price($sale_min) . '</ins> <del>' . wc_price($regular_min) . '</del></span>';
    }

    $regular = $product->get_regular_price();
    $sale    = $product->get_sale_price();
    if ($regular === '' || $sale === '') return '';
    return '<span class="price"><ins>' . wc_price($sale) . '</ins> <del>' . wc_price($regular) . '</del></span>';
}

/* =========================================================
   6) FINAL SAFETY NET: Fix price + append size everywhere
========================================================= */
add_filter('woocommerce_get_price_html', function ($price_html, $product) {
    if (!$product) return $price_html;

    $fixed = wabi_price_sale_first_html($product);
    if ($fixed !== '') $price_html = $fixed;

    $extra = wabi_size_html_for($product);
    return $price_html . $extra;
}, 999, 2);

/* =========================================================
   7) CSS
========================================================= */
add_action('wp_head', function () { ?>
    <style id="wabi-size-after-price-css">
        .product-small .price,
        .product-small .wabi-size-after-price { display:inline-block; vertical-align:middle; }
        .product-small .wabi-size-after-price { margin-left:8px; font-size:12px; opacity:.9; }
        .product-small .wabi-size-after-price-inline { margin-top:4px; font-size:12px; opacity:.9; }
        .ux-swiper .product-small .wabi-size-after-price { margin-left:6px; }

        .woocommerce .price ins { text-decoration:none !important; margin-right:8px; font-weight:700; }
        .woocommerce .price del { opacity:.6; }
    </style>
<?php });
