<?php

namespace Modules\Area\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Area\Interfaces\AreaRepositoryInterface;
use Modules\Area\Models\Area;
use Modules\Area\Models\AreaDescription;

class AreaRepository implements AreaRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Area::query()
            ->join('area_descriptions AS sd', 'areas.id', 'sd.area_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'areas.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return AreaDescription::where('area_id', $id)
            ->join('languages', 'languages.id', 'area_descriptions.language_id')
            ->join('areas', 'areas.id', 'area_descriptions.area_id')
            ->select(['area_descriptions.*', 'languages.local','areas.*'])->get();
    }

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

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

    public function create(array $request): Area
    {
        $area = Area::create($request);
        return $area;
    }

    public function update(array $request, ?Area $area): Area
    {
        $area->update($request);

        return $area;
    }

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

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

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

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