<?php

namespace App\Distributor\Repositories;

use App\Models\SitePagesTag as Model;
use App\Traits\DistSlugTrait;
use Dcat\Admin\Repositories\EloquentRepository;

class SitePagesTag extends EloquentRepository
{
    use DistSlugTrait;
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /*
     * 查找最新的N个标签
     */
    public static function selectOptionsNew($limit=30)
    {
        return Model::where('dist_id', getDistributorId())->orderBy('created_at', 'desc')->limit($limit)->pluck('name', 'id');
    }

    /*
     * 获取一个标签
     */
    public static function getOneById($id)
    {
        return Model::where('id', $id)->where('dist_id', getDistributorId())->first();
    }

    /*
     * 查询全部标签
     */
    public static function all()
    {
        $result =  Model::where('dist_id', getDistributorId())->orderBy('created_at', 'desc')->get();
        return $result;
    }

    /*
     * 处理标签
     */
    public static function handleTags($tags)
    {
        $self = new self();
        $model = new Model();
        if (!is_array($tags)) {
            $tagArray = explode(',', $tags);
        } else {
            $tagArray = $tags;
        }
        $tagArray = array_map('trim', $tagArray);
        $existingTags = $model
            ->whereIn('name', $tagArray)
            ->where('dist_id', getDistributorId())
            ->pluck('id', 'name')  // We also get the name => id mapping
            ->toArray();
        $tagsToInsert = array_diff($tagArray, array_keys($existingTags));
        foreach ($tagsToInsert as $tag) {
            $id = $model->insertGetId([
                'name' => $tag,
                'slug' => $self->generateSlug($tag),
                'dist_id'=> getDistributorId(),
                'created_at' => now(),
                'seo_title' => $tag,
            ]);
            $existingTags[$tag] = $id;
        }
        // Return the ids as an array
        return array_values($existingTags);
    }


}
