<?php

namespace Modules\Brand\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Brand\Interfaces\BrandRepositoryInterface;
use Modules\Brand\Models\Brand;
use Modules\Brand\Models\BrandDescription;

class BrandRepository implements BrandRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Brand::query()
            ->join('brand_descriptions AS sd', 'brands.id', 'sd.brand_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'brands.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return BrandDescription::where('brand_id', $id)
            ->join('languages', 'languages.id', 'brand_descriptions.language_id')
            ->join('brands', 'brands.id', 'brand_descriptions.brand_id')
            ->select(['brand_descriptions.*', 'languages.local','brands.*'])->get();
    }

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

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

    public function create(array $request): Brand
    {
        $brand = Brand::create($request);
        return $brand;
    }

    public function update(array $request, ?Brand $brand): Brand
    {
        $brand->update($request);

        return $brand;
    }

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

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

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

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