<?php
/**
 * Script to add gallery photos to all products that don't have them
 * 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) {
    $changed = false;
    
    // If product has no gallery or empty gallery, add some images
    if (empty($product['gallery']) || !is_array($product['gallery']) || count($product['gallery']) === 0) {
        // Get 2-4 random images (excluding the 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);
            $numGallery = min(rand(2, 4), count($candidates));
            $galleryImages = array_slice($candidates, 0, $numGallery);
            $products[$key]['gallery'] = $galleryImages;
            $changed = true;
            $updated++;
        }
    }
}

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