<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
admin_require_login();

function media_collect_files(string $dir): array
{
    if (!is_dir($dir)) {
        return [];
    }
    $result = [];
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    foreach ($iterator as $file) {
        if (!$file->isFile()) {
            continue;
        }
        $path = (string) $file->getPathname();
        $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg', 'ico'], true)) {
            continue;
        }
        $relative = str_replace(UPLOADS_DIR, '', $path);
        $relative = str_replace('\\', '/', $relative);
        $result[] = [
            'path' => $path,
            'url' => '/uploads' . $relative,
            'size' => (int) $file->getSize(),
            'modified_at' => (int) $file->getMTime(),
        ];
    }
    usort($result, static fn(array $a, array $b): int => $b['modified_at'] <=> $a['modified_at']);
    return $result;
}

$notice = '';
if (request_method() === 'POST' && isset($_FILES['file'])) {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $uploaded = admin_upload_image_file($_FILES['file'], trim(post_text('upload_folder', 'manual'), '/'));
        if ($uploaded) {
            $notice = '<div class="notice">Файл загружен: ' . e($uploaded) . '</div>';
        } else {
            $notice = '<div class="notice notice--error">Не удалось загрузить файл. Допустимы: jpg, jpeg, png, webp, gif, svg, ico.</div>';
        }
    }
}

$files = media_collect_files(UPLOADS_DIR);
$totalBytes = array_sum(array_column($files, 'size'));
ob_start();
echo $notice;
?>
<div class="grid grid-3">
  <div class="card"><div class="badge">Файлы</div><h2><?= count($files) ?></h2><p>Всего изображений и иконок в <code>/uploads</code> и вложенных папках.</p></div>
  <div class="card"><div class="badge">Размер</div><h2><?= e(format_bytes((int)$totalBytes)) ?></h2><p>Суммарный объём медиатеки.</p></div>
  <div class="card"><div class="badge">Структура</div><h2><?= count(array_unique(array_map(static fn(array $item): string => dirname($item['url']), $files))) ?></h2><p>Папок с файлами внутри uploads.</p></div>
</div>

<form class="panel grid" method="post" enctype="multipart/form-data" style="margin-top:18px">
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
  <div class="admin-page-head admin-page-head--compact">
    <div>
      <div class="badge">Загрузка</div>
      <h2 style="margin:10px 0 6px">Добавить файл в медиатеку</h2>
    </div>
  </div>
  <div class="grid grid-2">
    <label><span>Файл</span><input type="file" name="file" accept=".jpg,.jpeg,.png,.webp,.gif,.svg,.ico"></label>
    <label><span>Подпапка внутри uploads</span><input name="upload_folder" placeholder="manual, gallery, reviews, branding" value="manual"></label>
  </div>
  <button class="button" type="submit">Загрузить</button>
</form>

<div class="grid grid-3" style="margin-top:18px">
  <?php foreach ($files as $file): ?>
    <div class="card media-card">
      <div class="media-card__preview">
        <img src="<?= e($file['url']) ?>" alt="">
      </div>
      <div class="media-card__meta">
        <div class="media-card__path"><?= e($file['url']) ?></div>
        <div class="muted"><?= e(format_bytes((int)$file['size'])) ?> · <?= e(date('d.m.Y H:i', (int)$file['modified_at'])) ?></div>
      </div>
      <div class="module-actions">
        <button class="button button--ghost button--small" type="button" data-copy-text="<?= e($file['url']) ?>">Скопировать URL</button>
        <a class="button button--ghost button--small" href="<?= e($file['url']) ?>" target="_blank" rel="noopener">Открыть</a>
      </div>
    </div>
  <?php endforeach; ?>
</div>
<?php
admin_layout('Медиатека', ob_get_clean(), 'media');
