<?php
/*
** Copyright (C) 2021-2026 initMAX s.r.o.
**
** This program is free software: you can redistribute it and/or modify it under the terms of
** the GNU Affero General Public License as published by the Free Software Foundation, version 3.
**
** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License along with this program.
** If not, see <https://www.gnu.org/licenses/>.
**/

namespace Modules\uxMAX\Actions;

use API, CController, CControllerResponseData;
use Modules\uxMAX\Includes\RequestGuard;
use Modules\uxMAX\Module;
use Modules\uxMAX\Services\DatabaseFont;

class Font extends CController {

    use RequestGuard;

    public Module $module;

    protected function init() {
        $this->disableUxmaxRequestGuard();
    }

    public function checkInput() {
        $fields = [
            'i' =>      'int32|required',
            'png' =>    'string|required',
            'format' => 'string|required|in woff,woff2,ttf,otf,eot'
        ];

        $ret = $this->validateInput($fields);

        if (!$ret) {
            $this->setResponse(new CControllerResponseData([
                'error' => _('Invalid input')
            ]));
        }

        return $ret;
    }

    public function checkPermissions() {
        return true;
    }

    public function doAction() {
        $png = API::Image()->get([
            'output' => [],
            'select_image' => true,
            'filter' => ['name' => $this->getInput('png')]
        ])[0];
        $database_font = new DatabaseFont;
        $format = $this->getInput('format');
        $content_type = DatabaseFont::EXTENSION_CONTENT_TYPES[$format] ?? 'application/octet-stream';
        $font = $database_font->getDataBlockFromPng(base64_decode($png['image']), $this->getInput('i'));

        $this->setResponse((new CControllerResponseData([
            'font' => $font,
            'file_name' => $this->getInput('png').'.'.$format,
            'content_type' => $content_type
        ])));
    }
}
