<?php

namespace Modules\Gallery\Repositories;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Gallery\Models\Gallery;
use Modules\Gallery\Models\GalleryDescription;
use Modules\Gallery\Interfaces\GalleryRepositoryInterface;

class GalleryRepository implements GalleryRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Gallery::query()
            ->join('gallery_descriptions AS sd', 'galleries.id', 'sd.gallery_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'galleries.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return GalleryDescription::where('gallery_id', $id)
            ->join('languages', 'languages.id', 'gallery_descriptions.language_id')
            ->join('galleries', 'galleries.id', 'gallery_descriptions.gallery_id')
            ->select(['gallery_descriptions.*', 'languages.local','galleries.*'])->get();
    }

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

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

    public function create(array $request): Gallery
    {
        $gallery = Gallery::create($request);
        return $gallery;
    }

    public function update(array $request, ?Gallery $gallery): Gallery
    {
        $gallery->update($request);

        return $gallery;
    }

    public function saveData(array $request, int $gallery_id ) :void
    {
        GalleryDescription::where('gallery_id', $gallery_id)->delete();
        foreach (languages() as $lang) {
            $data =
            [
                'gallery_id'=> $gallery_id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
            ];
            GalleryDescription::create($data);
        }
    }

    /**
     * Remove the specified gallery from storage.
     * @param Gallery $gallery
     * @return void
     */
    public function destroy(Gallery $gallery) :void
    {
        $gallery->delete();
    }

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

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

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