<?php

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

/**
 * Simple script to create thumbnails for all existing image files
 * This processes files directly without needing database access
 */

echo "Starting thumbnail creation for existing images...\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 from the uploads directory
$imageFiles = glob(UPLOAD_ITEMS_PATH . '/*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);

echo "Found " . count($imageFiles) . " image files to process\n\n";

foreach ($imageFiles as $sourcePath) {
    $filename = basename($sourcePath);
    $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
    
    // Skip if thumbnail already exists
    if (file_exists($thumbPath)) {
        echo "Skipping $filename (thumbnail already exists)\n";
        continue;
    }
    
    echo "Processing $filename...\n";
    
    // Determine if this is likely a coin or banknote based on filename patterns
    // This is a heuristic - you might want to adjust this based on your naming conventions
    $isCoin = false;
    
    // Try to determine from filename (you can adjust this logic)
    if (preg_match('/coin|kovanica|novcic/i', $filename) || 
        (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] === 'coins')) {
        $isCoin = true;
    }
    
    // Create thumbnail with appropriate dimensions
    if ($isCoin) {
        $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 160, 160, 70);
    } else {
        $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 "\nThumbnail creation 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";
}

echo "\nUsage notes:\n";
echo "- Run this script as is to process all images as banknotes (170x80)\n";
echo "- Run with 'php create_thumbnails.php coins' to process all images as coins (160x160)\n";
echo "- The script skips images that already have thumbnails\n";
