<?php

namespace App\Services;

use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;

class CartManager
{
    /**
     * Get or create the cart for the current user or session.
     */
    public static function getOrCreateCart(): Cart
    {
        if (Auth::check()) {
            // Logged in user: match by user_id
            $cart = Cart::firstOrCreate(['user_id' => Auth::id()]);
            
            // If they had a guest cart session, we can migrate it
            $sessionId = Session::getId();
            $guestCart = Cart::where('session_id', $sessionId)->first();
            if ($guestCart && $guestCart->id !== $cart->id) {
                foreach ($guestCart->items as $item) {
                    // Check if user cart already has this item
                    $existingItem = $cart->items()
                        ->where('product_id', $item->product_id)
                        ->where('product_variant_id', $item->product_variant_id)
                        ->first();

                    if ($existingItem) {
                        $existingItem->update(['quantity' => $existingItem->quantity + $item->quantity]);
                        $item->delete();
                    } else {
                        $item->update(['cart_id' => $cart->id]);
                    }
                }
                $guestCart->delete();
            }
            return $cart;
        }

        // Guest user: match by session ID
        $sessionId = Session::getId();
        return Cart::firstOrCreate(['session_id' => $sessionId]);
    }

    /**
     * Add product or variant to cart.
     */
    public static function addToCart(int $productId, ?int $variantId = null, int $quantity = 1): array
    {
        $cart = self::getOrCreateCart();
        $product = Product::find($productId);

        if (!$product || !$product->is_visible) {
            return ['success' => false, 'message' => 'Product is not available.'];
        }

        // Verify stock limit
        $availableStock = $product->quantity;
        if ($variantId) {
            $variant = ProductVariant::find($variantId);
            if (!$variant || $variant->product_id !== $productId) {
                return ['success' => false, 'message' => 'Invalid product variant selected.'];
            }
            $availableStock = $variant->quantity;
        }

        // Check if item already in cart
        $cartItem = $cart->items()
            ->where('product_id', $productId)
            ->where('product_variant_id', $variantId)
            ->first();

        $currentQty = $cartItem ? $cartItem->quantity : 0;
        $newQty = $currentQty + $quantity;

        if ($newQty > $availableStock) {
            return [
                'success' => false,
                'message' => 'Requested quantity exceeds available stock (' . $availableStock . ' available).'
            ];
        }

        if ($cartItem) {
            $cartItem->update(['quantity' => $newQty]);
        } else {
            $cart->items()->create([
                'product_id' => $productId,
                'product_variant_id' => $variantId,
                'quantity' => $quantity,
            ]);
        }

        return ['success' => true, 'message' => 'Product added to cart successfully.'];
    }

    /**
     * Update item quantity.
     */
    public static function updateQuantity(int $cartItemId, int $quantity): array
    {
        $cart = self::getOrCreateCart();
        $cartItem = $cart->items()->find($cartItemId);

        if (!$cartItem) {
            return ['success' => false, 'message' => 'Item not found in cart.'];
        }

        if ($quantity <= 0) {
            $cartItem->delete();
            return ['success' => true, 'message' => 'Item removed from cart.'];
        }

        // Verify stock limit
        $availableStock = $cartItem->variant ? $cartItem->variant->quantity : $cartItem->product->quantity;
        if ($quantity > $availableStock) {
            return [
                'success' => false,
                'message' => 'Quantity exceeds available stock (' . $availableStock . ' available).'
            ];
        }

        $cartItem->update(['quantity' => $quantity]);
        return ['success' => true, 'message' => 'Cart updated.'];
    }

    /**
     * Remove item from cart.
     */
    public static function removeItem(int $cartItemId): bool
    {
        $cart = self::getOrCreateCart();
        $cartItem = $cart->items()->find($cartItemId);
        
        if ($cartItem) {
            $cartItem->delete();
            return true;
        }

        return false;
    }

    /**
     * Get subtotal of cart items.
     */
    public static function getSubtotal(): float
    {
        $cart = self::getOrCreateCart();
        $subtotal = 0.00;

        foreach ($cart->items as $item) {
            $price = $item->variant && $item->variant->price !== null && floatval($item->variant->price) > 0
                ? $item->variant->price 
                : ($item->product->sale_price ?? $item->product->price);
            
            $subtotal += $price * $item->quantity;
        }

        return $subtotal;
    }

    /**
     * Clear the cart.
     */
    public static function clearCart(): void
    {
        $cart = self::getOrCreateCart();
        $cart->items()->delete();
    }
}
