<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use Webman\Http\Request;
use support\Response;

class Ajax extends Frontend
{
    protected array $noNeedLogin = ['area', 'buildSuffixSvg'];
    protected array $noNeedPermission = ['upload'];

    public function upload(Request $request): Response
    {
        $response = $this->initializeFrontend($request);
        if ($response !== null) return $response;

        $file = $request->file('file');
        if (!$file) {
            return $this->error(__('No files were uploaded'));
        }
        $file = new \app\common\library\upload\WebmanUploadedFile($file);
        $driver = $request->get('driver', $request->post('driver', 'local'));
        $topic = $request->get('topic', $request->post('topic', 'default'));

        try {
            $upload = new \app\common\library\Upload();
            $attachment = $upload
                ->setFile($file)
                ->setDriver($driver)
                ->setTopic($topic)
                ->upload(null, 0, $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
        } catch (\Throwable $e) {
            return $this->error($e->getMessage());
        }

        return $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    public function area(Request $request): Response
    {
        $response = $this->initializeFrontend($request);
        if ($response !== null) return $response;

        return $this->success('', get_area($request));
    }

    public function buildSuffixSvg(Request $request): Response
    {
        $response = $this->initializeFrontend($request);
        if ($response !== null) return $response;

        $suffix = $request->get('suffix', $request->post('suffix', 'file'));
        $background = $request->get('background', $request->post('background'));
        $content = build_suffix_svg((string) $suffix, (string) $background);
        return response($content, 200, [
            'Content-Length' => strlen($content),
            'Content-Type' => 'image/svg+xml'
        ]);
    }
}
