<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Cart;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    // Add to Cart
    public function addToCart(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
            'price'      => 'required|numeric',
        ]);

        $userId = auth()->id(); // null for guest if not logged in

        // Check if product already exists in cart
        $cartItem = Cart::where('user_id', $userId)
            ->where('product_id', $request->product_id)
            ->first();

        if ($cartItem) {
            // Product exists → increase quantity
            $cartItem->quantity += $request->quantity;
            $cartItem->save();
        } else {
            // Product not in cart → create new
            Cart::create([
                'user_id'    => $userId,
                'product_id' => $request->product_id,
                'quantity'   => $request->quantity,
                'price'      => $request->price,
            ]);
        }

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


    // Get Cart (Guest OR Logged-in)
    public function getCart(Request $request)
    {

        // Authenticated cart
        $cart = Cart::where('user_id', Auth::id())
            ->with('product.images')
            ->get();


        return response()->json([
            'cart' => $cart
        ]);
    }


    // Update Cart
    public function updateCart(Request $request)
    {
        $request->validate([
            'cart_id'  => 'required|exists:carts,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $cart = Cart::find($request->cart_id);
        $cart->update([
            'quantity' => $cart->quantity + $request->quantity
        ]);

        return response()->json([
            'message' => 'Cart updated',
            'cart' => $cart
        ]);
    }


    // Remove Cart Item
    public function removeFromCart($id)
    {
        Cart::destroy($id);

        return response()->json([
            'message' => 'Item removed from cart'
        ]);
    }
}
