<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

final class UploadFilesController extends BaseFileManagerController
{

    public function index(\Symfony\Component\HttpFoundation\Request $request): \Symfony\Component\HttpFoundation\JsonResponse
    {
        $folderPath = $request->request->get('folderPath', '');
        $folderPath = $this->sanitizePath($folderPath);

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

        if (!$this->isPathInsideBase($uploadPath)) {
            return new \Symfony\Component\HttpFoundation\JsonResponse([
                'error' => 'Invalid upload path.'
            ], 400);
        }

        if (!file_exists($uploadPath)) {
            mkdir($uploadPath, 0777, true);
        }

        $uploadedFiles = [];
        $errors = [];

        $files = $request->files->get('file');

        if ($files) {
            foreach ($files as $file) {
                $filename = $file->getClientOriginalName();
                $filename = basename($filename);

                try {
                    $file->move($uploadPath, $filename);
                    $uploadedFiles[] = $filename;
                } catch (\Exception $e) {
                    $errors[] = 'Failed to upload ' . $filename;
                }
            }
        }

        return new \Symfony\Component\HttpFoundation\JsonResponse([
            'message' => 'Upload complete.',
            'uploaded' => $uploadedFiles,
            'errors' => $errors
        ]);
    }

}