<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class MoveFilesController extends BaseFileManagerController
{

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

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

        foreach ($selectedItems as $item) {
            $item = basename($item);
            $sourcePath = $this->basePath . '/' . trim($folderPath . '/' . $item, '/');
            $destinationPath = $this->basePath . '/' . trim($targetPath . '/' . $item, '/');

            if (!$this->isPathInsideBase($sourcePath) || !$this->isPathInsideBase(dirname($destinationPath))) {
                continue;
            }

            if (!file_exists($sourcePath)) {
                continue;
            }

            $destinationDir = dirname($destinationPath);
            if (!is_dir($destinationDir)) {
                mkdir($destinationDir, 0777, true);
            }

            rename($sourcePath, $destinationPath);
        }

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

}