<?php

namespace Modules\Product\Repositories;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Product\Interfaces\ProductRepositoryInterface;
use Modules\Product\Models\Product;
use Modules\Product\Models\ProductDescription;

class ProductRepository implements ProductRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Product::query()
            ->join('product_descriptions AS sd', 'products.id', 'sd.product_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.title', 'products.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return ProductDescription::where('product_id', $id)
            ->join('languages', 'languages.id', 'product_descriptions.language_id')
            ->join('products', 'products.id', 'product_descriptions.product_id')
            ->select(['product_descriptions.*', 'languages.local','products.*'])->get();
    }

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


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

    public function create(array $request): Product
    {
        $product = Product::create($request);
        return $product;
    }

    public function update(array $request, ?Product $product): Product
    {
        $product->update($request);

        return $product;
    }

    public function saveData(array $request, int $product_id ) :void
    {
        ProductDescription::where('product_id', $product_id)->delete();
        foreach (languages() as $lang) {
            $data=[
                'product_id'=> $product_id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
            ];
            ProductDescription::create($data);
        }
    }

    /**
     * Remove the specified product from storage.
     * @param Product $product
     * @return void
     */
    public function destroy(Product $product) :void
    {
        $product->delete();
    }

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

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

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