<?php

namespace Sarga\API\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Sarga\API\Http\Resources\Catalog\ProductVariant;
use Sarga\API\Http\Resources\Catalog\SuperAttribute;
use Sarga\Shop\Repositories\ProductRepository;
use Webkul\API\Http\Controllers\Shop\ProductController;
use Sarga\API\Http\Resources\Catalog\Product as ProductResource;
use Sarga\Shop\Repositories\AttributeOptionRepository;
use Webkul\Core\Repositories\SliderRepository;
use Carbon\Carbon;

class Products extends ProductController
{
    protected $attributeOptionRepository;

    public function __construct(
        ProductRepository $productRepository,
        SliderRepository $sliderRepository,
        AttributeOptionRepository $attributeOptionRepository
    ) {
        $this->attributeOptionRepository = $attributeOptionRepository;

        parent::__construct($productRepository);
    }

    /**
     * Returns a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return ProductResource::collection($this->productRepository->getAll(request()->input('category')));
    }

    public function getCurrentProduct(ProductRepository $prodRep, $id)
    {
        return ProductResource::collection($prodRep->getProductsRelatedToCategoryNurgul($id, request('perPage')));
    }

    public function home(SliderRepository $sliderRepository,)
    {
        // $data = [
        //     "sliders" => $sliderRepository->getActiveSliders(),
        //     "product_sections" => 'asd'
        // ];
        $sliders = $sliderRepository->select('title', 'path', 'content', 'expired_at', 'sort_order', 'slider_path')
            ->where(function ($query) {
                $query->where('expired_at', '>=', Carbon::now()->format('Y-m-d'))
                    ->orWhereNull('expired_at');
            })
            ->orderBy('sort_order', 'ASC')
            ->limit(3)
            ->get();

        $banner = $sliderRepository->select('title', 'path', 'content', 'expired_at', 'sort_order', 'slider_path')
            ->where(function ($query) {
                $query->where('expired_at', '>=', Carbon::now()->format('Y-m-d'))
                    ->orWhereNull('expired_at');
            })
            ->orderBy('sort_order', 'DESC')
            ->limit(1)
            ->get();

        $newProducts = ProductResource::collection($this->productRepository->getNewProducts());
        $featuredProducts = ProductResource::collection($this->productRepository->getFeaturedProducts());
        // $slider_map = $sliders->map(function ($item, $key){
        //     $item->review_average = $this->reviewRepository->getAverageRating($item);
        //     return $item;
        // });
        $data = [
            'data' => [
                'sliders' => $sliders,
                'product_sections' => [
                    [
                        'title' => 'New Products',
                        'type' => 'product',
                        'items' =>  $newProducts
                    ],
                    [
                        'title' => 'Adv Banner',
                        'type' => 'banner',
                        'items' =>  $banner
                    ],
                    [
                        'title' => 'Featured Products',
                        'type' => 'product',
                        'items' =>  $featuredProducts
                    ],
                ],
            ]
        ];

        return $data;
        // return HomeResource::collection($sliders);
        // dump(HomeResource::collection($sliders));
        // dump($sliders);
    }

    /**
     * Returns a individual resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function get($id)
    {
        return ($product = $this->productRepository->find($id)) ?
            new ProductResource($product) :
            response()->json(['error' => 'not found'], 404);
    }

    public function variants($id)
    {
        $product = $this->productRepository->with(['super_attributes:id,code', 'variants' => function ($query) {
            $query->with(['images', 'product_flats' => function ($qf) {
                $channel = core()->getRequestedChannelCode();

                $locale = core()->getRequestedLocaleCode();

                $qf->where('product_flat.channel', $channel)
                    ->where('product_flat.locale', $locale)
                    ->whereNotNull('product_flat.url_key')
                    ->where('status', 1);
            }]);
        }])->find($id);

        if (!empty($product) && $product->super_attributes->isNotEmpty() && $product->variants->isNotEmpty()) {
            $variants = $product->variants->makeHidden([
                'type', 'created_at', 'updated_at', 'parent_id', 'attribute_family_id',
                'additional', 'new', 'featured', 'visible_individually', 'status', 'guest_checkout', 'meta_title', 'meta_keywords',
                'product_flats', 'attribute_family', 'short_description', 'sku', 'brand'
            ]);

            $attribute = $product->super_attributes->first();

            $distinctVariants =  $variants->unique($attribute->code);

            $gr_data = array(
                'attribute' => SuperAttribute::make($attribute),
                'options' => [],
                'level' => $product->super_attributes->count()
            );

            foreach ($distinctVariants as $variant) {
                $option = $attribute->options->firstWhere('id', $variant->{$attribute->code});

                $item = [
                    'option' => $option->admin_name,
                    'images' => $variant->images,
                ];

                $attributes = $product->super_attributes;
                if ($attributes->count() > 1 && $option) {
                    $products = $variants->where($attribute->code, $variant->{$attribute->code})
                        ->map(function ($item, $key) use ($attributes) {
                            return ProductVariant::make($item, $attributes);
                        });

                    $item['variants']['attribute'] = SuperAttribute::make($product->super_attributes->last());
                    $item['variants']['products'] = $products->values();
                } else {
                    $item['product'] = ProductVariant::make($variant, $attributes);
                }
                $gr_data['options'][] = $item;
            }
            return response()->json($gr_data);
        }

        return response()->json(['message' => 'not found'], 404);
    }


    public function searchProducts()
    {
        //        return $this->productRepository->searchProductByAttribute(request('key'));
        return ProductResource::collection($this->productRepository->searchProductByAttributeShekil(request('key'),16));
    }

    public function discountedProducts()
    {
        return ProductResource::collection($this->productRepository->getDiscountedProducts(request()->input('category')));
    }

    public function popularProducts()
    {
        return ProductResource::collection($this->productRepository->getPopularProducts(request()->input('category')));
    }
}
