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

use app\repository\BaseRepository;
use Applications\sample\modules\article\model\Article;
use think\facade\Db;

/**
 * Article Repository
 * @package Applications\sample\modules\article\repository
 */
class ArticleRepository extends BaseRepository
{
    /**
     * 后台分页列表（含分类筛选 + 关联分类名）
     */
    public function paginateForAdmin(array $filters, int $limit): array
    {
        $query = Article::order('id', 'desc');

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $query->where('title', 'like', "%{$keyword}%");
        }
        $categoryId = $filters['category_id'] ?? '';
        if ($categoryId !== '' && $categoryId !== null) {
            $query->where('category_id', (int)$categoryId);
        }
        $status = $filters['status'] ?? '';
        if ($status !== '' && $status !== null) {
            $query->where('status', (int)$status);
        }

        $result = $query->paginate($limit);
        // 批量注入分类名
        $categoryIds = array_unique(array_column($result->items(), 'category_id'));
        $categories = \think\facade\Db::name('sample_category')->whereIn('id', $categoryIds)->column('name', 'id');
        foreach ($result as $item) {
            $item->category_name = $categories[$item->category_id] ?? '';
        }

        return $result->toArray();
    }

    /**
     * C端分页列表（仅已发布，支持分类筛选）
     */
    public function paginateForApi(array $filters, int $limit): array
    {
        $query = Article::where('status', 1)->order('id', 'desc');

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $query->where('title', 'like', "%{$keyword}%");
        }
        $categoryId = $filters['category_id'] ?? '';
        if ($categoryId !== '' && $categoryId !== null) {
            $query->where('category_id', (int)$categoryId);
        }

        $result = $query->paginate($limit);
        $categoryIds = array_unique(array_column($result->items(), 'category_id'));
        $categories = \think\facade\Db::name('sample_category')->whereIn('id', $categoryIds)->column('name', 'id');
        foreach ($result as $item) {
            $item->category_name = $categories[$item->category_id] ?? '';
        }

        return $result->toArray();
    }


    /**
     * 根据ID查找文章
     * @param int $id 文章ID
     * @return Article|null
     */
    public function findById(int $id): ?Article
    {
        $article = Article::find($id);
        return $article instanceof Article ? $article : null;
    }


    /**
     * 根据标题查找文章
     * @param string $title 文章标题
     * @param int $excludeId 排除的文章ID
     * @return Article|null
     */
    public function findByTitle(string $title, int $excludeId = 0): ?Article
    {
        $query = Article::where('title', $title);
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        $article = $query->find();
        return $article instanceof Article ? $article : null;
    }


    /**
     * 创建文章
     * @param array $payload 文章数据
     * @return Article
     */
    public function create(array $payload): Article
    {
        return Article::create($payload);
    }


    /**
     * 保存文章
     * @param Article $article 文章模型实例
     * @param array $payload 更新数据
     * @return void
     */
    public function save(Article $article, array $payload = []): void
    {
        $article->save($payload);
    }


    /**
     * 判断文章是否存在
     * @param int $id 文章ID
     * @return bool
     */
    public function exists(int $id): bool
    {
        return Article::where('id', $id)->count() > 0;
    }


    /**
     * 根据ID删除文章
     * @param int $id 文章ID
     * @return void
     */
    public function deleteById(int $id): void
    {
        Article::destroy($id);
    }
}
