<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class DeleteFilesController extends BaseFileManagerController
{

    public function index(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\JsonResponse
    {
        $data = json_decode($request->getContent(), true);

        $folderPath = $data['folderPath'] ?? '';
        $selectedItems = $data['selectedItems'] ?? [];
        $folderPath = $this->sanitizePath($folderPath);

        foreach ($selectedItems as $item) {
            $item = $this->sanitizePath($item);
            $itemPath = $this->basePath . '/' . trim($folderPath . '/' . $item, '/');
            if (!$this->isPathInsideBase($itemPath)) {
                continue;
            }

            $this->deleteItem($itemPath);
        }

        return new \Symfony\Component\HttpFoundation\JsonResponse([
            'message' => 'Selected files and folders deleted successfully.'
        ]);
    }

    private function deleteItem(string $itemPath): void
    {
        if (!file_exists($itemPath)) {
            return;
        }

        if (is_file($itemPath)) {
            unlink($itemPath);
            return;
        }

        if (is_dir($itemPath)) {
            $files = scandir($itemPath);

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

                $filePath = $itemPath . '/' . $file;

                $this->deleteItem($filePath);
            }

            rmdir($itemPath);
        }
    }

}