<?php

namespace Modules\School\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\School\Interfaces\SchoolRepositoryInterface;
use Modules\School\Models\School;
use Modules\School\Models\SchoolDescription;

class SchoolRepository implements SchoolRepositoryInterface
{
    public function get(array $request)
    {
        $builder = School::orderBy('id', 'DESC')
            ->join('school_descriptions AS sd', 'schools.id', 'sd.school_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'schools.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return SchoolDescription::where('school_id', $id)
            ->join('languages', 'languages.id', 'school_descriptions.language_id')
            ->join('schools', 'schools.id', 'school_descriptions.school_id')
            ->select(['school_descriptions.*', 'languages.local','schools.*'])->get();
    }

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

    public function getItemByCode(string $code)
    {
        return School::where('code',$code)->first();
    }

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

    public function create(array $request): School
    {
        $school = School::create($request);
        return $school;
    }

    public function update(array $request, ?School $school): School
    {
        $school->update($request);

        return $school;
    }

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

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

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

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