<?php

namespace app\controller\admin;

use app\extra\basic\Base;
use app\middleware\AuthMiddleware;
use app\model\system\SystemConfig;
use DI\Attribute\Inject;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Middleware;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;

#[Controller(prefix: "/api/pages"),Middleware(AuthMiddleware::class)]
class Pages extends Base
{

    #[Inject]
    protected SystemConfig $model;

    #[Route(path: "list",methods: "get")]
    public function getPageList(): Response
    {
        try {
            $data = $this->model->where("type","page")->field("type,desc,name")->select();
            return success("pages",$data->toArray());
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    #[Route(path: "detail",methods: "get")]
    public function getPageDetail(): Response
    {
        try {
            $param = $this->_valid([
                "name.require"  => trans("empty.require")
            ]);
            if (!is_array($param)) return error($param);
            $data = $this->model->where("type","page")->where("name",$param['name'])->findOrEmpty();
            if ($data->isEmpty()) return errorTrans("empty.data");
            return success("pages",$data->toArray());
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    #[Route(path: "save",methods: "post")]
    public function setPageData(Request $request): Response
    {
        try {
            $param = $request->post();
            $param['type'] = "page";
            $data = $this->model->where("type","page")->where("name",$param['name'])->findOrEmpty();
            if (!isset($param['id'])) {
                if (!$data->isEmpty()) return errorTrans("empty.data");
            }
            $state = $this->model->setAutoData($param);
            if (!$state) return errorTrans("error.data");
            return successTrans("success.data");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

}