<?php

namespace App\Controllers;

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

class GroupingController
{
    public function getAll(Request $request, Response $response)
    {
        $params = $request->getQueryParams();
        $parentId = $params['parentId'] ?? null;

        $model = new Grouping();
        $groupings = $model->getAll($parentId);

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

    public function create(Request $request, Response $response)
    {
        $data = $request->getParsedBody();
        $grouping = $data['grouping'] ?? '';
        $parentId = $data['parentId'] ?? 0;

        if (empty($grouping)) {
            $response->getBody()->write(json_encode(ApiResponse::fail('分组名称不能为空'), JSON_UNESCAPED_UNICODE));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        $model = new Grouping();
        $id = $model->create($grouping, $parentId);
        $created = $model->findById($id);

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

    public function update(Request $request, Response $response, $args)
    {
        $id = $args['id'];
        $data = $request->getParsedBody();
        $grouping = $data['grouping'] ?? '';

        if (empty($grouping)) {
            $response->getBody()->write(json_encode(ApiResponse::fail('分组名称不能为空'), JSON_UNESCAPED_UNICODE));
            return $response->withHeader('Content-Type', 'application/json; charset=utf-8')->withStatus(400);
        }

        $model = new Grouping();
        $model->update($id, $grouping);
        $updated = $model->findById($id);

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

    public function delete(Request $request, Response $response, $args)
    {
        $id = $args['id'];

        $model = new Grouping();
        $model->delete($id);

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