<?php

namespace App\Services\Repositories;

use App\Models\GroupProduct;
use App\Models\Product;
use App\Models\ProductDescription;
use App\Services\Integration\Integration\Connection;
use App\Services\Interfaces\ProductRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

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

        if ($request->category_id)
        {
            // $query->where('category_id',$request->category_id);
        }
        if ($request->group_id)
        {
            $query->whereIn('foodics_id', function($q) use($request){
                $q->select('product_id')->from('group_products')->where('is_active','1')->where('group_id', $request->group_id);
            });
        }
        if ($request->viewStatus)
        {
            if ($request->viewStatus == 'latest')
            {
                $query->orderBy('products.id','DESC');
            }

            if ($request->viewStatus == 'priceDESC')
            {
                $query->orderBy('products.price','DESC');
            }

            if ($request->viewStatus == 'priceASC')
            {
                $query->orderBy('products.price','ASC');
            }

            if ($request->viewStatus == 'popular')
            {
                $query->whereHas('orders')->withSum('orders', 'count');
                $query->orderByDesc('orders_sum_count');
            }

        }
        else
        {
            $query->orderBy('products.id','DESC');
        }

        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }
        // DB::enableQueryLog();
        if ($request->paginate ?? null) {
            $products= $query->paginate(50);
        }else{
            $products=$query->get();
        }
        // dd(DB::getQueryLog());
        return $products;
    }

    public function checkItem($id)
    {
        $product = Product::withTrashed()->where('foodics_id', $id)->first();
        return $product;
    }

    public function getItem($id)
    {
        $product = Product::where('foodics_id', $id)->firstOrFail();
        $query = Product::where('products.foodics_id', $id)
            ->join('product_descriptions', 'product_descriptions.product_id','products.id')
            ->join('languages', 'languages.id', 'product_descriptions.language_id')
            ->select(['products.*','product_descriptions.name','product_descriptions.description', 'languages.local']);

        $productDescription= $query->get();

        foreach ($productDescription as $key=>$row) {
            if ($row->local == getCurrentLocale())
            {
                $product = $row;
            }
            $product[$row->local] = $row;
        }
        return $product ;
    }



    public function create($request)
    {
        $data = $request instanceof Request ?  $request->all() : (array) $request;
        unset($data['created_at']);
        unset($data['updated_at']);
        unset($data['deleted_at']);
        $data['body'] = json_encode($data);
        $data['foodics_id'] = $data['id'];
        $product = Product::create($data);
        $this->saveData($data,$product);
    }
    public function update($request,$id)
    {
        $product = Product::withTrashed()->where('foodics_id', $id)->firstOrFail();
        $data = $request instanceof Request ?  $request->all() : (array) $request;
        unset($data['created_at']);
        unset($data['updated_at']);
        unset($data['deleted_at']);
        $data['body'] = json_encode($data);
        $data['foodics_id'] = $data['id'];
        $product->update($data);
        ProductDescription::where('product_id',$product->id)->delete();
        GroupProduct::where('product_id',$product->foodics_id)->delete();
        $this->saveData($data,$product);

    }

    public function saveData($data,$product){
        // Save description
        foreach (languages() as $lang) {
            $content=[
                'product_id'=> $product->id,
                'language_id'=> $lang->id,
                'name'=> $lang->local == 'en' ?  $data['name'] : (is_null($data['name_localized']) ? $data['name'] : $data['name_localized']) ,
                'description'=> $lang->local == 'en' ?  $data['description'] : (is_null($data['description_localized']) ? $data['description'] : $data['description_localized']) ,
            ];
            ProductDescription::create($content);
        }
        
        // save groups
        foreach ($data['groups'] ?? [] as $key => $group) {
            // Get Group
            $content=[
                'product_id'=> $product->foodics_id,
                'group_id'=> is_array($group) ? $group['id'] : $group->id,
                'is_active'=> is_array($group) ? $group['pivot']['is_active'] : $group->pivot->is_active
            ];
            GroupProduct::create($content);
        }
    }
    public function delete($request,$id)
    {
        $product = Product::where('foodics_id', $id)->firstOrFail();
        $product->delete();
    }
    public function restore($request,$id)
    {
        $product = Product::onlyTrashed()->where('foodics_id', $id)->firstOrFail();
        $product->restore();
    }

}
