<?php declare(strict_types=1);

namespace App\Engine\Files\FilesJs\Controllers;

abstract class BaseFileManagerController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{

    protected string $basePath;
    protected string $baseUrl;

    public function __construct(
        protected \Symfony\Component\HttpKernel\KernelInterface $kernel,
    ) {
        $this->basePath = "{$this->kernel->getProjectDir()}/public/data/storage";
        $this->baseUrl = ((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/data/storage';

        $this->onConstruct();
    }

    protected function onConstruct(): void
    {
    }

    protected function sanitizePath(string $path): string
    {
        $path = str_replace(['..', '\\'], '', $path);
        return trim($path, '/');
    }

    protected function isPathInsideBase(string $path): bool
    {
        $realBase = realpath($this->basePath);
        $realPath = realpath($path) ?: realpath(dirname($path));

        if ($realPath === false) {
            return false;
        }

        return str_starts_with($realPath, $realBase);
    }

    protected function getFileSize(int $bytes): string
    {
        if ($bytes >= 1024 * 1024) {
            return number_format($bytes / (1024 * 1024), 1) . ' MB';
        }

        return number_format($bytes / 1024, 0) . ' KB';
    }

    protected function generateRandomString(int $length): string
    {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $result = '';
        $maxIndex = strlen($characters) - 1;

        for ($i = 0; $i < $length; $i++) {
            $result .= $characters[rand(0, $maxIndex)];
        }

        return $result;
    }

    protected function generateRandomFileName(string $prefix = ''): string
    {
        $randomString = $this->generateRandomString(5);
        return $prefix ? "{$prefix}-{$randomString}" : "ai-{$randomString}";
    }

}