<?php

namespace Modules\Tag\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Tag\Interfaces\TagRepositoryInterface;
use Modules\Tag\Models\Tag;
use Modules\Tag\Models\TagDescription;

class TagRepository implements TagRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Tag::query()
            ->join('tag_descriptions AS sd', 'tags.id', 'sd.tag_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'tags.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return TagDescription::where('tag_id', $id)
            ->join('languages', 'languages.id', 'tag_descriptions.language_id')
            ->join('tags', 'tags.id', 'tag_descriptions.tag_id')
            ->select(['tag_descriptions.*', 'languages.local','tags.*'])->get();
    }

    public function checkItem(int $id)
    {
        return Tag::find($id);
    }

    public function getItemTrashed(int $id)
    {
        $tag = Tag::onlyTrashed()->find($id);
        return $tag ;
    }

    public function create(array $request): Tag
    {
        $tag = Tag::create($request);
        return $tag;
    }

    public function update(array $request, ?Tag $tag): Tag
    {
        $tag->update($request);

        return $tag;
    }

    public function saveData(array $request, int $tag_id ) :void
    {
        TagDescription::where('tag_id', $tag_id)->delete();
        foreach (languages() as $lang) {
            $data=[
                'tag_id'=> $tag_id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
            ];
            TagDescription::create($data);
        }
    }
    /**
     * Remove the specified tag from storage.
     * @param Tag $tag
     * @return void
     */
    public function destroy(Tag $tag) :void
    {
        $tag->delete();
    }

    /**
     * Remove several tags by IDs.
     *
     * @param array $request
     * @return void
     */
    public function destroyAll(array $ids) :void
    {
         Tag::whereIn('id', $ids)->delete();
    }

    /**
     * Restore the specified tag from storage.
     *
     * @param Tag $tag
     * @return void
     */
    public function restore(Tag $tag) :void
    {
        $tag->restore();
    }

    /**
     * Restore several tags by IDs.
     *
     * @param array $request
     * @return void
     */
    public function restoreAll(array $ids) :void
    {
        Tag::whereIn('id', $ids)->onlyTrashed()->restore();
    }
}
