<?php

namespace App\Http\Controllers\Web;

use App\Http\Requests\Web\NewsLetterRequest;
use App\Models\Attribute;
use App\Models\Brand;
use App\Models\Category;
use App\Models\CategoryAttribute;
use App\Models\ProductAttributeChoice;
use Illuminate\Http\Request;
use App\Models\Mail;
use App\Models\Page;
use App\Models\Product;
use App\Models\ProductAttribute;
use App\Models\ProductPhoto;
use App\Models\Rate;
use App\Models\VisitorMessage;
use App\Services\Product\ProductService;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use App\Http\Controllers\Controller;
use App\Http\Requests\Web\ContactRequest;


class ProductController extends Controller
{
    private $view = 'web.pages.products.';
    private $viewAjax = 'web.pages.ajax.';
    private $paginate = 12;


    /**
     * Show the application dashboard.
     * @return View
     */

    public function product($id): View
    {
        $product = Product::withDescription($id)->firstOrFail();
        
        $product->update(['views'=>$product->views + 1]);
        
        $count = $product->count;
        $category = Category::withDescription($product->category_id)->withTrashed()->first();
        if($product->model_id)
        {
            $sub_category = Category::withDescription($product->model_id)->withTrashed()->first();
        }

        $title = $product->name;
        $product_service = new ProductService($product);
        $related_products = $product_service->relatedProducts();
        $one_services = $product_service->productServices()['one_services'];

        $multi_services = $product_service->productServices()['multi_services'];

        $photos = ProductPhoto::where('product_id',$id)->get();

        $attr_photo_ids = ProductAttribute::where('product_id',$product->id)->pluck('id')->toArray();
        $attr_photos = ProductAttributeChoice::where('image','!=',null)->where('count',null)->whereIn('product_attribute_id',$attr_photo_ids)->get();
        $images = [];
        $images[0] = asset($product->image);
        foreach ($photos as $row)
        {
            $images['normal_'.$row->id] = asset($row->image);
        }
        foreach ($attr_photos as $row)
        {
            $images['attribute_'.$row->id] = asset($row->image);
        }

        $rates = Rate::where('product_id',$id)->orderBy('id','DESC')->cursor();

        return view($this->view.'product_details', get_defined_vars());
    }

    public function search(Request $request)
    {
        if($request->product)
        {
            $title = __('web.search') . ' : '. $request->product;
            $query = Product::withDescription()->where('ad.name','LIKE', '%'.$request->product.'%');
        }
        elseif($request->brand)
        {
            $brand = Brand::findOrFail($request->brand);
            $title =  $brand->descriptions()->name;
            $query = Product::withDescription()->where('products.brand_id',$request->brand);
        }
        else
        {
            $title = __('web.search');
            $query = Product::withDescription();
        }
        if($request->ajax())
        {
            $products = Product::withDescription()->where('ad.name','LIKE', '%'.$request->product.'%')->take(3)->cursor();
            $count = Product::withDescription()->where('ad.name','LIKE', '%'.$request->product.'%')->count();
            return view($this->viewAjax.'search', get_defined_vars());
        }
        $products = $query->cursor();
        return view($this->view.'products', get_defined_vars());
    }
    public function products(Request $request)
    {
        $title = __('web.products');
        $products = Product::withDescription()->paginate($this->paginate);

        return view($this->view.'allproducts', get_defined_vars());
    }

