<?php

namespace Modules\Faq\Services;

use Illuminate\Http\Request;
use Modules\Faq\Interfaces\FaqRepositoryInterface;
use Modules\Faq\Models\Faq;

class FaqService
{
    private FaqRepositoryInterface $faqRepository;

    public function __construct(FaqRepositoryInterface $faqRepository)
    {
        $this->faqRepository = $faqRepository;
    }

    public function get(array $request = [])
    {
        $builder = $this->faqRepository->get($request);

        if (@$request['question']) {
            $builder->where('sd.question', 'LIKE', '%' . $request['question'] . '%');
        }

        if (!is_null($request['type'])) {
            $builder->where('faqs.status', $request['type']);
        }

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

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

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

        if (@$request['paginate']) {
            $faqs = $builder->paginate(50);
        } elseif (@$request['api']) {
            $faqs = $builder;
        } else {
            $faqs = $builder->cursor();
        }
        return $faqs;
    }
    public function checkItem($id)
    {
        $faq = $this->faqRepository->checkItem($id);
        return $faq;
    }

    public function getItem($id)
    {
        $faq = $this->checkItem($id);
        $faqDescription = $this->faqRepository->getItem($id);
        foreach ($faqDescription as $row) {
            $faq[$row->local] = $row;
        }
        return $faq;
    }

    public function getItemTrashed($id)
    {
        $faq = $this->faqRepository->getItemTrashed($id);
        return $faq;
    }

    public function create(array $request): Faq
    {
        $faq = $this->faqRepository->create($request);
        $this->faqRepository->saveData($request, $faq->id);
        return $faq;
    }
    public function update(array $request, int $id): Faq
    {
        $faq = $this->checkItem($id);


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