<?php

namespace App\Http\Controllers\web\home;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Product;
use App\Models\Categorybanner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class allproductsController extends Controller
{
    public function setcolor($color)
    {

        $brown = '#6B4B36';
        $metalicgold = '#D2C77D';
        $pink = '#C55C82';
        $applegreen = '#88DB86';
        $avacadogreen = '#2FCBD4';
        $babyblue = '#61A8F8';
        $babypink = '#f4c2c2';
        $beige = '#BA9978';
        $black = '#000000';
        $blue = '#0F2D8D';
        $bottlegreen = '#006A4E';
        $clear = '#CAD3D0';
        $coffee = '#6F4E37';
        $cream = '#FFFDD0';
        $darkgrey = '#A9A9A9';
        $green = '#005E3A';
        $grey = '#808080';
        $lemonyellow = '#FEF250';
        $lightorange = '#FFA07A';
        $marblebeige = '#DDD3D1';
        $marbleblue = '#62ADE6';
        $marblegold = '#D4AF37';
        $marbleorange = '#E9CBB9';
        $marblepink = '#A78B8D';
        $marblegreen = "#58C3C2";
        $marblered = '#80355C';
        $metalicblue = '#13598B';
        $metalicred = '#C40233';
        $metalicsilver = '#B4B4B8';
        $metalicviolet = '#9582BB';
        $orange = '#D09305';
        $purple = '#A286F4';
        $red = '#FF0000';
        $skyblue = '#6CD2FA';
        $white = '#FFFFFF';
        $yellow = '#E9C500';
        $saffron = '#F4C430';
        $silver = '#C0C0C0';
        $metalicgold = '#D2C77D';
        $marbleviolet = '#BDB8EE';
        $marblewhite = '#DEE4EE';
        $buttermilk = '#DAD9C6';
        $metalicgreen = '#3D7764';
        $metalicyellow = '#F8B700';
        $coffee ='#6F4E37';
        $cream ='#FFFDD0';
        $darkgray ='#A9A9A9';
        $bottlegreen='#006A4E';
        $selectcolorvalue = '';
        if ($color == 'Brown') {
            $selectcolorvalue = $brown;
        } elseif ($color == 'Applegreen') {
            $selectcolorvalue = $applegreen;
        } elseif ($color == 'Avocadogreen') {
            $selectcolorvalue = $avacadogreen;
        } elseif ($color == 'Babyblue') {
            $selectcolorvalue = $babyblue;
        } elseif ($color == 'Babypink') {
            $selectcolorvalue = $babypink;
        } elseif ($color == 'Beige') {
            $selectcolorvalue = $beige;
        } elseif ($color == 'Black') {
            $selectcolorvalue = $black;
        } elseif ($color == 'Blue') {
            $selectcolorvalue = $blue;
        } elseif ($color == 'Bottlegreen') {
            $selectcolorvalue = $bottlegreen;
        } elseif ($color == 'Clear') {
            $selectcolorvalue = $clear;
        } elseif ($color == 'Coffee') {
            $selectcolorvalue = $coffee;
        } elseif ($color == 'Cream') {
            $selectcolorvalue = $cream;
        } elseif ($color == 'Darkgrey') {
            $selectcolorvalue = $darkgrey;
        } elseif ($color == 'Green') {
            $selectcolorvalue = $green;
        } elseif ($color == 'Grey') {
            $selectcolorvalue = $grey;
        } elseif ($color == 'Lemonyellow') {
            $selectcolorvalue = $lemonyellow;
        } elseif ($color == 'Lightorange') {
            $selectcolorvalue = $lightorange;
        } elseif ($color == 'Marblebeige') {
            $selectcolorvalue = $marblebeige;
        } elseif ($color == 'Marbleblue') {
            $selectcolorvalue = $marbleblue;
        } elseif ($color == 'Marblegold') {
            $selectcolorvalue = $marblegold;
        } elseif ($color == 'Marbleorange') {
            $selectcolorvalue = $marbleorange;
        } elseif ($color == 'Marblepink') {
            $selectcolorvalue = $marblepink;
        } elseif ($color == 'Marblered') {
            $selectcolorvalue = $marblered;
        } elseif ($color == 'Metallicblue') {
            $selectcolorvalue = $metalicblue;
        } elseif ($color == 'Metalicred') {
            $selectcolorvalue = $metalicred;
        } elseif ($color == 'Metallicsilver') {
            $selectcolorvalue = $metalicsilver;
        } elseif ($color == 'Metalicviolet') {
            $selectcolorvalue = $metalicviolet;
        } elseif ($color == 'Orange') {
            $selectcolorvalue = $orange;
        } elseif ($color == 'Purple') {
            $selectcolorvalue = $purple;
        } elseif ($color == 'Red') {
            $selectcolorvalue = $red;
        } elseif ($color == 'Skyblue') {
            $selectcolorvalue = $skyblue;
        } elseif ($color == 'Purewhite') {
            $selectcolorvalue = $white;
        } elseif ($color == 'Yellow') {
            $selectcolorvalue = $yellow;
        } elseif ($color == 'Saffron') {
            $selectcolorvalue = $saffron;
        } elseif ($color == 'Marblegreen') {
            $selectcolorvalue = $marblegreen;
        } elseif ($color == 'Pink') {
            $selectcolorvalue = $pink;
        } elseif ($color == 'Silver') {
            $selectcolorvalue = $silver;
        } elseif ($color == 'Metallicgold') {
            $selectcolorvalue = $metalicgold;
        } elseif ($color == 'Marbleviolet') {
            $selectcolorvalue = $marbleviolet;
        } elseif ($color == 'Marblewhite') {
            $selectcolorvalue = $marblewhite;
        } elseif ($color == 'Buttermilk') {
            $selectcolorvalue = $buttermilk;
        } elseif ($color == 'Metalicgreen') {
            $selectcolorvalue = $metalicgreen;
        } elseif ($color == 'Metalicyellow') {
            $selectcolorvalue = $metalicyellow;
        }



        return $selectcolorvalue;
    }
    public function all_products(Request $request)
    {
        try {
            $user = Auth::user();
            $products = DB::table('product')
                ->join('product_color', 'product.id', '=', 'product_color.product_id')
                ->select(
                    'product.id',
                    'product.product_name',
                    'product.category_id',
                    'product.product_tags',
                    'product.sku',
                    'product.product_image',
                    'product.product_price',
                    'product.cutted_price',
                    'product.product_description',
                    'product.qty',
                    'product.weight',
                    'product.views',
                    'product.order',
                    'product.status',
                    'product.created_at',
                    'product_color.product_color',
                    'product_color.color_image'
                )
                ->where('product.status', 1)
                ->whereNull('product.deleted_at');
            $productCount = $products->count();
            $selectedSize = $request->query('size');
            $selectedcolor = $request->query('color');
            $getcolor = $this->setcolor($selectedcolor);



            $minprice = $request->min_price;
            $maxprice = $request->max_price;

            if ($minprice && $maxprice) {
                $products = $products->whereBetween('product_price', [$request->min_price, $request->max_price]);
            }

            if ($selectedSize != null) {
                $products = $products->whereJsonContains('product_size', $selectedSize);
            }
            if ($selectedcolor != null) {

                $products = DB::table('product')
                    ->join('product_color', 'product.id', '=', 'product_color.product_id')
                    ->select(
                        'product.id',
                        'product.product_name',
                        'product.category_id',
                        'product.product_tags',
                        'product.sku',
                        'product.product_image',
                        'product.product_price',
                        'product.cutted_price',
                        'product.product_description',
                        'product.qty',
                        'product.weight',
                        'product.views',
                        'product.order',
                        'product.status',
                        'product.created_at',
                        'product_color.product_color',
                        'product_color.color_image',
                    )
                    ->where('product_color.product_color', $getcolor)
                    ->whereNull('product.deleted_at');
            }

            switch (request('sortBy')) {
                case 'lowtohigh':
                    $products = $products->orderBy('product_price', 'asc')->get();
                    break;
                case 'hightolow':
                    $products = $products->orderBy('product_price', 'desc')->get();
                    break;
                default:
                    $products = $products->orderBy('product.created_at', 'asc')->get();
                    break;
            }

            $products = $products->groupBy('id')->flatMap(function ($group) {
                return $group->take(1); // Take only the first item from each group
            });
            $items = $products->values()->toArray();

            // Set up pagination variables
            $page = request()->get('page', 1); // Get current page from the request, default is 1
            $perPage = 16; // Number of items per page

            // Create a new LengthAwarePaginator instance
            $products = new LengthAwarePaginator(
                array_slice($items, ($page - 1) * $perPage, $perPage), // Slice the items array for the current page
                count($items), // Total items
                $perPage, // Items per page
                $page, // Current page
                ['path' => request()->url(), 'query' => request()->query()] // Keep the query parameters intact
            );
            $popular_products = Product::where('status', 1)->inRandomOrder()->take(4)->get();
            $categorybanner = null;

            return view('web.home.products.products', compact('products', 'productCount', 'popular_products', 'categorybanner'));
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
            return redirect()->route('american.plastic.web');
        }
    }

    public function view_from_categories(Request $request)
    {
        try {
            $id = request()->query('id');

            $user = Auth::user();
            $products = DB::table('product')
                ->join('product_color', 'product.id', '=', 'product_color.product_id')
                ->select(
                    'product.id',
                    'product.product_name',
                    'product.category_id',
                    'product.product_tags',
                    'product.sku',
                    'product.product_image',
                    'product.product_price',
                    'product.cutted_price',
                    'product.product_description',
                    'product.qty',
                    'product.weight',
                    'product.views',
                    'product.order',
                    'product.status',
                    'product.created_at',
                    'product_color.product_color',
                    'product_color.color_image'
                )
                ->where('product.status', 1)
                ->whereNull('product.deleted_at')
                ->where('product.category_id', $id);

            $productCount = $products->count();
            $selectedSize = $request->query('size');
            $selectedcolor = $request->query('color');
            $getcolor = $this->setcolor($selectedcolor);
            $minprice = $request->min_price;
            $maxprice = $request->max_price;

            if ($minprice && $maxprice) {
                $products = $products->whereBetween('product_price', [$request->min_price, $request->max_price]);
            }

            if ($selectedSize != null) {
                $products = $products->whereJsonContains('product_size', $selectedSize);
            }
            if ($selectedcolor != null) {
                $products = DB::table('product')
                    ->join('product_color', 'product.id', '=', 'product_color.product_id')
                    ->select(
                        'product.id',
                        'product.product_name',
                        'product.category_id',
                        'product.product_tags',
                        'product.sku',
                        'product.product_image',
                        'product.product_price',
                        'product.cutted_price',
                        'product.product_description',
                        'product.qty',
                        'product.weight',
                        'product.views',
                        'product.order',
                        'product.status',
                        'product.created_at',
                        'product_color.product_color',
                        'product_color.color_image',
                    )
                    ->where('product_color.product_color', $getcolor)
                    ->whereNull('product.deleted_at')
                    ->where('product.category_id', $id);
            }
            switch (request('sortBy')) {
                case 'lowtohigh':
                    $products = $products->orderBy('product_price', 'asc')->get();
                    break;
                case 'hightolow':
                    $products = $products->orderBy('product_price', 'desc')->get();
                    break;
                default:
                    $products = $products->orderBy('created_at', 'asc')->get();
                    break;
            }

            $products = $products->groupBy('id')->flatMap(function ($group) {
                return $group->take(1); // Take only the first item from each group
            });
            $items = $products->values()->toArray();

            // Set up pagination variables
            $page = request()->get('page', 1); // Get current page from the request, default is 1
            $perPage = 16; // Number of items per page

            // Create a new LengthAwarePaginator instance
            $products = new LengthAwarePaginator(
                array_slice($items, ($page - 1) * $perPage, $perPage), // Slice the items array for the current page
                count($items), // Total items
                $perPage, // Items per page
                $page, // Current page
                ['path' => request()->url(), 'query' => request()->query()] // Keep the query parameters intact
            );
            $popular_products = Product::where('status', 1)->inRandomOrder()->take(4)->get();
            $categorybanner = Categorybanner::where('category_id', $id)->first();

            return view('web.home.products.products', compact('products', 'productCount', 'popular_products', 'categorybanner'));
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
            return redirect()->route('american.plastic.web');
        }
    }

    public function search_products(Request $request)
    {
        $user = Auth::user();
        try {
            $search = $request->search_value;
            $products = DB::table('product')
                ->join('product_color', 'product.id', '=', 'product_color.product_id')
                ->select(
                    'product.id',
                    'product.product_name',
                    'product.category_id',
                    'product.product_tags',
                    'product.sku',
                    'product.product_image',
                    'product.product_price',
                    'product.cutted_price',
                    'product.product_description',
                    'product.qty',
                    'product.weight',
                    'product.views',
                    'product.order',
                    'product.status',
                    'product.created_at',
                    'product_color.product_color',
                    'product_color.color_image'
                )
                ->where('product.status', 1)
                ->whereNull('product.deleted_at')
                ->where(function ($query) use ($search) {
                    $query->where('product_name', 'LIKE', '%' . $search . '%')
                        ->orWhere('product_description', 'LIKE', '%' . $search . '%');
                });
            $productCount = $products->count();
            $selectedSize = $request->query('size');
            $selectedcolor = $request->query('color');
            $getcolor = $this->setcolor($selectedcolor);
            $minprice = $request->min_price;
            $maxprice = $request->max_price;

            if ($minprice && $maxprice) {
                $products = $products->whereBetween('product_price', [$request->min_price, $request->max_price]);
            }

            if ($selectedSize != null) {
                $products = $products->whereJsonContains('product_size', $selectedSize);
            }
            if ($selectedcolor != null) {
                $products = DB::table('product')
                    ->join('product_color', 'product.id', '=', 'product_color.product_id')
                    ->select(
                        'product.id',
                        'product.product_name',
                        'product.category_id',
                        'product.product_tags',
                        'product.sku',
                        'product.product_image',
                        'product.product_price',
                        'product.cutted_price',
                        'product.product_description',
                        'product.qty',
                        'product.weight',
                        'product.views',
                        'product.order',
                        'product.status',
                        'product.created_at',
                        'product_color.product_color',
                        'product_color.color_image',
                    )
                    ->where('product_color.product_color', $getcolor)
                    ->whereNull('product.deleted_at')
                    ->where('product.status', 1)
                    ->where(function ($query) use ($search) {
                        $query->where('product_name', 'LIKE', '%' . $search . '%')
                            ->orWhere('product_description', 'LIKE', '%' . $search . '%');
                    });
            }
            switch (request('sortBy')) {
                case 'lowtohigh':
                    $products = $products->orderBy('product_price', 'asc')->get();
                    break;
                case 'hightolow':
                    $products = $products->orderBy('product_price', 'desc')->get();
                    break;
                default:
                    $products = $products->orderBy('created_at', 'asc')->get();
                    break;
            }

            $products = $products->groupBy('id')->flatMap(function ($group) {
                return $group->take(1); // Take only the first item from each group
            });
            $items = $products->values()->toArray();

            // Set up pagination variables
            $page = request()->get('page', 1); // Get current page from the request, default is 1
            $perPage = 16; // Number of items per page

            // Create a new LengthAwarePaginator instance
            $products = new LengthAwarePaginator(
                array_slice($items, ($page - 1) * $perPage, $perPage), // Slice the items array for the current page
                count($items), // Total items
                $perPage, // Items per page
                $page, // Current page
                ['path' => request()->url(), 'query' => request()->query()] // Keep the query parameters intact
            );
            $popular_products = Product::where('status', 1)->inRandomOrder()->take(4)->get();
            $categorybanner = null;
            return view('web.home.products.products', compact('products', 'productCount', 'popular_products', 'categorybanner'));
        } catch (\Throwable $th) {
            DB::table('error_logs')->insert([
                'message' => $th->getMessage(),
                'file' => $th->getFile(),
                'line' => $th->getLine(),
                'trace' => $th->getTraceAsString(),
                'created_at' => now(),
            ]);
            return redirect()->route('american.plastic.web');
        }
    }
}
