<?php

namespace App\Http\Controllers\Frontend;

use App\Helper\Sorting;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Category;
use App\Models\ExtraMiniCategory;
use App\Models\Collection;
use App\Models\Color;
use App\Models\Comment;
use App\Models\Product;
use App\Models\Campaign;
use App\Models\CampaingProduct;
use App\Models\Attribute;
use App\Models\AttributeValue;
use App\Models\Advertisement;
use App\Models\SubCategory;
use App\Models\miniCategory;
use Illuminate\Http\Request;
use View;
use Illuminate\Support\Facades\DB;

class ProductController extends Controller
{


    public function showAllProduct(Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $products =  Product::where('status', '1')
            ->skip($skip)->orderBy('id', 'desc')
            ->take(16)->get();



        $data = '';
        $data2 = '';
        if ($request->ajax()) {
            if ($products->count() > 0) {
                foreach ($products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.product', compact('products'));
    }



    /**
     * product filtering by requested data
     *
     * @param  mixed $request
     * @return void
     */
    public function productFilter(Request $request)
    {
        $products = Product::where('status', '1');


        // return $request;
        $unr = $request->unr;
        // dd($unr); // http://lems.test/product
        
        if (isset($request->min_range_amount) && isset($request->max_range_amount)) {
            if (setting('CURRENCY_CODE_MIN')) {
                $currency_code_min = setting('CURRENCY_CODE_MIN');
            } else {
                $currency_code_min = "Tk";
            }
            $min        = (int)$request->min_range_amount;
            $max        = (int)$request->max_range_amount;
            $products   = $products->whereBetween('regular_price', [$min, $max]);
        } else {
            $min = 0;
            $max = 9999999999999999999999999;
        }

        // check category
        if ($request->extra_category != '') {
            $sub_category = ExtraMiniCategory::where('slug', $request->extra_category)->pluck('id');
            $sub_category_product_ids = DB::table('extra_mini_category_product')->where('extra_mini_category_id', $sub_category)->get()->pluck('product_id');
            $products = $products->whereIn('id', $sub_category_product_ids);
        } elseif ($request->mini_category != '') {
            $sub_category = miniCategory::where('slug', $request->mini_category)->pluck('id');
            $sub_category_product_ids = DB::table('mini_category_product')->where('mini_category_id', $sub_category)->get()->pluck('product_id');
            $products = $products->whereIn('id', $sub_category_product_ids);
        } elseif ($request->sub_category != '') {
            $sub_category = SubCategory::where('slug', $request->sub_category)->pluck('id');
            $sub_category_product_ids = DB::table('product_sub_category')->where('sub_category_id', $sub_category)->get()->pluck('product_id');
            $products = $products->whereIn('id', $sub_category_product_ids);
        } elseif ($request->category != '') {
            $category = Category::where('slug', $request->category)->pluck('id');
            $category_product_ids = DB::table('category_product')->where('category_id', $category)->get()->pluck('product_id');
            $products = $products->whereIn('id', $category_product_ids);
        }

        // check request collection
        if ($request->collection != '') {
            $collection  = Collection::where('slug', $request->collection)->first();
            $categoryIds = $collection->categories->pluck('id');
            $collection_product_ids  = DB::table('category_product')->whereIn('category_id', $categoryIds)->get()->pluck('product_id');
            $products = $products->whereIn('id', $collection_product_ids);
        }

        // Attributets
        if ($request->rating != '') {
            $rating_product_ids = DB::table('reviews')->where('rating', $request->rating)->get()->pluck('product_id');
            $products = $products->whereIn('id', $rating_product_ids);
        }
        if ($request->colors != '') {
            $colors = Color::whereIn('slug', $request->colors)->pluck('id');
            $color_product_ids = DB::table('color_product')->whereIn('color_id', $colors)->get()->pluck('product_id');

            $products = $products->whereIn('id', $color_product_ids);
        }



        $s_attri = $request->input('attri');
        if (!empty($s_attri)) {
            $brands = AttributeValue::whereIn('slug', $s_attri)->pluck('id');
            $brandProductIds = DB::table('attribute_product')->whereIn('attribute_value_id', $brands)->pluck('product_id');
            if ($brandProductIds->count() > 0) {
                $products = $products->whereIn('id', $brandProductIds->toArray());
            } else {
                // No products found, reset the query to get no products
                $products = $products->where('id', 0);
            }
        }

        $brands = $request->input('brands'); // Get brands from the request
        if (!empty($brands)) {
            $brandIds = Brand::whereIn('slug', $brands)->pluck('id'); // Fetch IDs of brands in the request
            if ($brandIds->count() > 0) {
                $products = $products->whereIn('brand_id', $brandIds); // Filter products based on brand IDs
            }
        }

        // sorting
        $sort       = new Sorting();
        $value      = $sort->getValue($request->sort);
        if ($value == $sort->oldToNew) {
            $products = $products->orderBy('id', 'asc')->get();
        } elseif ($value == $sort->best) {
            $products = $products->orderBy('reach', 'desc')->get();
        } elseif ($value == $sort->highToLow) {
            $products = $products->orderByRaw('CONVERT(regular_price, SIGNED) desc')->get();
        } elseif ($value == $sort->lowToHigh) {
            $products = $products->orderByRaw('CONVERT(regular_price, SIGNED) asc')->get();
        } elseif ($value == $sort->dhighToLow) {
            $products = $products->orderByRaw('CONVERT(discount_price, SIGNED) desc')->get();
        } elseif ($value == $sort->dlowToHigh) {
            $products = $products->orderByRaw('CONVERT(discount_price, SIGNED) asc')->get();
        } else {
            $products = $products->orderBy('id', 'desc')->get();
        }


        return view('frontend.filter-product', compact('products', 'request', 'min', 'max', 'unr'));
    }



    // show products by category
    public function showProductByCategory($slug, Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }

        $category = Category::with(['products' => function ($query) use ($skip) {
            return $query->where('status', true)->latest('id')->take(15)->skip($skip);
        }])
            ->where('slug', $slug)
            ->where('status', true)
            ->firstOrFail();

        $products = $category;
        $data = '';
        $data2 = '';



        $advertisements = Advertisement::select('id', 'status', 'type', 'position', 'url', 'image', 'video', 'content')
                    ->where('status', 1)
                    ->where('position', 3)
                    ->orderBy('updated_at', 'desc')
                    ->take(3)
                    ->get();
                    // dd($advertisements);

        if ($request->ajax()) {
            if ($category->products->count() > 0) {
                foreach ($category->products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.category-product', compact('category', 'slug', 'advertisements'));
    }



    public function showProductByBrand($slug, Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $brand = Brand::where('slug', $slug)->first();
        $products =  Product::where('status', '1')->where('brand_id', $brand->id)
            ->skip($skip)
            ->take(16)->get();

        $data = '';
        $data2 = '';

        if ($request->ajax()) {
            if ($products->count() > 0) {
                foreach ($products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.product', compact('slug', 'products'));
    }
    public function showProductByAuthor($slug, Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $products =  Product::where('status', '1')->where('author_id', $slug)
            ->skip($skip)
            ->take(16)->get();

        $data = '';
        $data2 = '';

        if ($request->ajax()) {
            if ($products->count() > 0) {
                foreach ($products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.product', compact('slug', 'products'));
    }


    // show products by sub category
    public function showProductBySubCategory($slug, Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $data = '';
        $data2 = '';
        $subCategory = SubCategory::with(['products' => function ($query) use ($skip) {
            return $query->where('status', true)->latest('id')->take(16)->skip($skip);
        }])
            ->where('slug', $slug)
            ->where('status', true)
            ->firstOrFail();
        if ($request->ajax()) {
            if ($subCategory->products->count() > 0) {
                foreach ($subCategory->products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        $type = '0';
        return view('frontend.sub-category-product', compact('subCategory', 'slug', 'type'));
    }
    public function showProductByMiniCategory($slug, Request $request)
    {
        $type = '1';
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $data = '';
        $data2 = '';
        $subCategory = miniCategory::with(['products' => function ($query) use ($skip) {
            return $query->where('status', true)->latest('id')->take(16)->skip($skip);
        }])
            ->where('slug', $slug)
            ->where('status', true)
            ->firstOrFail();
        if ($request->ajax()) {
            if ($subCategory->products->count() > 0) {
                foreach ($subCategory->products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.sub-category-product', compact('subCategory', 'slug', 'type'));
    }
    public function showProductByextraCategory($slug, Request $request)
    {
        $type = '2';
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $data = '';
        $data2 = '';
        $subCategory = ExtraMiniCategory::with(['products' => function ($query) use ($skip) {
            return $query->where('status', true)->latest('id')->take(16)->skip($skip);
        }])
            ->where('slug', $slug)
            ->where('status', true)
            ->firstOrFail();
        if ($request->ajax()) {
            if ($subCategory->products->count() > 0) {
                foreach ($subCategory->products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.sub-category-product', compact('subCategory', 'type', 'slug'));
    }

    /**
     * show products by collection
     *
     * @param  mixed $slug
     * @return void
     */
    public function showProductByCollection($slug, Request $request)
    {
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }

        $collection  = Collection::where('slug', $slug)->where('status', true)->firstOrFail();
        $categoryIds = $collection->categories->pluck('id');
        $productIds  = DB::table('category_product')->whereIn('category_id', $categoryIds)->get()->pluck('product_id');
        $products    = Product::whereIn('id', $productIds)->where('status', true)->latest('id')->take(4)->skip($skip)->get();
        $data = '';
        $data2 = '';
        if ($request->ajax()) {
            if ($products->count() > 0) {
                foreach ($products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        return view('frontend.collection-product', compact('products', 'collection'));
    }


    public function productSearch(Request $request)
    {

        $searchKeyword = $request->keyword;
        $i = 1;
        if ($request->ajax()) {
            $skip = $request->skip / 2;
        } else {
            $skip = 0;
        }
        $data = '';
        $data2 = '';
        $products = Product::whereLike(['title', 'full_description', 'tags.name'], $searchKeyword)
            ->filter('status', true)
            ->latest('id')
            ->skip($skip)
            ->take(16)->get();

        // $advertisements = Advertisement::select('id', 'status', 'type', 'position', 'url', 'image', 'video', 'content')
        //             ->where('status', 1)
        //             ->where('position', 4)
        //             ->orderBy('updated_at', 'desc')
        //             ->take(3)
        //             ->get();
                    // dd($advertisements);

        
        if ($request->ajax()) {
            if ($products->count() > 0) {
                foreach ($products as $product) {
                    $data .= View::make("components.product-grid-view")
                        ->with("product", $product)
                        ->render();
                    $data2 .= View::make("components.product-list-view")
                        ->with("product", $product)->with('advertisements', $advertisements)
                        ->render();
                }
            }
            return json_encode(array($data, $data2));;
        }
        $key = $searchKeyword;

        
        return view('frontend.search-product', compact('products', 'key', 'searchKeyword'));
    }
    public function advanceSearch(Request $request)
    {
        $products = Product::whereLike(['title', 'full_description', 'tags.name'], $request->key)
            ->orWhere('sku', $request->key)
            ->orWhere('id', $request->key)
            ->orWhere('slug', $request->key)
            ->filter('status', true)
            ->latest('id')
            ->paginate(20);
        $data = '<style>.pin:hover{background:gainsboro !important}</style>';
        if ($products->count() > 0) {

            foreach ($products as $product) {
                $data .= '<div class="product col-lg-12" style="height: initial;"><div class="product-wrapper list-comp"><a href="' . route('product.details', $product->slug) . '"><div class="pin"><div class="thumbnail"><img style="object-fit:fill;width:60px;height: 60px;max-width: 100px;" src="' . asset('uploads/product/' . $product->image) . '" alt="Product Image"></div><div class="detaisls"><h5 class="search_p_titile">' . $product->title . '</h5></div></div></a></div></div>';
            }
        }
        return json_encode($data);;
    }
    
    

    // // show product landing
    // public function landing_page($slug){


    //     $landing_design = 1; // will be dynamic

    //     $product = Product::with('comments', 'reviews')->where('slug', $slug)->where('status', true)->firstOrFail();
    //     $product->reach += 1;
    //     $product->update();
    //     $colors_product = DB::table('color_product')
    //         ->select('*')
    //         ->join('colors', 'colors.id', '=', 'color_product.color_id')
    //         ->where('color_product.product_id', $product->id)
    //         ->get();
    //     $attributes = Attribute::all();

    //     return view("landing_pages.landing_page_$landing_design", compact('product', 'colors_product', 'attributes'));
    // }



    // show product details
    public function productDetails($slug)
    {
        $product = Product::with('comments', 'reviews')->where('slug', $slug)->where('status', true)->firstOrFail();
        $product->reach += 1;
        $product->update();
        $colors_product = DB::table('color_product')
                        ->select('*')
                        ->join('colors', 'colors.id', '=', 'color_product.color_id')
                        ->where('color_product.product_id', $product->id)
                        ->get();
        $attributes = Attribute::all();


        $single_product_layout = setting('SINGLE_PRODUCT_LAYOUT'); // 1, 2, 3 like this, coming from setting and changin from dashboard/setting/layout
        $single_product_layout = ($single_product_layout) ? $single_product_layout : 1; // if null then set 1

        return view("frontend.single_product_$single_product_layout", compact('product', 'colors_product', 'attributes'));
    }


    // show product details
    public function campProductDetails($slug)
    {
        $campaigns_product = CampaingProduct::find($slug);
        // $campaigns_product = CampaingProduct::where('product_id', $slug)->first();

        $product = Product::with('comments', 'reviews')
                            ->where('id', $campaigns_product->product_id)
                            ->where('status', true)
                            ->firstOrFail();
                            $product->price = $campaigns_product->price;
                            $product->dynamic_price = $campaigns_product->price;
                            $product->discount_price = $campaigns_product->price;

        $reachProduct = Product::with('comments', 'reviews')
                            ->where('id', $campaigns_product->product_id)
                            ->where('status', true)
                            ->firstOrFail();
        // Product view increment
        $reachProduct->reach += 1;
        $reachProduct->update();

        $colors_product = DB::table('color_product')
            ->select('*')
            ->join('colors', 'colors.id', '=', 'color_product.color_id')
            ->where('color_product.product_id', $product->id)
            ->get();

        $attributes = Attribute::all();

        $single_product_layout = setting('SINGLE_PRODUCT_LAYOUT'); // 1, 2, 3 like this, coming from setting and changin from dashboard/setting/layout
        $single_product_layout = ($single_product_layout) ? $single_product_layout : 1; // if null then set 1
        // return view('frontend.single-product', compact('product', 'colors_product', 'attributes', 'campaigns_product'));
        return view("frontend.single_product_$single_product_layout", compact('product', 'colors_product', 'attributes', 'campaigns_product'));
    }

    // add to cart product
    public function addToCart(Request $request)
    {
        $this->validate($request, [
            'id'    => 'required|integer',
            'qty'   => 'required|integer',
            'color' => 'required|string|max:20',
            'size'  => 'required|string|max:20'
        ]);

        $user = auth()->user();
        if ($user->role_id == 2 || $user->role_id == 3) {

            return response()->json([
                'alert'   => 'success',
                'message' => 'Product add to cart successfully'
            ]);
        } else {
            return response()->json([
                'alert'   => 'error',
                'message' => 'Please login your account!!'
            ]);
        }
    }

    /**
     * comment by product
     *
     * @param  mixed $slug
     * @return void
     */
    public function comment(Request $request, $slug)
    {
        $this->validate($request, [
            'comment' => 'required|string'
        ]);

        $product = Product::where('slug', $slug)->first();

        Comment::create([
            'user_id'    => auth()->id(),
            'product_id' => $product->id,
            'body'       => $request->comment
        ]);

        notify()->success("Your comment successful", "Success");
        return back();
    }

    /**
     * product comment reply
     *
     * @param  mixed $request
     * @param  mixed $slug
     * @param  mixed $id
     * @return void
     */
    public function reply(Request $request, $slug, $id)
    {
        $this->validate($request, [
            'reply' => 'required|string'
        ]);

        $product = Product::where('slug', $slug)->first();

        Comment::create([
            'user_id'    => auth()->id(),
            'product_id' => $product->id,
            'parent_id'  => $id,
            'body'       => $request->reply
        ]);

        notify()->success("Your reply successful", "Success");
        return back();
    }



    /**
     * show product details to cart
     *
     * @param  mixed $slug
     * @return void
     */
    public function productInfo($slug)
    {
        $product = Product::with(array(
            'colors' => function ($query) {
                $query->select('code', 'name', 'slug');
            },
            'sizes' => function ($query) {
                $query->select('name');
            }
        ))->where('slug', $slug)->firstOrFail(['id', 'slug', 'regular_price', 'discount_price', 'image']);
        $attributes = Attribute::all();
        $values = '<script>function hiddenValueInputID(hiddenInputID, hiddenInputValue){$("input#" + hiddenInputID).val(hiddenInputValue);}</script>';
        $attrs = '';  // Initialize $attrs

        foreach ($attributes as $attribute) {
            $attribute_prouct = DB::table('attribute_product')
                ->select('*')
                ->join('attribute_values', 'attribute_values.id', '=', 'attribute_product.attribute_value_id')
                ->addselect('attribute_values.name as vName')
                ->addselect('attribute_values.id as vid')
                ->join('attributes', 'attributes.id', '=', 'attribute_values.attributes_id')
                ->where('attribute_product.product_id', $product->id)
                ->where('attributes.id', $attribute->id)
                ->get();
            if ($attribute_prouct->count() > 0) {
                $attrs .= '<div class="col-12 pl-0 mb-2"><strong>Select ' . $attribute->name . ':</strong></div>';
                foreach ($attribute_prouct as $attr) {
                    $attrs .= '<div class="form-check"><input onclick="hiddenValueInputID(\'' . $attribute->slug . '\', \'' . $attr->vid . '\');" id="' . $attr->vName . '" class="form-check-input product_model_pop_up_get_attri_price pp' . $attribute->slug . '" type="radio" name="' . $attribute->slug . '" value="' . $attr->vid . '"><label class="form-check-label" for="' . $attr->vName . '">' . $attr->vName . '</label></div>';
                }
                $values .= '<input type="hidden" name="' . $attribute->slug . '" id="' . $attribute->slug . '" value="blank">';
            }
        }
        return response()->json(array($product, $attrs, $values));
    }
    public function campProductInfo($id)
    {
        $camp = CampaingProduct::find($id);
        $slug = $camp->product_id;
        $product = Product::where('id', $slug)
        ->with(array(
            'colors' => function ($query) {
                $query->select('code', 'name', 'slug');
            },
            'sizes' => function ($query) {
                $query->select('name');
            }
        ))
        ->firstOrFail(['id', 'slug', 'regular_price', 'discount_price', 'image']);
        
        // Update product campaing price as discount/ override price coming from product table 
        $product->discount_price = $camp->price;
        $attributes = Attribute::all();
        $values = '<script>function hiddenValueInputID(hiddenInputID, hiddenInputValue){$("input#" + hiddenInputID).val(hiddenInputValue);}</script>';
        $values .= '<input type="hidden" name="camp" value="' . $product->id .'">';
        $attrs = '';  // Initialize $attrs

        foreach ($attributes as $attribute) {
            $attribute_prouct = DB::table('attribute_product')
                ->select('*')
                ->join('attribute_values', 'attribute_values.id', '=', 'attribute_product.attribute_value_id')
                ->addselect('attribute_values.name as vName')
                ->addselect('attribute_values.id as vid')
                ->join('attributes', 'attributes.id', '=', 'attribute_values.attributes_id')
                ->where('attribute_product.product_id', $product->id)
                ->where('attributes.id', $attribute->id)
                ->get();
                // dd($attribute_prouct);

            // if ($attribute_prouct->count() > 0) {
            //     $attrs .= '<div class="col-12 pl-0 mb-2"><p><strong>Select ' . $attribute->name . ':</strong></p></div>';
            //     foreach ($attribute_prouct as $attr) {
            //         $attrs .= '<div class="form-check col-2 col-sm-2"><input onclick="hiddenValueInputID(\'' . $attribute->slug . '\', \'' . $attr->vid . '\');" id="' . $attr->vName . '" class="form-check-input get_attri_price pp' . $attribute->slug . '" type="radio" name="' . $attribute->slug . '" value="' . $attr->vid . '"><label class="form-check-label" for="' . $attr->vName . '">' . $attr->vName . '</label></div>';
            //     }
            //     $values .= '<input type="hidden" name="' . $attribute->slug . '" id="' . $attribute->slug . '" value="blank">';
            // }

            if ($attribute_prouct->count() > 0) {
                $attrs .= '<div class="col-12 pl-0 mb-2"><strong>Select ' . $attribute->name . ':</strong></div>';
                foreach ($attribute_prouct as $attr) {
                    $attrs .= '<div class="form-check"><input onclick="hiddenValueInputID(\'' . $attribute->slug . '\', \'' . $attr->vid . '\');" id="' . $attr->vName . '" class="form-check-input product_model_pop_up_get_attri_price pp' . $attribute->slug . '" type="radio" name="' . $attribute->slug . '" value="' . $attr->vid . '"><label class="form-check-label" for="' . $attr->vName . '">' . $attr->vName . '</label></div>';
                }
                $values .= '<input type="hidden" name="' . $attribute->slug . '" id="' . $attribute->slug . '" value="blank">';
            }
        }


        return response()->json(array($product, $attrs, $values, $camp));
    }
    public function getAttrPrice(Request $request)
    {


        // dd($request->all());

        // dd('Hello');
        // dd($request);

        $attributes = Attribute::all();
        $price = 0;

        if(isset($request->size) && $request->size != null){
            foreach (json_decode($request->size, true) as $key => $value) {
                if (isset($request->$key)) {
                    // If key already exists in request, avoid merging
                    continue;
                }
                $request->merge([$key => $value]);
            }
        }
        // dd($request->all());
        
        
        foreach ($attributes as $attribute) {
            $attribute_prouct = DB::table('attribute_product')
                ->select('*')
                ->join('attribute_values', 'attribute_values.id', '=', 'attribute_product.attribute_value_id')
                ->addselect('attribute_values.name as vName')
                ->addselect('attribute_product.id as vid')
                ->join('attributes', 'attributes.id', '=', 'attribute_values.attributes_id')
                ->where('attribute_product.product_id', $request->id)
                ->where('attributes.id', $attribute->id)
                ->get();
            if ($attribute_prouct->count() > 0) {
                $slug = $attribute->slug;
                $id = $request->$slug;
                if ($id > 0) {
                    $attr_pro = DB::table('attribute_product')->where('product_id', $request->id)->where('attribute_value_id', $id)->first();
                    // dd($attr_pro);
                    $price += $attr_pro->price;
                }
            }
        }

        $c = Color::where('slug', $request->color)->first();
        if (!empty($c)) {
            $color = DB::table('color_product')->where('product_id', $request->id)->where('color_id', $c->id)->first();
        }

        $product = Product::find($request->id);

        if (isset($request->camp)) {
            // dd($request->camp);
            // $camp = CampaingProduct::find($request->camp);
            $camp = CampaingProduct::where('product_id', $request->id)->first();
            $op = $camp->price;
        
        } elseif (empty($product->discount_price)) {
            $op = $product->regular_price;
        } else {
            $op = $product->discount_price;
        }
        if (!empty($color)) {
            $price += $op + $color->price;
        } else {
            $price += $op;
        }

        return response()->json($price);
    }
    public function allBrand()
    {
        $brands = Brand::where('status', '1')->get();
        return view('frontend.brands', compact('brands'));
    }
}
