<?php

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

/**
 * Script to regenerate thumbnails with correct dimensions for coins and banknotes
 * This script uses database information to determine correct thumbnail sizes
 */

echo "Starting 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";
}

// Simple database connection without using the Database class
$host = Env::get('DB_HOST', '127.0.0.1');
$dbname = Env::get('DB_NAME', 'notafilija');
$username = Env::get('DB_USER');
$password = Env::get('DB_PASS');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    echo "Connected to database successfully\n";
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage() . "\n";
    echo "Please check your database configuration in .env file\n";
    exit(1);
}

$processedImages = 0;
$failedImages = 0;

// Process coins (160x160 square thumbnails)
echo "\nProcessing coins...\n";
$stmt = $pdo->query("SELECT image_obverse, image_reverse FROM coins WHERE image_obverse IS NOT NULL OR image_reverse IS NOT NULL");
$coins = $stmt->fetchAll();

foreach ($coins as $coin) {
    // Process obverse image
    if ($coin['image_obverse']) {
        $sourcePath = UPLOAD_ITEMS_PATH . '/' . $coin['image_obverse'];
        if (file_exists($sourcePath)) {
            $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
            $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 160, 160, 70);
            if ($result['success']) {
                $processedImages++;
                echo "Created coin thumbnail: " . basename($thumbPath) . "\n";
            } else {
                $failedImages++;
                echo "Failed to create coin thumbnail for " . $coin['image_obverse'] . ": " . $result['error'] . "\n";
            }
        }
    }
    
    // Process reverse image
    if ($coin['image_reverse']) {
        $sourcePath = UPLOAD_ITEMS_PATH . '/' . $coin['image_reverse'];
        if (file_exists($sourcePath)) {
            $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
            $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 160, 160, 70);
            if ($result['success']) {
                $processedImages++;
                echo "Created coin thumbnail: " . basename($thumbPath) . "\n";
            } else {
                $failedImages++;
                echo "Failed to create coin thumbnail for " . $coin['image_reverse'] . ": " . $result['error'] . "\n";
            }
        }
    }
}

// Process additional coin images
echo "\nProcessing additional coin images...\n";
$stmt = $pdo->query("SELECT filename FROM coin_images WHERE filename IS NOT NULL");
$coinImages = $stmt->fetchAll();

foreach ($coinImages as $coinImage) {
    $sourcePath = UPLOAD_ITEMS_PATH . '/' . $coinImage['filename'];
    if (file_exists($sourcePath)) {
        $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
        $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 160, 160, 70);
        if ($result['success']) {
            $processedImages++;
            echo "Created coin thumbnail: " . basename($thumbPath) . "\n";
        } else {
            $failedImages++;
            echo "Failed to create coin thumbnail for " . $coinImage['filename'] . ": " . $result['error'] . "\n";
        }
    }
}

// Process items/banknotes (170x80 rectangular thumbnails)
echo "\nProcessing banknotes...\n";
$stmt = $pdo->query("SELECT image_obverse, image_reverse FROM items WHERE image_obverse IS NOT NULL OR image_reverse IS NOT NULL");
$items = $stmt->fetchAll();

foreach ($items as $item) {
    // Process obverse image
    if ($item['image_obverse']) {
        $sourcePath = UPLOAD_ITEMS_PATH . '/' . $item['image_obverse'];
        if (file_exists($sourcePath)) {
            $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
            $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 170, 80, 70);
            if ($result['success']) {
                $processedImages++;
                echo "Created banknote thumbnail: " . basename($thumbPath) . "\n";
            } else {
                $failedImages++;
                echo "Failed to create banknote thumbnail for " . $item['image_obverse'] . ": " . $result['error'] . "\n";
            }
        }
    }
    
    // Process reverse image
    if ($item['image_reverse']) {
        $sourcePath = UPLOAD_ITEMS_PATH . '/' . $item['image_reverse'];
        if (file_exists($sourcePath)) {
            $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
            $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 170, 80, 70);
            if ($result['success']) {
                $processedImages++;
                echo "Created banknote thumbnail: " . basename($thumbPath) . "\n";
            } else {
                $failedImages++;
                echo "Failed to create banknote thumbnail for " . $item['image_reverse'] . ": " . $result['error'] . "\n";
            }
        }
    }
}

// Process additional item images
echo "\nProcessing additional banknote images...\n";
$stmt = $pdo->query("SELECT filename FROM item_images WHERE filename IS NOT NULL");
$itemImages = $stmt->fetchAll();

foreach ($itemImages as $itemImage) {
    $sourcePath = UPLOAD_ITEMS_PATH . '/' . $itemImage['filename'];
    if (file_exists($sourcePath)) {
        $thumbPath = FileUpload::getThumbnailPath($sourcePath, UPLOAD_ITEMS_THUMBS_PATH);
        $result = FileUpload::createThumbnail($sourcePath, $thumbPath, 170, 80, 70);
        if ($result['success']) {
            $processedImages++;
            echo "Created banknote thumbnail: " . basename($thumbPath) . "\n";
        } else {
            $failedImages++;
            echo "Failed to create banknote thumbnail for " . $itemImage['filename'] . ": " . $result['error'] . "\n";
        }
    }
}

echo "\nThumbnail 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";
}
