<?php
/**
 * Fix corrupted image filenames in products.json
 * This script maps corrupted filenames to actual files on disk
 */

$dataFile = __DIR__ . '/data/products.json';
$picsDir = __DIR__ . '/pics_ecom';

// Map of corrupted filenames to correct ones
$fileMap = [
    // These are the files that actually exist on disk
    'Shipping_ Worldwide\u00a0Express\u00a0Shipping\u2026.jfif' => 'Shipping_ Worldwide Express Shipping.jfif',
    'Hulianfu Chiffon Dress for Women Fashion Fairycore\u2026 (1).jfif' => 'f1.jpg',  // Use fallback
    'Make a bold statement with Green Pointed-Toe\u2026.jfif' => 'f2.jpg', // Use fallback
    'Sommerkleid mit Ditsy Blume Muster, geraffter\u2026.jfif' => 'f3.jpg', // Use fallback
    '_Miss Dior Eau de Parfum \u0639\u0637\u0631 \u0645\u0633 \u062f\u064a\u0648\u0631 \u0644\u0644\u0646\u0633\u0627\u0621\u2764\ufe0f_\ud83d\udd25\ud83e\udd79\u2026.jfif' => 'by aya.jfif',
    '\u2708\ufe0e\ud835\ude70\ud835\ude9f\ud835\ude8a\ud835\ude92\ud835\ude95\ud835\ude8a\ud835\ude8b\ud835\ude95\ud835\ude8e  \ud835\ude8f\ud835\ude98\ud835\ude9b \ud835\ude99\ud835\ude9b\ud835\ude8e-\ud835\ude98\ud835\ude9b\ud835\ude8d\ud835\ude8e\ud835\ude9b\u2708\ufe0e\u2026 (1).jfif' => 'f4.jpg'
];

// Read the products.json file
$data = json_decode(file_get_contents($dataFile), true);

if (!$data) {
    die('Error reading products.json');
}

// Function to clean image paths recursively
function cleanImagePath($value) {
    global $fileMap;
    
    if (is_string($value)) {
        // Check if this is an image path with corrupted filename
        foreach ($fileMap as $corrupted => $clean) {
            if (strpos($value, $corrupted) !== false) {
                // Replace with a valid image
                return str_replace($corrupted, $clean, $value);
            }
        }
    }
    return $value;
}

// Function to recursively fix all image references
function fixImages(&$item) {
    if (is_array($item)) {
        foreach ($item as $key => &$value) {
            if (is_string($value) && (strpos($value, 'pics_ecom') !== false || strpos($value, 'pics_ecom') !== false)) {
                $value = cleanImagePath($value);
            } elseif (is_array($value)) {
                fixImages($value);
            }
        }
    }
}

// Fix each product
foreach ($data as &$product) {
    fixImages($product);
}

// Save the cleaned data
if (file_put_contents($dataFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
    echo "Products.json fixed successfully!";
} else {
    echo "Error writing to products.json";
}
?>
