<?php

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\CartRepository;
use App\Models\Cart;
use App\Models\Colour;
use Gloudemans\Shoppingcart\Facades\Cart as cartItem;
use App\Models\Product;
use App\Validators\CartValidator;

/**
 * Class CartRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class CartRepositoryEloquent extends BaseRepository implements CartRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Cart::class;
    }

    public function getCartContent()
    {
        return session()->get('cart', []);
    }

    public function addToCart($request, $id)
    {
        $product = Product::findOrFail($id);
        $requestedQuantity = $request['quantity'] ?: 1;
        $colorId = $request['colour'] ?? 'default';

        $colourName = Colour::find($colorId);
        // if (!$colourName) {
        //     return redirect()->back()->with('error', 'Selected color does not exist.');
        // }

        $cart = session()->get('cart', []);

        $cartKey = "{$id}_{$colorId}";

        if (isset($cart[$cartKey])) {
            $newQuantity = $cart[$cartKey]['quantity'] + $requestedQuantity;
            $cart[$cartKey]['quantity'] = $newQuantity;

        } else {

            $cart[$cartKey] = [
                "name" => $product->name,
                "description" => $product->description,
                "price" => $product->price,
                "quantity" => $requestedQuantity,
                "product_id" => $product->id,
                "colour_id" => $colorId,
                "colour_name" => $colourName->name ?? 'default',

            ];

        }
        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Product added to cart successfully!');
    }


    // Update stock for the product



    public function updateCart($id, $request)
    {

        $productId = $id;
        $colorId = $request['colour'] ?? '';
        $requestedQuantity = $request['quantity'];

//        if ($requestedQuantity <= 1) {
//            return redirect()->back()->with('error', 'Quantity cannot be less than 1.');
//        }

        $cart = session()->get('cart', []);

        $cartKey = "{$productId}_{$colorId}";

        if (isset($cart[$cartKey])) {
            $cart[$cartKey]['quantity'] = $requestedQuantity;

            session()->put('cart', $cart);
            return redirect()->back()->with('success', 'Cart updated successfully!');
        }

        return redirect()->back()->with('error', 'Product not found in cart.');
    }


    public function removeCart($id)
    {
        $cart = session()->get('cart', []);

        if (isset($cart[$id])) {
            unset($cart[$id]);
            session()->put('cart', $cart);
        }

        return redirect()->back()->with('success', 'Product removed from cart successfully!');
    }

    public function removeWholeCart()
    {
        session()->forget('cart');
    }

    public function getCount()
    {
        return cartItem::content()->count();
    }


    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }
}
