<?php

namespace Modules\Option\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Option\Interfaces\OptionRepositoryInterface;
use Modules\Option\Models\Option;
use Modules\Option\Models\OptionDescription;

class OptionRepository implements OptionRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Option::query()
            ->join('option_descriptions AS sd', 'options.id', 'sd.option_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'options.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return OptionDescription::where('option_id', $id)
            ->join('languages', 'languages.id', 'option_descriptions.language_id')
            ->join('options', 'options.id', 'option_descriptions.option_id')
            ->select(['option_descriptions.*', 'languages.local','options.*'])->get();
    }

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

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

    public function create(array $request): Option
    {
        $option = Option::create($request);
        return $option;
    }

    public function update(array $request, ?Option $option): Option
    {
        $option->update($request);

        return $option;
    }

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

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

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

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