<?php

namespace Modules\Tag\Services;

use Illuminate\Http\Request;
use Modules\Tag\Interfaces\TagRepositoryInterface;
use Modules\Tag\Models\Tag;

class TagService
{
    private TagRepositoryInterface $tagRepository ;

    public function __construct(TagRepositoryInterface $tagRepository)
    {
        $this->tagRepository = $tagRepository;
    }

    public function get(array $request)
    {
        $builder = $this->tagRepository->get($request);

        if (@$request['title'])
        {
            $builder->where('sd.title', 'LIKE', '%'.$request['title'].'%');
        }
        if (@$request['date_from'])
        {
            $builder->whereDate('tags.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to'])
        {
            $builder->whereDate('tags.created_at', '<=', $request['date_to']);
        }

        if (isset($request['status']))
        {
            if (@$request['status'] == 0)
            {
                $builder->onlyTrashed();
            }
        }

        if (@$request['orderBy'])
        {
            $builder->orderBy($request['orderBy']['key'],$request['orderBy']['value']);
        }
        else
        {
            $builder->orderBy('id','DESC');
        }

        if (@$request['paginate']) {
            $tags= $builder->paginate(50);
        }else{
            $tags=$builder->cursor();
        }
        return $tags;
    }
    public function checkItem($id)
    {
        $tag = $this->tagRepository->checkItem($id);
        return $tag;
    }

    public function getItem($id)
    {
        $tag = $this->checkItem($id);
        $tagDescription = $this->tagRepository->getItem($id);
        foreach ($tagDescription as $row) {
            $tag[$row->local]= $row;
        }
        return $tag;
    }

    public function getItemTrashed($id)
    {
        $tag = $this->tagRepository->getItemTrashed($id);
        return $tag;
    }

    public function create(array $request): Tag
    {
        $tag = $this->tagRepository->create($request);
        $this->tagRepository->saveData($request,$tag->id);
        return $tag;
    }
    public function update(array $request,int $id): Tag
    {
        $tag = $this->checkItem($id);


        $tag = $this->tagRepository->update($request,$tag);
        $this->tagRepository->saveData($request,$tag->id);
        return $tag;
    }
    public function destroy(int $id): void
    {
        $tag = $this->checkItem($id);
        if ($tag)
        {
            $this->tagRepository->destroy($tag);
        }
        else
        {
            $tag = $this->getItemTrashed($id);
            $this->tagRepository->restore($tag);
        }
    }
    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1)
        {
            $this->tagRepository->destroyAll($request['ids']);
        }
        else
        {
            $this->tagRepository->restoreAll($request['ids']);
        }
    }
}
