<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    /**
     * Get the current cart.
     */
    public function index(Request $request)
    {
        $cart = session()->get('cart', []);
        $cartItems = [];
        $total = 0;
        $subtotal = 0;

        foreach ($cart as $productId => $item) {
            $product = Product::with('images')->find($productId);
            if ($product) {
                $price = $product->sale_price ?? $product->price;
                $itemTotal = $price * $item['quantity'];
                $subtotal += $itemTotal;
                
                $cartItems[] = [
                    'product' => $product,
                    'quantity' => $item['quantity'],
                    'price' => $price,
                    'subtotal' => $itemTotal,
                ];
            }
        }

        $total = $subtotal; // No tax or shipping for now

        return view('cart.index', compact('cartItems', 'subtotal', 'total'));
    }

    /**
     * Add item to cart.
     */
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $product = Product::findOrFail($request->product_id);
        
        if (!$product->availability) {
            return response()->json([
                'success' => false,
                'message' => 'This product is currently unavailable.',
            ], 400);
        }

        $cart = session()->get('cart', []);
        $productId = $request->product_id;
        $quantity = (int) $request->quantity;

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

        session()->put('cart', $cart);

        $cartCount = $this->getCartCount($cart);
        $cartTotal = $this->getCartTotal($cart);

        return response()->json([
            'success' => true,
            'message' => 'Product added to cart!',
            'cart_count' => $cartCount,
            'cart_total' => $cartTotal,
        ]);
    }

    /**
     * Update item quantity in cart.
     */
    public function update(Request $request, $productId)
    {
        $request->validate([
            'quantity' => 'required|integer|min:1',
        ]);

        $cart = session()->get('cart', []);

        if (isset($cart[$productId])) {
            $cart[$productId]['quantity'] = (int) $request->quantity;
            session()->put('cart', $cart);

            $cartCount = $this->getCartCount($cart);
            $cartTotal = $this->getCartTotal($cart);
            $item = $this->getCartItem($productId, $cart);

            return response()->json([
                'success' => true,
                'message' => 'Cart updated!',
                'cart_count' => $cartCount,
                'cart_total' => $cartTotal,
                'item_subtotal' => $item['subtotal'],
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Item not found in cart.',
        ], 404);
    }

    /**
     * Remove item from cart.
     */
    public function remove($productId)
    {
        $cart = session()->get('cart', []);

        if (isset($cart[$productId])) {
            unset($cart[$productId]);
            session()->put('cart', $cart);

            $cartCount = $this->getCartCount($cart);
            $cartTotal = $this->getCartTotal($cart);

            return response()->json([
                'success' => true,
                'message' => 'Item removed from cart!',
                'cart_count' => $cartCount,
                'cart_total' => $cartTotal,
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Item not found in cart.',
        ], 404);
    }

    /**
     * Clear the entire cart.
     */
    public function clear()
    {
        session()->forget('cart');

        return response()->json([
            'success' => true,
            'message' => 'Cart cleared!',
            'cart_count' => 0,
            'cart_total' => 0,
        ]);
    }

    /**
     * Get cart count (API endpoint).
     */
    public function count()
    {
        $cart = session()->get('cart', []);
        $cartCount = $this->getCartCount($cart);
        $cartTotal = $this->getCartTotal($cart);

        return response()->json([
            'count' => $cartCount,
            'total' => $cartTotal,
        ]);
    }

    /**
     * Check if product is in cart and get quantity.
     */
    public function check($productId)
    {
        $cart = session()->get('cart', []);
        $quantity = isset($cart[$productId]) ? $cart[$productId]['quantity'] : 0;
        
        return response()->json([
            'in_cart' => $quantity > 0,
            'quantity' => $quantity,
        ]);
    }

    /**
     * Get cart status for multiple products.
     */
    public function status(Request $request)
    {
        $productIds = $request->get('product_ids', []);
        if (is_string($productIds)) {
            $productIds = explode(',', $productIds);
        }
        
        $cart = session()->get('cart', []);
        $status = [];
        
        foreach ($productIds as $productId) {
            $productId = trim($productId);
            if ($productId) {
                $status[$productId] = [
                    'in_cart' => isset($cart[$productId]),
                    'quantity' => $cart[$productId]['quantity'] ?? 0,
                ];
            }
        }
        
        return response()->json($status);
    }

    /**
     * Get cart count.
     */
    private function getCartCount($cart)
    {
        return array_sum(array_column($cart, 'quantity'));
    }

    /**
     * Get cart total.
     */
    private function getCartTotal($cart)
    {
        $total = 0;
        foreach ($cart as $productId => $item) {
            $product = Product::find($productId);
            if ($product) {
                $price = $product->sale_price ?? $product->price;
                $total += $price * $item['quantity'];
            }
        }
        return number_format($total, 2, '.', '');
    }

    /**
     * Get cart item details.
     */
    private function getCartItem($productId, $cart)
    {
        if (!isset($cart[$productId])) {
            return null;
        }

        $product = Product::find($productId);
        if (!$product) {
            return null;
        }

        $price = $product->sale_price ?? $product->price;
        $quantity = $cart[$productId]['quantity'];
        $subtotal = $price * $quantity;

        return [
            'product' => $product,
            'quantity' => $quantity,
            'price' => $price,
            'subtotal' => $subtotal,
        ];
    }
}
