<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function index(Request $request)
    {
        $items = CartItem::with('product')->where('user_id', $request->user()->id)->get();
        $total = $items->sum(fn($i) => $i->product->effective_price * $i->quantity);
        return response()->json(['success'=>true,'data'=>$items,'subtotal'=>$total]);
    }

    public function add(Request $request)
    {
        $data = $request->validate(['product_id'=>'required|exists:products,id','quantity'=>'required|integer|min:1','size'=>'nullable|string','color'=>'nullable|string']);
        $product = Product::findOrFail($data['product_id']);
        if($product->stock < $data['quantity'])
            return response()->json(['success'=>false,'message'=>'Insufficient stock.'],422);
        $item = CartItem::updateOrCreate(
            ['user_id'=>$request->user()->id,'product_id'=>$data['product_id'],'size'=>$data['size']??null,'color'=>$data['color']??null],
            ['quantity'=>\DB::raw("quantity + {$data['quantity']}")]
        );
        return response()->json(['success'=>true,'message'=>'Added to cart.','data'=>$item->load('product')]);
    }

    public function update(Request $request, int $id)
    {
        $request->validate(['quantity'=>'required|integer|min:1']);
        $item = CartItem::where('user_id',$request->user()->id)->findOrFail($id);
        $item->update(['quantity'=>$request->quantity]);
        return response()->json(['success'=>true,'data'=>$item]);
    }

    public function remove(Request $request, int $id)
    {
        CartItem::where('user_id',$request->user()->id)->findOrFail($id)->delete();
        return response()->json(['success'=>true,'message'=>'Removed from cart.']);
    }

    public function clear(Request $request)
    {
        CartItem::where('user_id',$request->user()->id)->delete();
        return response()->json(['success'=>true,'message'=>'Cart cleared.']);
    }
}
