<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

$galleryDir = __DIR__ . '/gallery';
$thumbsDir = $galleryDir . '/.thumbs';

if (!file_exists($galleryDir)) {
    mkdir($galleryDir, 0755, true);
}
if (!file_exists($thumbsDir)) {
    mkdir($thumbsDir, 0755, true);
}

// Помощна функция за генериране на миниатюри (само за снимки)
function createThumbnail($sourcePath, $thumbPath, $maxWidth = 400, $maxHeight = 400) {
    if (file_exists($thumbPath)) return true; // Вече има
    
    $ext = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
    
    // Проверка дали имаме нужните функции (GD library)
    if (!function_exists('imagecreatefromjpeg')) return false;

    if ($ext === 'jpg' || $ext === 'jpeg') {
        $sourceImage = @imagecreatefromjpeg($sourcePath);
    } else if ($ext === 'png') {
        $sourceImage = @imagecreatefrompng($sourcePath);
    } else if ($ext === 'gif') {
        $sourceImage = @imagecreatefromgif($sourcePath);
    } else if ($ext === 'webp') {
        $sourceImage = @imagecreatefromwebp($sourcePath);
    } else {
        return false;
    }

    if (!$sourceImage) return false;

    $sourceWidth = imagesx($sourceImage);
    $sourceHeight = imagesy($sourceImage);

    $ratio = min($maxWidth / $sourceWidth, $maxHeight / $sourceHeight);
    $newWidth = max(1, $sourceWidth * $ratio);
    $newHeight = max(1, $sourceHeight * $ratio);

    $thumbImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // Запазване на прозрачността за PNG/WebP
    if ($ext === 'png' || $ext === 'webp') {
        imagealphablending($thumbImage, false);
        imagesavealpha($thumbImage, true);
        $transparent = imagecolorallocatealpha($thumbImage, 255, 255, 255, 127);
        imagefilledrectangle($thumbImage, 0, 0, $newWidth, $newHeight, $transparent);
    }

    imagecopyresampled($thumbImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);

    if ($ext === 'png') {
        imagepng($thumbImage, $thumbPath, 5);
    } else {
        imagejpeg($thumbImage, $thumbPath, 80);
    }

    imagedestroy($sourceImage);
    imagedestroy($thumbImage);
    return true;
}

$files = scandir($galleryDir);
$items = [];

foreach ($files as $file) {
    if ($file === '.' || $file === '..' || $file === '.thumbs') continue;
    
    $filePath = $galleryDir . '/' . $file;
    if (is_dir($filePath)) continue;

    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $isImage = in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp']);
    $isVideo = in_array($ext, ['mp4', 'mov', 'avi', 'mkv', 'webm']);

    if (!$isImage && !$isVideo) continue; // Показваме само снимки и видеа

    $item = [
        'name' => $file,
        'url' => 'gallery/' . rawurlencode($file),
        'type' => $isImage ? 'image' : 'video',
        'size' => filesize($filePath)
    ];

    if ($isImage) {
        $thumbName = $file;
        $thumbPath = $thumbsDir . '/' . $thumbName;
        
        // Създаване на тъмбнейл (ако все още няма)
        createThumbnail($filePath, $thumbPath);
        
        if (file_exists($thumbPath)) {
            $item['thumbnail'] = 'gallery/.thumbs/' . rawurlencode($thumbName);
        } else {
            $item['thumbnail'] = $item['url']; // Ако GD липсва, ползваме оригинала
        }
    } else {
        $item['thumbnail'] = null; 
        
        // Опит за генериране на видео тъмбнейл чрез ffmpeg (ако сървърът/Unraid го поддържа)
        $thumbName = $file . '.jpg';
        $thumbPath = $thumbsDir . '/' . $thumbName;
        
        if (!file_exists($thumbPath) && function_exists('exec')) {
            $ffmpegPath = exec('which ffmpeg');
            if (!empty($ffmpegPath)) {
                $cmd = escapeshellcmd($ffmpegPath) . " -i " . escapeshellarg($filePath) . " -ss 00:00:00.001 -vframes 1 -vf \"scale='min(400,iw)':-1\" -q:v 2 " . escapeshellarg($thumbPath) . " 2>&1";
                exec($cmd);
            }
        }
        
        if (file_exists($thumbPath)) {
            $item['thumbnail'] = 'gallery/.thumbs/' . rawurlencode($thumbName);
        }
    }

    $items[] = $item;
}

// Сортиране: най-новите файлове първи
usort($items, function($a, $b) use ($galleryDir) {
    $timeA = filemtime($galleryDir . '/' . $a['name']);
    $timeB = filemtime($galleryDir . '/' . $b['name']);
    return $timeB - $timeA;
});

echo json_encode(['status' => 'success', 'items' => $items]);
?>
