<?php
// services/FileManagerService.php
class FileManagerService {
    private $fileStorageDir = __DIR__ . '/../../storage';
    
    public function __construct() {
        if (!file_exists($this->fileStorageDir)) {
            mkdir($this->fileStorageDir, 0777, true);
        }
    }

	public function getPathInfo($path) {
		$path = urldecode($path);
		$path = str_replace('..', '', $path);
		$path = ltrim($path, '/');
		$fullPath = $this->fileStorageDir . ($path ? '/' . $path : '');
		
		if (strlen(realpath($fullPath)) === 0) {
			return json_encode([
				'error' => "Нет такого файла или каталога $path",
			]);
		}
		// Проверка безопасности
		else if (strpos(realpath($fullPath), realpath($this->fileStorageDir)) !== 0) {
			return json_encode([
				'error' => "Доступ запрещен $path",
			]);
		}
		
		$parentDir = dirname($path);
		if ($parentDir == '.') $parentDir = '';

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

		$files = scandir($fullPath);
		// Разделяем папки и файлы
		$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($path),
			'path' => $path,
			'parentDir' => $parentDir,
			'foldersList' => $foldersList,
			'filesList' => $filesList,
		]);
	}
	
	public function getPathTree($path, $result, $relativePath = '') {
		// Если пришел реальный абсолютный путь, делаем относительный от $this->fileStorageDir
		if (file_exists($path)) {
			$path = substr($path, strlen(realpath($this->fileStorageDir)));
		}
		
		$pathInfo = json_decode($this->getPathInfo($path), true);
		
		// Если ошибка, возвращаем текущий результат
		if (isset($pathInfo['error'])) {
			return $result;
		}
		
		// Путь относительно запрошенной папки
		$newRelativePath = $relativePath ? $relativePath . '/' . $pathInfo['name'] : $pathInfo['name'];
		
		$result[] = [
			'isFolder' => $pathInfo['isFolder'],
			'name' => $pathInfo['name'],
			'path' => $pathInfo['path'], // полный путь от $this->fileStorageDir
			'relativePath' => $relativePath, // путь относительно изначального $path
		];
		
		if ($pathInfo['isFolder']) {
			if (!empty($pathInfo['filesList'])) {
				foreach ($pathInfo['filesList'] as $file) {
					$newPath = $pathInfo['path'] ? $pathInfo['path'] . '/' . $file : $file;
					$result = $this->getPathTree($newPath, $result, $newRelativePath);
				}
			}
			if (!empty($pathInfo['foldersList'])) {
				foreach ($pathInfo['foldersList'] as $folder) {
					$newPath = $pathInfo['path'] ? $pathInfo['path'] . '/' . $folder : $folder;
					$result = $this->getPathTree($newPath, $result, $newRelativePath);
				}
			}
		}
		return $result;
	}
}
?>