<?php

namespace kernel\app_modules\tag\services;

use kernel\app_modules\tag\models\Tag;
use kernel\app_modules\tag\models\TagEntity;
use kernel\FormModel;
use kernel\helpers\Debug;
use kernel\helpers\Slug;

class TagEntityService
{

    public function create(FormModel $form_model): false|TagEntity
    {
        $model = new TagEntity();
        $model->tag_id = $form_model->getItem('tag_id');
        $model->entity = $form_model->getItem('entity');
        $model->entity_id = $form_model->getItem('entity_id');
        if ($model->save()){
            return $model;
        }

        return false;
    }

    public function update(FormModel $form_model, TagEntity $tag): false|TagEntity
    {
        $tag->tag_id = $form_model->getItem('tag_id');
        $tag->entity = $form_model->getItem('entity');
        $tag->entity_id = $form_model->getItem('entity_id');

        if ($tag->save()){
            return $tag;
        }

        return false;
    }

    public static function getTagsByEntity(string $entity, int $entity_id): array
    {
        $tags= TagEntity::where("entity_id", $entity_id)->where("entity", $entity)->get();
        $value = [];
        foreach ($tags as $tag) {
            $value[$tag->id] = $tag->tag->label;
        }

        return $value;
    }

}