<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$baseDir = __DIR__ . DIRECTORY_SEPARATOR . 'pics';
$cacheFile = __DIR__ . DIRECTORY_SEPARATOR . 'asset-manifest.json';
$cacheTtlSeconds = 900;
$refreshRequested = isset($_GET['refresh']) && $_GET['refresh'] === '1';

if (!is_dir($baseDir)) {
    http_response_code(500);
    echo json_encode([
        'error' => 'pics directory not found'
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

$imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'svg'];

if (!$refreshRequested && is_file($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTtlSeconds) {
    $cached = file_get_contents($cacheFile);
    if ($cached !== false && trim($cached) !== '') {
        echo $cached;
        exit;
    }
}

$backgrounds = [];
$logos = [];

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($baseDir, FilesystemIterator::SKIP_DOTS)
);

if (!$iterator instanceof RecursiveIteratorIterator) {
    http_response_code(500);
    echo json_encode([
        'error' => 'pics directory could not be scanned'
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

foreach ($iterator as $fileInfo) {
    if (!$fileInfo instanceof SplFileInfo || !$fileInfo->isFile()) {
        continue;
    }

    $extension = strtolower($fileInfo->getExtension());
    if (!in_array($extension, $imageExtensions, true)) {
        continue;
    }

    $absolutePath = $fileInfo->getPathname();
    $relativePath = str_replace('\\', '/', substr($absolutePath, strlen($baseDir) + 1));
    $asset = buildAsset($fileInfo, $relativePath);

    if (isLogoAsset($relativePath)) {
        $logos[] = $asset;
    } else {
        $backgrounds[] = $asset;
    }
}

usort($backgrounds, static function (array $left, array $right): int {
    $groupCompare = strnatcasecmp($left['group'], $right['group']);
    if ($groupCompare !== 0) {
        return $groupCompare;
    }

    return strnatcasecmp($left['label'], $right['label']);
});

usort($logos, static function (array $left, array $right): int {
    $groupCompare = strnatcasecmp($left['group'], $right['group']);
    if ($groupCompare !== 0) {
        return $groupCompare;
    }

    return strnatcasecmp($left['label'], $right['label']);
});

tryWriteCache($cacheFile, json_encode([
    'backgrounds' => $backgrounds,
    'logos' => $logos
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

echo json_encode([
    'backgrounds' => $backgrounds,
    'logos' => $logos
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

function buildAsset(SplFileInfo $fileInfo, string $relativePath): array
{
    $segments = explode('/', $relativePath);
    $group = count($segments) > 1 ? $segments[0] : 'Allgemein';

    return [
        'group' => $group,
        'label' => buildLabel($fileInfo->getBasename('.' . $fileInfo->getExtension())),
        'url' => 'pics/' . encodePath($relativePath)
    ];
}

function isLogoAsset(string $relativePath): bool
{
    $path = strtolower(str_replace('\\', '/', $relativePath));

    if (preg_match('/(^|\/)(logo|logos|logo svg|svg)(\/|$)/', $path)) {
        return true;
    }

    if (preg_match('/logo|_logo|logoeule|wbk_logo|sb[_ -]?logo/', $path)) {
        return true;
    }

    return false;
}

function buildLabel(string $value): string
{
    $value = str_replace(['_', '-'], ' ', $value);
    $value = preg_replace('/\s+/', ' ', $value);
    $value = trim((string) $value);
    return $value !== '' ? $value : 'Datei';
}

function encodePath(string $relativePath): string
{
    $segments = explode('/', $relativePath);
    $encodedSegments = array_map(static function (string $segment): string {
        return rawurlencode($segment);
    }, $segments);

    return implode('/', $encodedSegments);
}

function tryWriteCache(string $cacheFile, $json): void
{
    if (!is_string($json) || $json === '') {
        return;
    }

    @file_put_contents($cacheFile, $json . PHP_EOL, LOCK_EX);
}