    public function filter(Request $request,$id)
    {
        $category = Category::withDescription($id)->firstOrFail();
        if($category->category_id)
        {
            $model = $category;
            $category = Category::withDescription($category->category_id)->firstOrFail();
        }
        
        if(!$request->ajax())
        {
            $category->update(['views'=>$category->views + 1]);
        }
        $query = Product::withDescription()->where('products.category_id',$category->id);
        if(isset($model))
        {
            $query->where('products.model_id',$model->id);
        }
        if($request->choices)
        {
            $ids = [];
            foreach($request->choices as $key=>$choice)
            {
                if($choice)
                {
                    $product_ids = ProductAttribute::where('choice_id',$choice)->pluck('product_id')->toArray();
                    if(count($ids) == 0)
                    {
                        $ids = $product_ids;
                    }
                    else
                    {
                        $ids = array_intersect($ids,$product_ids);
                    }
                }
            }
            $check_ids = empty(array_filter($request->choices, function ($a) { return $a !== null;}));
            
            if(!$check_ids)
            {
                $query->whereIn('products.id',$ids);
            }
        }
        if($request->brand_id)
        {
            $query->where('products.brand_id',$request->brand_id);
        }
        if($request->gender)
        {
            $query->where('products.gender',$request->gender);
        }
        
        if($request->choice_id && $request->attribute_id)
        {
            $ids = ProductAttribute::query()
                ->join('product_attribute_choices as pac', 'pac.product_attribute_id', 'product_attributes.id')
                ->whereIn('pac.choice_id',$request['choice_id'])
                ->where('pac.count','!=',null)
                ->where('product_attributes.product_attribute_id','!=',null)
                ->select(['product_attributes.product_id', 'pac.*'])->pluck('product_attributes.product_id')->toArray();
            $main_ids = ProductAttributeChoice::whereIn('choice_id',$request->attribute_id)->pluck('id')->toArray();

            $main_ids = ProductAttribute::query()
                ->join('product_attribute_choices as pac', 'pac.product_attribute_id', 'product_attributes.id')
                ->whereIn('product_attributes.product_attribute_choice_id',$main_ids)
                ->where('pac.count','!=',null)
                ->where('product_attributes.product_attribute_id','!=',null)
                ->select(['product_attributes.product_id', 'pac.*'])->pluck('product_attributes.product_id')->toArray();
                
            $product_ids = array_intersect($ids,$main_ids);
            
            $product_ids = count($product_ids) == 0 ? [0] : $product_ids;
            $query->whereRaw("products.id IN (".implode(',', $product_ids).")");
        }
        elseif(!$request->choice_id && $request->attribute_id)
        {
            if($category->sub_id)
            {
                
            $main_ids = ProductAttributeChoice::whereIn('choice_id',$request->attribute_id)->pluck('id')->toArray();

            $product_ids = ProductAttribute::query()
                ->join('product_attribute_choices as pac', 'pac.product_attribute_id', 'product_attributes.id')
                ->whereIn('product_attributes.product_attribute_choice_id',$main_ids)
                ->where('pac.count','!=',null)
                ->where('product_attributes.product_attribute_id','!=',null)
                ->select(['product_attributes.product_id', 'pac.*'])->pluck('product_attributes.product_id')->toArray();
                
            }
            else
            {
                $ids = ProductAttribute::query()
                    ->join('product_attribute_choices as pac', 'pac.product_attribute_id', 'product_attributes.id')
                    ->whereIn('pac.choice_id',$request['attribute_id'])
                    ->where('pac.count','!=',null)
                    ->select(['product_attributes.product_id', 'pac.*'])->pluck('product_attributes.product_id')->toArray();
                $product_ids = $ids;
            }
            
            $product_ids = count($product_ids) == 0 ? [0] : $product_ids;
            $query->whereRaw("products.id IN (".implode(',', $product_ids).")");
        }
        elseif(isset($request->choice_id) && !isset($request->attribute_id))
        {
            $ids = ProductAttribute::query()
                ->join('product_attribute_choices as pac', 'pac.product_attribute_id', 'product_attributes.id')
                ->whereIn('pac.choice_id',$request['choice_id'])
                ->where('pac.count','!=',null)
                ->where('product_attributes.product_attribute_id','!=',null)
                ->select(['product_attributes.product_id', 'pac.*'])->pluck('product_attributes.product_id')->toArray();

            $product_ids = count($ids) == 0 ? [0] : $ids;
            $query->whereRaw("products.id IN (".implode(',', $product_ids).")");
        }
            
        

        if($request->paginate)
        {
            $pagination = $request->paginate;
        }
        else
        {
            $pagination = 0;
        }
        $count_paginate = $query->count() / $this->paginate;
        $products = $query;

        if($request->order_by)
        {
            if($request->order_by == 'highest_rate')
            {
                $products = $products->get()->sortByDESC('rate')->skip($this->paginate * $pagination)->take($this->paginate);
            }
            elseif ($request->order_by == 'lowest_rate')
            {
                $products = $products->get()->sortBy('rate')->skip($this->paginate * $pagination)->take($this->paginate);
            }
            elseif ($request->order_by == 'highest_cost')
            {
                $products = $products->get()->sortByDESC('cost')->skip($this->paginate * $pagination)->take($this->paginate);
            }
            elseif ($request->order_by == 'lowest_cost')
            {
                $products = $products->get()->sortBy('cost')->skip($this->paginate * $pagination)->take($this->paginate);
            }

        }
        else
        {
            $products = $products->skip($this->paginate * $pagination)->take($this->paginate)->get();
        }

        if($request->ajax())
        {
            if(isset($model))
            {
                $category = $model;
            }
            return view($this->viewAjax.'products', get_defined_vars());
        }
        $title = __('web.filter') . ' '.$category->name;

        if($category->brand_status == true)
        {
            $brands = Brand::withDescription()->cursor();
        }
        $attribute_ids = CategoryAttribute::where('category_id',$category->id)->pluck('attribute_id')->toArray();
//        $attribute_ids = count($attribute_ids) == 0 ? ['0']:$attribute_ids;

        $attribute_one = Attribute::withDescription()->with(
            ['choices' => function($query)
                {
                    $query->with('choice');
                },
            ]
        )->whereIn('attributes.id',$attribute_ids)->get();

        $main = Attribute::withDescription()->with(
            ['choices' => function($query)
                {
                    $query->with('choice');
                },
            ]
        )->where('attributes.id',$category->main_id)->first();

        $sub = Attribute::withDescription()->with(
            ['choices' => function($query)
            {
                $query->with('choice');
            },
            ]
        )->where('attributes.id',$category->sub_id)->first();

        if(isset($model))
        {
            $category = $model;
        }
        return view($this->view.'filter', get_defined_vars());
    }
}
