<?php

namespace App\Http\Controllers\FrontControllers;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Repositories\CartRepository;
use App\Repositories\CMSPagesRepositoryEloquent;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AddToCartController extends Controller
{
    //  start this  code add to cart product detail fetch

    protected $cartRepository;
    private $cmsPageRepository;
    public function __construct(CMSPagesRepositoryEloquent $cMSPagesRepository, CartRepository $cartRepository)
    {
        $this->cartRepository = $cartRepository;
        $this->cmsPageRepository = $cMSPagesRepository;
    }
    public function cart()
    {
        if (Auth::check() && Auth::user()->hasRole('admin')) {
            $this->cartRepository->removeWholeCart();
            $cart_data = [];
        } else {
            $cart_data = $this->cartRepository->getCartContent();
        }
        $data = $this->cmsPageRepository->getPageBySlug('cart');
        return view('front.cart', compact('cart_data','data'));

    }

//    public function update(Request $request)
//    {
//
//        return $this->cartRepository->updateCart( $request->all());
//    }
    public function update(Request $request)
    {
        $cart = session('cart', []);
        $productId = $request->product_id;
        $quantity = max(1, intval($request->quantity));

        if (isset($cart[$productId])) {
            $cart[$productId]['quantity'] = $quantity;
            session(['cart' => $cart]);
        }

        return response()->json(['success' => true, 'message' => 'Cart updated successfully']);
    }

    public function add(Request $request, $id)
    {
        $request->validate([
            // 'colour' => 'required|exists:colours,id',
            'quantity' => 'required|integer|min:1',
        ]);
        return $this->cartRepository->addToCart($request->all(), $id);

    }


    public function remove($id)
    {
        return $this->cartRepository->removeCart($id);
    }

    public function cartRemoveCheckout(Request $request)
    {

        return $this->cartRepository->removeWholeCart();

    }

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

        if (isset($cart[$id])) {
            unset($cart[$id]); // Remove the item from the session
            session()->put('cart', $cart); // Update the session
        }

        return back()->with('success', 'Item removed from cart.');
    }








}
