/*
Theme Name: Lightning Child
Theme URI:
Template: lightning
Description:
Author:
Tags:
Version: 0.6.1
*/

// from価格（税抜）を取得：_from_price or from_price のどちらでもOK
function my_get_from_price_ex_tax( $product_id ) {
    foreach (['_from_price','from_price'] as $k) {
        $v = get_post_meta($product_id, $k, true);
        if ($v !== '' && is_numeric($v)) return (float)$v;
    }
    return null;
}

// 表示用（Wooの税設定＝税抜入力/税込表示に追従）
function my_format_from_price_with_tilde( $product, $from_ex ) {
    $display = wc_price( wc_get_price_to_display($product, ['price'=>$from_ex]) );
    return $display . '〜';
}

// [from_price] ショートコード
add_shortcode('from_price', function($atts){
    if (!function_exists('wc_get_product')) return '';
    $atts = shortcode_atts(['id'=>0], $atts, 'from_price');
    $product = $atts['id'] ? wc_get_product((int)$atts['id']) : wc_get_product(get_the_ID());
    if (!$product) return '';

    $from = my_get_from_price_ex_tax( $product->get_id() );
    if ($from === null) {
        // バリエーション商品で未設定の場合は最安バリエーションから
        if ($product->is_type('variable')) {
            $min_ex = (float)$product->get_variation_price('min', false);
            return '<span class="price">'. my_format_from_price_with_tilde($product, $min_ex) .'</span>';
        }
        return ''; // 何も出さない（従来価格にフォールバック可能）
    }
    return '<span class="price">'. my_format_from_price_with_tilde($product, $from) .'</span>';
});
