<?php

namespace Modules\City\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\City\Interfaces\CityRepositoryInterface;
use Modules\City\Models\City;
use Modules\City\Models\CityDescription;

class CityRepository implements CityRepositoryInterface
{
    public function get(array $request)
    {
        $builder = City::query()
            ->join('city_descriptions AS sd', 'cities.id', 'sd.city_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'cities.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return CityDescription::where('city_id', $id)
            ->join('languages', 'languages.id', 'city_descriptions.language_id')
            ->join('cities', 'cities.id', 'city_descriptions.city_id')
            ->select(['city_descriptions.*', 'languages.local','cities.*'])->get();
    }

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

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

    public function create(array $request): City
    {
        $city = City::create($request);
        return $city;
    }

    public function update(array $request, ?City $city): City
    {
        $city->update($request);

        return $city;
    }

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

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

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

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