<?php
/**
 * Quick Migration Script - Run via CLI to convert all products
 */

$dataFile = __DIR__ . '/data/products.json';
$products = [];
if (file_exists($dataFile)) {
    $products = json_decode(file_get_contents($dataFile), true) ?: [];
}

$converted = 0;
$skipped = 0;

foreach ($products as &$product) {
    // Skip if already has size_variants
    if (isset($product['size_variants'])) {
        $skipped++;
        continue;
    }
    
    $basePrice = (float)($product['price'] ?? 0);
    $mainImage = $product['image'] ?? '';
    $gallery = $product['gallery'] ?? [];
    
    // Convert "sizes" to "size_variants"
    if (isset($product['sizes']) && is_array($product['sizes'])) {
        $sizeVariants = [];
        $priceMap = ['XS' => -20, 'S' => -10, 'M' => 0, 'L' => 20, 'XL' => 40, 'XXL' => 60];
        
        foreach ($product['sizes'] as $idx => $size) {
            $increment = isset($priceMap[$size]) ? $priceMap[$size] : 0;
            $sizeImage = isset($gallery[$idx]) ? $gallery[$idx] : $mainImage;
            
            $sizeVariants[] = [
                'name' => $size,
                'price' => max(5, $basePrice + $increment), // Ensure price is at least $5
                'image' => $sizeImage
            ];
        }
        
        $product['size_variants'] = $sizeVariants;
        unset($product['sizes']);
        $converted++;
    } 
    // Convert single "size" to "size_variants"
    elseif (isset($product['size'])) {
        $product['size_variants'] = [[
            'name' => $product['size'],
            'price' => $basePrice,
            'image' => $mainImage
        ]];
        unset($product['size']);
        $converted++;
    } else {
        $skipped++;
    }
}
unset($product);

// Save
if (file_put_contents($dataFile, json_encode($products, JSON_PRETTY_PRINT)) !== false) {
    echo "✓ Migration Complete!\n";
    echo "  Converted: {$converted} products\n";
    echo "  Skipped: {$skipped} products\n";
} else {
    echo "✗ Error saving file!\n";
}
?>
