<?php

namespace Modules\Faq\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Faq\Interfaces\FaqRepositoryInterface;
use Modules\Faq\Models\Faq;
use Modules\Faq\Models\FaqDescription;

class FaqRepository implements FaqRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Faq::orderBy('id', 'DESC')
            ->join('faq_descriptions AS sd', 'faqs.id', 'sd.faq_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.question', 'faqs.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return FaqDescription::where('faq_id', $id)
            ->join('languages', 'languages.id', 'faq_descriptions.language_id')
            ->join('faqs', 'faqs.id', 'faq_descriptions.faq_id')
            ->select(['faq_descriptions.*', 'languages.local','faqs.*'])->get();
    }

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

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

    public function create(array $request): Faq
    {
        $faq = Faq::create($request);
        return $faq;
    }

    public function update(array $request, ?Faq $faq): Faq
    {
        $faq->update($request);

        return $faq;
    }

    public function saveData(array $request, int $faq_id ) :void
    {
        FaqDescription::where('faq_id', $faq_id)->delete();
        foreach (languages() as $lang) {
            $data=[
                'faq_id'=> $faq_id,
                'language_id'=> $lang->id,
                'question'=> $request['question_'.$lang->local],
                'answer'=> $request['answer_'.$lang->local],
            ];
            FaqDescription::create($data);
        }
    }
    /**
     * Remove the specified faq from storage.
     * @param Faq $faq
     * @return void
     */
    public function destroy(Faq $faq) :void
    {
        $faq->delete();
    }

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

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

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