<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Product;

class SyncProductImages extends Command
{
    protected $signature = 'products:sync-images';
    protected $description = 'Synchroniser les images JSON vers la colonne image';

    public function handle()
    {
        $products = Product::all();
        $updated = 0;

        foreach ($products as $product) {
            try {
                if ($product->images) {
                    $images = json_decode($product->images, true);
                    
                    if (is_array($images) && !empty($images)) {
                        $firstImage = $images[0];
                        
                        if (is_array($firstImage) && isset($firstImage['path'])) {
                            $imagePath = $firstImage['path'];
                        } elseif (is_string($firstImage)) {
                            $imagePath = $firstImage;
                        } else {
                            continue;
                        }
                        
                        // Mettre à jour la colonne image
                        if ($product->image !== $imagePath) {
                            $product->update([
                                'image' => $imagePath,
                                'thumbnail' => $imagePath
                            ]);
                            $updated++;
                            $this->line("✅ Product {$product->id}: {$product->name} - Image synchronisée");
                        }
                    }
                }
            } catch (\Exception $e) {
                $this->error("❌ Product {$product->id}: {$e->getMessage()}");
                continue;
            }
        }

        $this->info("\n✅ Synchronisation complète: $updated produit(s) mis à jour");
    }
}
