<?php

require_once __DIR__ . '/../helpers/Env.php';
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../helpers/FileUpload.php';

/**
 * Smart thumbnail regeneration based on image aspect ratios
 * Coins are typically square-ish (aspect ratio close to 1.0)
 * Banknotes are typically rectangular (aspect ratio far from 1.0)
 */

echo "Starting smart thumbnail regeneration...\n";

// Create thumbnail directory if it doesn't exist
if (!is_dir(UPLOAD_ITEMS_THUMBS_PATH)) {
    mkdir(UPLOAD_ITEMS_THUMBS_PATH, 0755, true);
    echo "Created thumbnail directory: " . UPLOAD_ITEMS_THUMBS_PATH . "\n";
}

$processedImages = 0;
$failedImages = 0;

// Get all image files
$imageFiles = glob(UPLOAD_ITEMS_PATH . '/*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
echo "Found " . count($imageFiles) . " image files to analyze\n\n";

foreach ($imageFiles as $sourcePath) {
    $filename = basename($sourcePath);
    $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
    
    echo "Analyzing $filename...\n";
    
    // Get image dimensions to determine if it's a coin or banknote
    $imageInfo = getimagesize($sourcePath);
    if ($imageInfo === false) {
        echo "  Skipping: Could not read image info\n";
        continue;
    }
    
    list($width, $height) = $imageInfo;
    $aspectRatio = $width / $height;
    
    echo "  Dimensions: {$width}x{$height}, Aspect ratio: " . number_format($aspectRatio, 2) . "\n";
    
    // Determine if it's a coin or banknote based on aspect ratio
    // Coins are typically square-ish (0.7 to 1.3 aspect ratio)
    // Banknotes are typically rectangular (outside that range)
    $isCoin = ($aspectRatio >= 0.7 && $aspectRatio <= 1.3);
    
    if ($isCoin) {
        echo "  Detected as: COIN (square-ish)\n";
        $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 160, 160, 70);
    } else {
        echo "  Detected as: BANKNOTE (rectangular)\n";
        $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 170, 80, 70);
    }
    
    if ($result['success']) {
        $processedImages++;
        echo "  Created thumbnail: " . basename($thumbPath) . "\n";
    } else {
        $failedImages++;
        echo "  Failed to create thumbnail: " . $result['error'] . "\n";
    }
    
    echo "\n";
}

echo "Smart thumbnail regeneration completed!\n";
echo "Processed images: $processedImages\n";
echo "Failed images: $failedImages\n";

if ($failedImages > 0) {
    echo "\nSome images failed to process. Please check the error messages above.\n";
} else {
    echo "\nAll images processed successfully!\n";
}
