<?php

namespace Modules\Chip\Repositories;


use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Chip\Interfaces\ChipRepositoryInterface;
use Modules\Chip\Models\Chip;
use Modules\Chip\Models\ChipDescription;

class ChipRepository implements ChipRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Chip::query()
            ->join('chip_descriptions AS sd', 'chips.id', 'sd.chip_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'chips.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return ChipDescription::where('chip_id', $id)
            ->join('languages', 'languages.id', 'chip_descriptions.language_id')
            ->join('chips', 'chips.id', 'chip_descriptions.chip_id')
            ->select(['chip_descriptions.*', 'languages.local', 'chips.*'])->get();
    }

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


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


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

    public function create(array $request): Chip
    {
        $chip = Chip::create($request);
        return $chip;
    }

    public function update(array $request, ?Chip $chip): Chip
    {
        $chip->update($request);

        return $chip;
    }

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

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

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

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