<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Product;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class CompareController extends Controller
{
    /**
     * Display the compare page.
     *
     * @param Request $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $compareIds = $request->session()->get('compare', []);
        $products = Product::whereIn('id', $compareIds)->get();
        $allProducts = Product::all();

        $suggestedProducts = new Collection();
        if ($products->isEmpty()) {
            // Fetch some products to suggest if the compare list is empty
            $suggestedProducts = Product::inRandomOrder()->limit(3)->get();
        }


        return view('frontend.pages.compare', compact('products', 'allProducts', 'suggestedProducts'));
    }

    /**
     * Add a product to the compare list.
     *
     * @param Request $request
     * @param Product $product
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request, Product $product)
    {
        $compare = $request->session()->get('compare', []);

        // Limit comparison to a certain number of products, e.g., 4
        if (count($compare) >= 4 && !isset($compare[$product->id])) {
            return response()->json([
                'success' => false,
                'message' => 'You can only compare up to 4 products at a time.',
            ], 422);
        }

        if (!in_array($product->id, $compare)) {
            $compare[$product->id] = $product->id;
            $message = 'Product added to compare list.';
        } else {
            $message = 'Product is already in the compare list.';
        }

        $request->session()->put('compare', $compare);

        return response()->json([
            'success' => true,
            'message' => $message,
            'compareCount' => count($compare),
            'status' => 'added'
        ]);
    }

    /**
     * Remove a product from the compare list.
     *
     * @param Request $request
     * @param Product $product
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function remove(Request $request, Product $product)
    {
        $compare = $request->session()->get('compare', []);
        $key = array_search($product->id, $compare);
        if ($key !== false) {
            unset($compare[$key]);
            $request->session()->put('compare', $compare);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Product removed from compare list.',
                'compareCount' => count($compare)
            ]);
        }

        return back()->with('success', 'Product removed from compare list.');
    }

    /**
     * Clear all products from the compare list.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function clear(Request $request)
    {
        $request->session()->forget('compare');

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Compare list has been cleared.',
                'compareCount' => 0,
            ]);
        }

        return redirect()->back()->with('success', 'Compare list has been cleared.');
    }
}
