<?php
/**
 * Diagnostic tool to find duplicate image URLs in step data files.
 */

$files = [
    'furniture_steps.php',
    'civil_steps.php',
    'aluminium_steps.php',
    'pvc_steps.php'
];

$image_usage = [];

foreach ($files as $file) {
    if (!file_exists($file)) {
        continue;
    }
    
    $content = file_get_contents($file);
    
    // Match entire item blocks to get number, title, and image
    if (preg_match_all("/'number'\s*=>\s*(\d+).*?'title'\s*=>\s*['\"]([^'\"]+)['\"].*?'image'\s*=>\s*['\"]([^'\"]+)['\"]/is", $content, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            $num = $match[1];
            $title = $match[2];
            $img = $match[3];
            
            $id = $img;
            if (preg_match('/photo-([a-zA-Z0-9-]+)/', $img, $m)) {
                $id = $m[1];
            }
            
            if (!isset($image_usage[$id])) {
                $image_usage[$id] = [];
            }
            
            $image_usage[$id][] = [
                'file' => $file,
                'number' => $num,
                'title' => $title,
                'image' => $img
            ];
        }
    }
}

$report = "Duplicates Found:\n";
$report .= "================\n";

$duplicate_count = 0;
foreach ($image_usage as $id => $usages) {
    if (count($usages) > 1) {
        $duplicate_count++;
        $report .= "Image ID/URL: $id\n";
        foreach ($usages as $use) {
            $report .= "  - [{$use['file']}] #{$use['number']}: {$use['title']} ({$use['image']})\n";
        }
        $report .= "\n";
    }
}

if ($duplicate_count === 0) {
    $report .= "No duplicates found! All images are unique.\n";
} else {
    $report .= "Total duplicate images found: $duplicate_count\n";
}

file_put_contents('duplicates_report.txt', $report);
echo "Report written to duplicates_report.txt\n";
?>
