<?php

namespace App\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Models\SystemSetting;
use App\Models\RegistrationCode;
use App\Utils\Response as ApiResponse;

class SystemController
{
    /**
     * 获取注册功能状态
     */
    public function getRegistrationStatus(Request $request, Response $response)
    {
        $model = new SystemSetting();
        $enabled = $model->isRegistrationEnabled();

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($enabled)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    /**
     * 切换注册功能状态（需要认证）
     */
    public function toggleRegistration(Request $request, Response $response)
    {
        $data = $request->getParsedBody();
        $enabled = $data['enabled'] ?? false;

        $model = new SystemSetting();
        $model->setRegistrationEnabled($enabled);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success(null, '设置成功')));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }

    /**
     * 生成注册码（需要认证）
     */
    public function generateRegistrationCode(Request $request, Response $response)
    {
        $userId = $request->getAttribute('userId');

        if (!$userId) {
            $response->getBody()->write(ApiResponse::json(ApiResponse::fail('未授权')));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(401);
        }

        $model = new RegistrationCode();
        $code = $model->generateCode($userId);

        $response->getBody()->write(ApiResponse::json(ApiResponse::success($code)));
        return $response->withHeader('Content-Type', 'application/json; charset=utf-8');
    }
}
