<?php
declare(strict_types=1);

class Media
{
    private string $samplesDir;
    private string $samplesUrl;
    private string $uploadsDir;
    private string $uploadsUrl;

    public function __construct(string $rootDir, string $appUrl)
    {
        $this->samplesDir = $rootDir . '/assets/img/samples';
        $this->samplesUrl = $appUrl . '/assets/img/samples';
        $this->uploadsDir = $rootDir . '/uploads/sections';
        $this->uploadsUrl = $appUrl . '/uploads/sections';
    }

    public function list(): array
    {
        return [
            'samples' => $this->scanDir($this->samplesDir, $this->samplesUrl),
            'uploads' => $this->scanDir($this->uploadsDir, $this->uploadsUrl),
        ];
    }

    private function scanDir(string $dir, string $baseUrl): array
    {
        if (!is_dir($dir)) return [];
        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'svg'];
        $files   = [];

        foreach (scandir($dir) as $file) {
            if ($file[0] === '.') continue;
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            if (!in_array($ext, $allowed, true)) continue;
            $files[] = [
                'name' => $file,
                'url'  => $baseUrl . '/' . rawurlencode($file),
            ];
        }

        usort($files, fn($a, $b) => strcmp($a['name'], $b['name']));
        return $files;
    }
}
