<?php
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/includes/functions.php';
startSecureSession();

if ($_SESSION['admin_role'] !== 'super_admin') {
    header('Content-Type: application/json');
    die(json_encode(['error' => 'Unauthorized']));
}

$files = [];
$dir = UPLOAD_PATH . '/';

if (is_dir($dir)) {
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $path = $dir . $item;
        if (is_file($path)) {
            $mime = mime_content_type($path);
            if (strpos($mime, 'image/') === 0) {
                $files[] = [
                    'name' => $item,
                    'url' => '/uploads/' . $item,
                    'size' => filesize($path),
                    'time' => filemtime($path)
                ];
            }
        }
    }
}

// Sort by time descending
usort($files, function($a, $b) { return $b['time'] - $a['time']; });

header('Content-Type: application/json');
echo json_encode(['success' => true, 'files' => $files]);
