<?php
namespace admin\Controllers;

class FilemanagerController
{
    private const RFM_KEY_TTL = 1200; // 20 min
    private const FILEMANAGER_DIALOG_PATH = '/libraries/filemanager-9.14.2/dialog.php';

    public function draw(): string
    {
        $akey = $this->ensureFilemanagerAccessKey();
        $filemanagerUrl = $this->buildFilemanagerUrl($akey);

        return \Shared\Tpl\Tpl::view('filemanager/filemanager', [
            'filemanager_url' => $filemanagerUrl,
        ]);
    }

    private function ensureFilemanagerAccessKey(): string
    {
        $expiresAt = (int)($_SESSION['rfm_akey_expires'] ?? 0);
        $existingKey = trim((string)($_SESSION['rfm_akey'] ?? ''));

        if ($existingKey !== '' && $expiresAt >= time()) {
            $_SESSION['rfm_akey_expires'] = time() + self::RFM_KEY_TTL;
            return $existingKey;
        }

        try {
            $newKey = bin2hex(random_bytes(16));
        } catch (\Throwable $e) {
            $newKey = sha1(uniqid('rfm', true));
        }

        $_SESSION['rfm_akey'] = $newKey;
        $_SESSION['rfm_akey_expires'] = time() + self::RFM_KEY_TTL;

        return $newKey;
    }

    private function buildFilemanagerUrl(string $akey): string
    {
        return self::FILEMANAGER_DIALOG_PATH . '?akey=' . rawurlencode($akey);
    }
}

