<?php
$basePath = __DIR__ . '/../../storage';

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

function index($currentPath) {
	$basePath = __DIR__ . '/../../storage';
    // Получаем текущую директорию
    $currentPath = urldecode($currentPath);
    $currentPath = str_replace('..', '', $currentPath);
    $currentPath = ltrim($currentPath, '/');

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

    if (strlen(realpath($fullPath)) === 0) {
		return json_encode([
            'error' => "Нет такого файла или каталога $currentPath",
		]);
	}
	// Проверка безопасности
    else if (strpos(realpath($fullPath), realpath($basePath)) !== 0) {
        return json_encode([
            'error' => "Доступ запрещен $currentPath",
		]);
    }

	if (!is_dir($fullPath)) {
		return json_encode([
            'isFolder' => false,
            'name' => basename($currentPath),
            'path' => $currentPath,
		]);
	}

	$files = scandir($fullPath);
	$parentDir = dirname($currentPath);
	if ($parentDir == '.') $parentDir = '';

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

	foreach ($files as $file) {
		if ($file == '.' || $file == '..') continue;

		$filePath = $fullPath . '/' . $file;
		if (is_dir($filePath)) {
			$foldersList[] = $file;
		} else {
			$filesList[] = $file;
		}
	}

	// Сортируем
	sort($foldersList, SORT_STRING | SORT_FLAG_CASE);
	sort($filesList, SORT_STRING | SORT_FLAG_CASE);
	
	return json_encode([
		'isFolder' => true,
		'name' => basename($currentPath),
		'path' => $currentPath,
		'parentDir' => $parentDir,
		'foldersList' => $foldersList,
		'filesList' => $filesList,
	]);
}
?>