<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace Applications\sample\modules\category\core;

use Core\service\BaseCoreService;
use Applications\sample\modules\category\repository\CategoryRepository;

/**
 * Core Category Service
 * @package Applications\sample\modules\category\core
 */
class CoreCategoryService extends BaseCoreService
{
    /**
     * 创建分类
     * @param array $payload 分类数据
     * @return array
     */
    public function create(array $payload): array
    {
        $name = trim((string)($payload['name'] ?? ''));
        if ($name === '') {
            return ['code' => 1, 'msg' => '分类名称不能为空'];
        }
        $data = [
            'name' => $name,
            'sort' => (int)($payload['sort'] ?? 0),
            'status' => (int)($payload['status'] ?? 1) ? 1 : 0,
        ];
        $cat = $this->repo()->create($data);
        return ['code' => 0, 'msg' => '创建成功', 'data' => ['id' => $cat->id]];
    }


    /**
     * 更新分类
     * @param int $id 分类ID
     * @param array $payload 更新数据
     * @return array
     */
    public function update(int $id, array $payload): array
    {
        $cat = $this->repo()->findById($id);
        if (!$cat) {
            return ['code' => 1, 'msg' => '分类不存在'];
        }
        $data = [
            'name' => trim((string)($payload['name'] ?? $cat->name)),
            'sort' => (int)($payload['sort'] ?? $cat->sort),
            'status' => (int)($payload['status'] ?? $cat->status) ? 1 : 0,
        ];
        $this->repo()->save($cat, $data);
        return ['code' => 0, 'msg' => '更新成功', 'data' => ['id' => $id]];
    }


    /**
     * 删除分类
     * @param int $id 分类ID
     * @return array
     */
    public function delete(int $id): array
    {
        if ($id <= 0) return ['code' => 1, 'msg' => '参数错误'];
        $this->repo()->deleteById($id);
        return ['code' => 0, 'msg' => '删除成功'];
    }

    /**
     * 获取分类仓库实例
     * @return CategoryRepository
     */
    private function repo(): CategoryRepository
    {
        return $this->app->make(CategoryRepository::class);
    }
}
