<?php
header('Content-Type: application/json');

$basePath = realpath(__DIR__ . '/../storage');

// Создаем директорию для файлов, если её нет
if (!file_exists($basePath)) {
    mkdir($basePath, 0777, true);
}

// Получаем путь из запроса
$requestPath = isset($_GET['path']) ? $_GET['path'] : '';
$requestPath = str_replace('..', '', $requestPath);
$requestPath = ltrim($requestPath, '/');

$fullPath = $basePath . ($requestPath ? '/' . $requestPath : '');

// Проверяем, существует ли путь
if (!file_exists($fullPath)) {
    echo json_encode(['error' => "Путь не существует: $requestPath"]);
    exit;
}

// Если это файл — возвращаем информацию для скачивания
if (is_file($fullPath)) {
    if (isset($_GET['download'])) {
        // Скачиваем файл
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($fullPath) . '"');
        header('Content-Length: ' . filesize($fullPath));
        readfile($fullPath);
        exit;
    }
    
    // Просто информация о файле
    echo json_encode([
        'isFile' => true,
        'downloadUrl' => "/api/files.php?path=" . urlencode($requestPath) . "&download=1",
        'name' => basename($fullPath),
        'size' => filesize($fullPath)
    ]);
    exit;
}

// Это директория — сканируем
$files = scandir($fullPath);
$relativePath = $requestPath;

// Разделяем папки и файлы
$folders = [];
$filesList = [];

foreach ($files as $file) {
    if ($file == '.' || $file == '..') continue;
    
    $filePath = $fullPath . '/' . $file;
    if (is_dir($filePath)) {
        $folders[] = ['name' => $file, 'isDir' => true];
    } else {
        $filesList[] = [
            'name' => $file,
            'size' => filesize($filePath),
            'isDir' => false
        ];
    }
}

// Сортируем
usort($folders, function($a, $b) {
    return strcasecmp($a['name'], $b['name']);
});
usort($filesList, function($a, $b) {
    return strcasecmp($a['name'], $b['name']);
});

$result = [
    'currentPath' => $relativePath,
    'files' => array_merge($folders, $filesList)
];

if (count($result['files']) == 0) {
    $result['files'] = [['name' => '📁 Папка пуста', 'isDir' => true]];
}

echo json_encode($result);
?>