<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

$adsDir = __DIR__ . '/ads';
$baseUrl = 'ads';
$imageAllowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$videoAllowed = ['mp4', 'webm'];
$allowed = array_merge($imageAllowed, $videoAllowed);
$items = [];

if (is_dir($adsDir)) {
    foreach (scandir($adsDir) as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }

        $fullPath = $adsDir . DIRECTORY_SEPARATOR . $file;
        if (!is_file($fullPath)) {
            continue;
        }

        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed, true)) {
            continue;
        }

        $mtime = @filemtime($fullPath);
        $type = in_array($ext, $videoAllowed, true) ? 'video' : 'image';

        $items[] = [
            'file' => $file,
            'src' => $baseUrl . '/' . rawurlencode($file) . '?v=' . (int)$mtime,
            'mtime' => (int)$mtime,
            'type' => $type,
        ];
    }
}

usort($items, function ($a, $b) {
    if ($a['mtime'] === $b['mtime']) {
        return strnatcasecmp($b['file'], $a['file']);
    }
    return $b['mtime'] <=> $a['mtime'];
});

$signature = sha1(json_encode(array_map(function ($item) {
    return [$item['file'], $item['mtime']];
}, $items)));

echo json_encode([
    'ok' => true,
    'signature' => $signature,
    'count' => count($items),
    'items' => $items,
], JSON_UNESCAPED_SLASHES);
