<?php

namespace Modules\Region\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Region\Interfaces\RegionRepositoryInterface;
use Modules\Region\Models\Region;
use Modules\Region\Models\RegionDescription;

class RegionRepository implements RegionRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Region::orderBy('id', 'DESC')
            ->join('region_descriptions AS sd', 'regions.id', 'sd.region_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'regions.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return RegionDescription::where('region_id', $id)
            ->join('languages', 'languages.id', 'region_descriptions.language_id')
            ->join('regions', 'regions.id', 'region_descriptions.region_id')
            ->select(['region_descriptions.*', 'languages.local','regions.*'])->get();
    }

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

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

    public function create(array $request): Region
    {
        $region = Region::create($request);
        return $region;
    }

    public function update(array $request, ?Region $region): Region
    {
        $region->update($request);

        return $region;
    }

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

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

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

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