<?php
function parse_products($details, $qty = 0, $unit_price = 0.0) {
    if (empty($details)) return [];
    $details = trim($details);
    if (strpos($details, '[') === 0) {
        $parsed = json_decode($details, true);
        if (is_array($parsed)) {
            return $parsed;
        }
    }
    
    // Legacy fallback
    preg_match('/Name:\s*(.*)/i',        $details, $m1);
    preg_match('/SKU:\s*(.*)/i',          $details, $m2);
    preg_match('/Description:\s*(.*)/i',  $details, $m3);
    
    $product_name = trim($m1[1] ?? (explode("\n", $details)[0] ?? ''));
    $product_sku  = trim($m2[1] ?? '');
    $product_desc = trim($m3[1] ?? '');
    
    return [[
        'name' => $product_name,
        'sku' => $product_sku,
        'description' => $product_desc,
        'quantity' => (int)$qty,
        'unit_price' => (float)$unit_price
    ]];
}

$legacy = "Name: E2E Test Shirt\nSKU: E2E-SH-001\nDescription: Test shirt description";
print_r(parse_products($legacy, 100, 12.50));
?>
