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

use app\repository\BaseRepository;
use Applications\sample\plugins\notice\model\Notice;

/**
 * 示例应用公告插件仓储
 * Class NoticeRepository
 * @package Applications\sample\plugins\notice\repository
 */
class NoticeRepository extends BaseRepository
{
    /**
     * 获取分页列表
     * @param array $filters
     * @param int $page
     * @param int $limit
     * @return array
     */
    public function paginateForAdmin(array $filters, int $page, int $limit): array
    {
        $query = Notice::order('sort', 'asc')->order('id', 'desc');

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $query->where(function ($builder) use ($keyword) {
                $builder->where('title', 'like', "%{$keyword}%")
                    ->whereOr('code', 'like', "%{$keyword}%");
            });
        }

        $status = $filters['status'] ?? null;
        if ($status !== '' && $status !== null) {
            $query->where('status', (int)$status);
        }

        $page = max($page, 1);
        $limit = max($limit, 1);

        return $query->paginate([
            'list_rows' => $limit,
            'page' => $page,
        ])->toArray();
    }

    /**
     * 根据编码判断是否存在
     * @param string $code
     * @param int $excludeId
     * @return bool
     */
    public function existsCode(string $code, int $excludeId = 0): bool
    {
        $query = Notice::where('code', $code);
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }

        return $query->count() > 0;
    }

    /**
     * 根据 ID 查询记录
     * @param int $id
     * @return Notice|null
     */
    public function findById(int $id): ?Notice
    {
        $row = Notice::find($id);
        return $row instanceof Notice ? $row : null;
    }

    /**
     * 创建记录
     * @param array $payload
     * @return Notice
     */
    public function create(array $payload): Notice
    {
        return Notice::create($payload);
    }

    /**
     * 保存记录
     * @param Notice $notice
     * @param array $payload
     * @return void
     */
    public function save(Notice $notice, array $payload = []): void
    {
        $notice->save($payload);
    }

    /**
     * 删除记录
     * @param int $id
     * @return bool
     */
    public function deleteById(int $id): bool
    {
        return Notice::destroy($id) > 0;
    }
}
