<?php
/**
 * Script to add color images to products that have colors but no images for those colors
 * Uses images from pics_ecom folder
 */

$productsFile = __DIR__ . '/data/products.json';
$products = [];

if (file_exists($productsFile)) {
    $products = json_decode(file_get_contents($productsFile), true) ?: [];
}

// Get all available images from pics_ecom
$picsDir = __DIR__ . '/pics_ecom';
$availableImages = [];
if (is_dir($picsDir)) {
    $files = scandir($picsDir);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..' && preg_match('/\.(jpg|jpeg|png|gif|jfif)$/i', $file)) {
            $availableImages[] = 'pics_ecom/' . $file;
        }
    }
}

$updated = 0;
foreach ($products as $key => $product) {
    if (empty($product['colors']) || !is_array($product['colors'])) {
        continue;
    }
    
    $changed = false;
    foreach ($product['colors'] as $colorIdx => $color) {
        // If color doesn't have an image, add one
        if (empty($color['image']) || !file_exists(__DIR__ . '/' . $color['image'])) {
            // Get random image (excluding main product image)
            $mainImage = $product['image'] ?? '';
            $candidates = array_filter($availableImages, function($img) use ($mainImage) {
                return $img !== $mainImage;
            });
            
            if (count($candidates) > 0) {
                $candidates = array_values($candidates);
                $randomImage = $candidates[array_rand($candidates)];
                $products[$key]['colors'][$colorIdx]['image'] = $randomImage;
                $changed = true;
            }
        }
    }
    
    if ($changed) {
        $updated++;
    }
}

// Save updated products
if ($updated > 0) {
    file_put_contents($productsFile, json_encode($products, JSON_PRETTY_PRINT));
    echo "Updated $updated products with color images.\n";
} else {
    echo "No products needed updating.\n";
}
