<?php
/**
 * Sync Product Images
 * This script matches product names to image filenames and updates the database
 */

include "config/db.php";

// Define image matches - product ID/name to image filename
$image_mapping = [
    1 => 'saree1.jpg',                                    // Red Silk Saree
    2 => 'lehenga1.jpg',                                  // Designer Lehenga
    3 => 'gown1.jpg',                                     // Evening Gown
    5 => 'Cocktail Dress.webp',                           // Cocktail Dress
    6 => 'anarkali1.jpg',                                 // Designer Anarkali
    8 => '1769000225_6970cd213e9ee.png',                  // Pink Cotton Metallic Polka Dots Flared Suit Set
];

// Alternative: Auto-match by name (fuzzy matching)
function getMatchingImage($product_name, $product_id) {
    $images_dir = __DIR__ . '/assets/images/products/';
    $images = array_diff(scandir($images_dir), ['.', '..']);
    
    $name_lower = strtolower($product_name);
    
    // Direct keyword matching
    $keywords = [
        'saree' => 'saree1.jpg',
        'lehenga' => 'lehenga1.jpg',
        'gown' => 'gown1.jpg',
        'cocktail' => 'Cocktail Dress.webp',
        'anarkali' => 'anarkali1.jpg',
        'sherwani' => 'sherwani1.jpg',
    ];
    
    foreach ($keywords as $keyword => $filename) {
        if (strpos($name_lower, $keyword) !== false) {
            $filepath = $images_dir . $filename;
            if (file_exists($filepath)) {
                return $filename;
            }
        }
    }
    
    // No fallback if no match found
    return '';
}

// Get all products
$result = mysqli_query($conn, "SELECT id, name FROM products ORDER BY id");

if (!$result) {
    die("Error: " . mysqli_error($conn));
}

$updated_count = 0;
$updates = [];

echo "<h2>Product Image Sync Report</h2>";
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Product ID</th><th>Product Name</th><th>Matched Image</th><th>Status</th></tr>";

while ($product = mysqli_fetch_assoc($result)) {
    $id = $product['id'];
    $name = $product['name'];
    
    // Use mapping if exists, otherwise auto-match
    $image = isset($image_mapping[$id]) ? $image_mapping[$id] : getMatchingImage($name, $id);
    
    // Verify image exists
    $image_path = __DIR__ . '/assets/images/products/' . $image;
    $exists = file_exists($image_path);
    
    $status = $exists ? '✓ Found' : '✗ Missing';
    $status_color = $exists ? 'green' : 'red';
    
    echo "<tr>";
    echo "<td>$id</td>";
    echo "<td>$name</td>";
    echo "<td>$image</td>";
    echo "<td style='color: $status_color;'>$status</td>";
    echo "</tr>";
    
    if ($exists) {
        $updates[] = [
            'id' => $id,
            'image' => $image
        ];
        $updated_count++;
    }
}

echo "</table>";

// Apply updates
if ($updated_count > 0) {
    echo "<h3>Updating Database...</h3>";
    
    foreach ($updates as $update) {
        $id = $update['id'];
        $image = mysqli_real_escape_string($conn, $update['image']);
        
        $query = "UPDATE products SET images = '$image' WHERE id = $id";
        if (mysqli_query($conn, $query)) {
            echo "✓ Updated product ID $id with image: $image<br>";
        } else {
            echo "✗ Error updating product ID $id: " . mysqli_error($conn) . "<br>";
        }
    }
    
    echo "<h3 style='color: green;'>Success! $updated_count products updated.</h3>";
} else {
    echo "<h3 style='color: red;'>No matching images found. Please check image filenames.</h3>";
}

echo "<br><a href='index.php' style='padding: 10px 20px; background: #ff6b35; color: white; text-decoration: none; border-radius: 5px;'>Back to Home</a>";
?>
