<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class ListFoldersController extends BaseFileManagerController
{

    public function index(): \Symfony\Component\HttpFoundation\JsonResponse
    {
        $folderStructure = $this->generateFolderStructure($this->basePath);

        return new \Symfony\Component\HttpFoundation\JsonResponse([
            'folders' => $folderStructure
        ]);
    }

    public function generateFolderStructure(string $directoryPath, string $parentPath = ''): array
    {
        $folders = [];

        if (!is_dir($directoryPath)) {
            return [];
        }

        $items = scandir($directoryPath);

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }

            $itemPath = $directoryPath . '/' . $item;
            $relativePath = trim($parentPath . '/' . $item, '/');

            if (is_dir($itemPath)) {
                $subfolders = $this->generateFolderStructure(
                    $itemPath,
                    $relativePath
                );

                $folders[] = [
                    'name' => $item,
                    'path' => $relativePath,
                    'subfolders' => $subfolders
                ];
            }
        }

        return $folders;
    }

}