<?php

namespace Modules\Slider\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Slider\Interfaces\SliderRepositoryInterface;
use Modules\Slider\Models\Slider;
use Modules\Slider\Models\SliderDescription;

class SliderRepository implements SliderRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Slider::query()
            ->join('slider_descriptions AS sd', 'sliders.id', 'sd.slider_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'sliders.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return SliderDescription::where('slider_id', $id)
            ->join('languages', 'languages.id', 'slider_descriptions.language_id')
            ->join('sliders', 'sliders.id', 'slider_descriptions.slider_id')
            ->select(['slider_descriptions.*', 'languages.local','sliders.*'])->get();
    }

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

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

    public function create(array $request): Slider
    {
        $slider = Slider::create($request);
        return $slider;
    }

    public function update(array $request, ?Slider $slider): Slider
    {
        $slider->update($request);

        return $slider;
    }

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

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

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

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