<?php

namespace Modules\Supplier\Repositories;

use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Supplier\Interfaces\SupplierRepositoryInterface;
use Modules\Supplier\Models\Supplier;
use Modules\Supplier\Models\SupplierDescription;

class SupplierRepository implements SupplierRepositoryInterface
{
    public function get(array $request)
    {
        $builder = Supplier::orderBy('id', 'DESC')
            ->join('supplier_descriptions AS sd', 'suppliers.id', 'sd.supplier_id')
            ->join('languages', 'languages.id', 'sd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['sd.name', 'suppliers.*']);
        return $builder;
    }

    public function getItem(int $id)
    {
        return SupplierDescription::where('supplier_id', $id)
            ->join('languages', 'languages.id', 'supplier_descriptions.language_id')
            ->join('suppliers', 'suppliers.id', 'supplier_descriptions.supplier_id')
            ->select(['supplier_descriptions.*', 'languages.local','suppliers.*'])->get();
    }

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

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

    public function create(array $request): Supplier
    {
        $supplier = Supplier::create($request);
        return $supplier;
    }

    public function update(array $request, ?Supplier $supplier): Supplier
    {
        $supplier->update($request);

        return $supplier;
    }

    public function saveData(array $request, int $supplier_id ) :void
    {
        SupplierDescription::where('supplier_id', $supplier_id)->delete();
        foreach (languages() as $lang) {
            $data=[
                'supplier_id'=> $supplier_id,
                'language_id'=> $lang->id,
                'name'=> $request['name_'.$lang->local],
            ];
            SupplierDescription::create($data);
        }
    }
    /**
     * Remove the specified supplier from storage.
     * @param Supplier $supplier
     * @return void
     */
    public function destroy(Supplier $supplier) :void
    {
        $supplier->delete();
    }

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

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

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