<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class ListFilesController extends BaseFileManagerController
{

    public function index(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\JsonResponse
    {
        if ($request->isMethod('POST')) {
            $data = json_decode($request->getContent(), true);
            $folderPath = $data['folderPath'] ?? '';
        } else {
            $folderPath = $request->query->get('folderPath', '');
        }

        $fileList = $this->getFilesAndFolders($folderPath);

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

    public function getFilesAndFolders(string $folderPath = ''): array
    {
        $folderPath = $this->sanitizePath($folderPath);

        $fullPath = $this->basePath . '/' . $folderPath;

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

        $items = scandir($fullPath);
        $items = array_filter($items, fn($item) => !str_starts_with($item, '.') && $item !== 'thumbs'); // Vyfiltrujeme skryté soubory a thumbnaily.

        $folders = [];
        $files = [];

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

            $itemPath = $fullPath . '/' . $item;
            $isDirectory = is_dir($itemPath);

            $url = $this->baseUrl . '/' . trim($folderPath . '/' . $item, '/');
            $url = str_replace('//', '/', $url);
            $url = str_replace(':/', '://', $url);

            $itemObj = [
                'name' => $item,
                'type' => $isDirectory ? 'folder' : 'file',
                'url' => $url,
                'created' => date('Y-m-d H:i:s', filectime($itemPath)),
                'modified' => date('Y-m-d H:i:s', filemtime($itemPath)),
                'size' => $isDirectory ? '-' : $this->getFileSize(filesize($itemPath))
            ];

            if ($isDirectory) {
                $folders[] = $itemObj;
            } else {
                $files[] = $itemObj;
            }
        }

        usort($files, function ($a, $b) {
            return strtotime($b['modified']) - strtotime($a['modified']);
        });

        return array_merge($folders, $files);
    }

}