<?php

declare(strict_types=1);

namespace App\Http\Controllers\Market;

use App\Models\Market\Cart;
use App\Models\Market\CartItem;
use App\Models\Market\Product;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Response;
use Hypervel\Support\Str;

class CartController
{
    public function getCart()
    {
        $user = Auth::user();
        if (!$user) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $cart = Cart::firstOrCreate(['user_id' => $user->id]);

        $items = $cart->items()->with('product')->get();

        return Response::json([
            'success' => true,
            'cart' => $cart,
            'items' => $items,
            'total' => $items->sum(fn($item) => $item->price * $item->quantity)
        ]);
    }

    public function addItem(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $request->validate([
            'product_hash' => 'required|string',
            'quantity' => 'nullable|integer|min:1',
        ]);

        $product = Product::where('hashkey', $request->input('product_hash'))->first();
        if (!$product) {
            return Response::json(['error' => 'Product not found'], 404);
        }

        $cart = Cart::firstOrCreate(['user_id' => $user->id]);
        
        $item = $cart->items()->where('product_id', $product->id)->first();
        
        if ($item) {
            $item->quantity += $request->input('quantity', 1);
            $item->save();
        } else {
            $cart->items()->create([
                'product_id' => $product->id,
                'quantity' => $request->input('quantity', 1),
                'price' => $product->price,
                'is_active' => true,
                'hashkey' => Str::uuid()->toString(),
            ]);
        }

        return Response::json(['success' => true, 'message' => 'Item added to cart']);
    }

    public function updateItem(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $request->validate([
            'item_hash' => 'required|string',
            'quantity' => 'required|integer|min:1',
        ]);

        $item = CartItem::where('hashkey', $request->input('item_hash'))->first();
        if (!$item) {
            return Response::json(['error' => 'Item not found'], 404);
        }

        // Verify cart ownership
        $cart = Cart::find($item->cart_id);
        if ($cart->user_id !== $user->id) {
            return Response::json(['error' => 'Forbidden'], 403);
        }

        $item->quantity = $request->input('quantity');
        $item->save();

        return Response::json(['success' => true, 'message' => 'Cart updated']);
    }

    public function removeItem(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $request->validate([
            'item_hash' => 'required|string',
        ]);

        $item = CartItem::where('hashkey', $request->input('item_hash'))->first();
        if (!$item) {
            return Response::json(['error' => 'Item not found'], 404);
        }

        $cart = Cart::find($item->cart_id);
        if ($cart->user_id !== $user->id) {
            return Response::json(['error' => 'Forbidden'], 403);
        }

        $item->delete();

        return Response::json(['success' => true, 'message' => 'Item removed from cart']);
    }

    public function clearCart()
    {
        $user = Auth::user();
        if (!$user) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }

        $cart = Cart::where('user_id', $user->id)->first();
        if ($cart) {
            $cart->items()->delete();
        }

        return Response::json(['success' => true, 'message' => 'Cart cleared']);
    }
}
