<?php
ini_set('display_errors', 0); error_reporting(0);
require_once 'functions.php';
checkAuth();
$cfg = cfg();

$folderKey = $_GET['folder'] ?? '';
$subPath = $_GET['path'] ?? '';
$fileName = $_GET['file'] ?? '';

if (!isset($cfg['allowedFolders'][$folderKey])) die();

$subPath = sanitizePath($subPath);
$fileName = basename($fileName);
$megaPath = rtrim($cfg['allowedFolders'][$folderKey] . '/' . $subPath, '/') . '/' . $fileName; 
$localPath = '/mnt/mega' . $megaPath; 

if (!file_exists($localPath) || is_dir($localPath)) die();

$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) die();

$thumbDir = __DIR__ . '/data/thumbs';
if (!is_dir($thumbDir)) mkdir($thumbDir, 0777, true);

// Tworzymy unikalny skrót i zapisujemy w formacie WebP dla optymalizacji
$hash = md5($megaPath) . '.webp';
$thumbPath = $thumbDir . '/' . $hash;

// Jesli w systemie Linux brakuje biblioteki GD, wysylamy po prostu normalne zdjecie
if (!function_exists('imagecreatefromjpeg')) {
    header('Content-Type: image/' . ($ext === 'jpg' ? 'jpeg' : $ext));
    header('Content-Disposition: inline; filename="' . $fileName . '"');
    header("X-Sendfile: " . $localPath);
    exit;
}

if (!file_exists($thumbPath)) {
    ini_set('memory_limit', '512M'); // Bezpieczny limit RAM dla duzych matryc z aparatu
    
    $im = null;
    if ($ext === 'jpg' || $ext === 'jpeg') $im = @imagecreatefromjpeg($localPath);
    elseif ($ext === 'png') $im = @imagecreatefrompng($localPath);
    elseif ($ext === 'gif') $im = @imagecreatefromgif($localPath);
    elseif ($ext === 'webp') $im = @imagecreatefromwebp($localPath);

    if ($im) {
        $w = imagesx($im);
        $h = imagesy($im);
        $thumbSize = 400; // Bazowy wymiar miniatury w pikselach
        
        $ratio = min($thumbSize/$w, $thumbSize/$h);
        $newW = round($w * $ratio);
        $newH = round($h * $ratio);
        
        $thumb = imagecreatetruecolor($newW, $newH);
        
        if ($ext === 'png' || $ext === 'webp' || $ext === 'gif') {
            imagealphablending($thumb, false);
            imagesavealpha($thumb, true);
            $transparent = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
            imagefilledrectangle($thumb, 0, 0, $newW, $newH, $transparent);
        }
        
        imagecopyresampled($thumb, $im, 0, 0, 0, 0, $newW, $newH, $w, $h);
        imagewebp($thumb, $thumbPath, 80); // Zapisujemy super-lekki plik
        imagedestroy($im);
        imagedestroy($thumb);
    } else {
        // Fallback dla uszkodzonych plików obrazów
        header('Content-Type: image/' . ($ext === 'jpg' ? 'jpeg' : $ext));
        header('Content-Disposition: inline; filename="' . $fileName . '"');
        header("X-Sendfile: " . $localPath);
        exit;
    }
}

// Serwujemy lokalną, wygenerowaną miniaturę (błyskawicznie!)
header('Content-Type: image/webp');
header('Content-Length: ' . filesize($thumbPath));
readfile($thumbPath);
exit;
