<?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'] ?? '';

$resolved = resolveAllowedFile($folderKey, $subPath, $fileName);
if ($resolved === false) die();

$subPath = $resolved['path'];
$fileName = $resolved['file'];
$megaPath = $resolved['mega']; 
$localPath = $resolved['full']; 

$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
$fileMtime = @filemtime($localPath) ?: 0;
$fileSize = @filesize($localPath) ?: 0;
$hash = md5($megaPath . '|' . $fileMtime . '|' . $fileSize) . '.webp';
$thumbPath = $thumbDir . '/' . $hash;
$thumbTmp = $thumbPath . '.tmp';
$thumbPart = $thumbPath . '.part.webp';

if (is_file($thumbPath) && filesize($thumbPath) === 0) @unlink($thumbPath);
if (is_file($thumbTmp) && time() - filemtime($thumbTmp) > 300) @unlink($thumbTmp);
if (is_file($thumbPart) && time() - filemtime($thumbPart) > 300) @unlink($thumbPart);

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

if (!file_exists($thumbPath)) {
    $lockHandle = @fopen($thumbTmp, 'x');
    if ($lockHandle !== false) {
        fclose($lockHandle);
        @unlink($thumbPart);
        ini_set('memory_limit', '256M'); // Bezpieczny limit RAM dla duzych matryc z aparatu

        $sourceInfo = @getimagesize($localPath);
        $estimatedMemory = $sourceInfo ? ((int)$sourceInfo[0] * (int)$sourceInfo[1] * 5) : PHP_INT_MAX;
        $im = null;

        // Bardzo duże obrazy są wysyłane bez generowania miniatury, aby pojedyncze żądanie nie zużyło całej pamięci PHP.
        if ($sourceInfo !== false && $estimatedMemory < 220 * 1024 * 1024) {
            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(1, min($thumbSize/$w, $thumbSize/$h));
            $newW = max(1, (int)round($w * $ratio));
            $newH = max(1, (int)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);
            $saved = imagewebp($thumb, $thumbPart, 80); // Zapisujemy super-lekki plik
            imagedestroy($im);
            imagedestroy($thumb);

            if ($saved && is_file($thumbPart) && filesize($thumbPart) > 0) {
                @rename($thumbPart, $thumbPath);
            } else {
                @unlink($thumbPart);
            }
        }

        @unlink($thumbTmp);
    } else {
        // Inne żądanie generuje tę samą miniaturę. Czekamy krótko na gotowy plik.
        for ($i = 0; $i < 20 && !is_file($thumbPath); $i++) usleep(100000);
    }
}

if (!is_file($thumbPath) || filesize($thumbPath) === 0) {
    // Fallback dla uszkodzonych lub zbyt dużych plików obrazów
    header('Content-Type: image/' . ($ext === 'jpg' ? 'jpeg' : $ext));
    header('Content-Disposition: inline; filename="' . str_replace('"', "'", $fileName) . '"');
    header('Cache-Control: private, max-age=3600');
    header("X-Sendfile: " . $localPath);
    exit;
}

// Serwujemy lokalną, wygenerowaną miniaturę (błyskawicznie!)
@touch($thumbPath);
header('Content-Type: image/webp');
header('Content-Length: ' . filesize($thumbPath));
header('Cache-Control: private, max-age=86400');
readfile($thumbPath);
exit;
