<?php

namespace Modules\Banner\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Banner\Interfaces\BannerRepositoryInterface;
use Modules\Banner\Models\Banner;
use Modules\Banner\Models\BannerDescription;

class BannerRepository implements BannerRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Banner::query()
            ->join('banner_descriptions AS sd', 'banners.id', 'sd.banner_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'banners.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return BannerDescription::where('banner_id', $id)
            ->join('languages', 'languages.id', 'banner_descriptions.language_id')
            ->join('banners', 'banners.id', 'banner_descriptions.banner_id')
            ->select(['banner_descriptions.*', 'languages.local','banners.*'])->get();
    }

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

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

    public function create(array $request): Banner
    {
        $banner = Banner::create($request);
        return $banner;
    }

    public function update(array $request, ?Banner $banner): Banner
    {
        $banner->update($request);

        return $banner;
    }

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

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

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

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