<?php

class CartController {

    // ─── GET /api/cart ────────────────────────────────────────────────────────
    public static function getCart(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        $stmt = $db->prepare(
            "SELECT ci.id, ci.product_id, ci.quantity,
                    p.name, p.price, p.discount_percent, p.images, p.stock
             FROM cart_items ci
             JOIN products p ON p.id = ci.product_id
             WHERE ci.user_id = ?"
        );
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        $subtotal = 0;
        foreach ($items as &$item) {
            $effectivePrice          = ProductController::effectivePrice($item['price'], $item['discount_percent']);
            $item['effective_price'] = $effectivePrice;
            $item['line_total']      = round($effectivePrice * $item['quantity'], 2);
            $subtotal               += $item['line_total'];
        }

        sendSuccess([
            'items'    => $items,
            'subtotal' => round($subtotal, 2),
        ]);
    }

    // ─── POST /api/cart/add ───────────────────────────────────────────────────
    public static function addToCart(): void {
        $user      = AuthController::requireAuth();
        $userId    = $user['id'];
        $body      = getJsonBody();

        $productId = (int)($body['product_id'] ?? 0);
        $quantity  = max(1, (int)($body['quantity'] ?? 1));

        if (!$productId) sendError('Product ID is required', 422);

        $db = getDb();

        // Verify product exists & has stock
        $stmt = $db->prepare("SELECT id, stock FROM products WHERE id = ? AND stock > 0 LIMIT 1");
        $stmt->bind_param('i', $productId);
        $stmt->execute();
        $product = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if (!$product) sendError('Product not found', 404);
        if ($product['stock'] < $quantity) sendError('Insufficient stock', 409);

        // Upsert
        $stmt = $db->prepare(
            "INSERT INTO cart_items (user_id, product_id, quantity)
             VALUES (?, ?, ?)
             ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)"
        );
        $stmt->bind_param('iii', $userId, $productId, $quantity);
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Item added to cart');
    }

    // ─── POST /api/cart/update ────────────────────────────────────────────────
    public static function updateCart(): void {
        $user      = AuthController::requireAuth();
        $userId    = $user['id'];
        $body      = getJsonBody();

        $cartItemId = (int)($body['cart_item_id'] ?? 0);
        $quantity   = max(1, (int)($body['quantity'] ?? 1));

        if (!$cartItemId) sendError('cart_item_id is required', 422);

        $db   = getDb();
        $stmt = $db->prepare("UPDATE cart_items SET quantity = ? WHERE id = ? AND user_id = ?");
        $stmt->bind_param('iii', $quantity, $cartItemId, $userId);
        $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        if (!$affected) sendError('Cart item not found', 404);
        sendSuccess(null, 'Cart updated');
    }

    // ─── POST /api/cart/remove ────────────────────────────────────────────────
    public static function removeFromCart(): void {
        $user       = AuthController::requireAuth();
        $userId     = $user['id'];
        $body       = getJsonBody();
        $cartItemId = (int)($body['cart_item_id'] ?? 0);

        if (!$cartItemId) sendError('cart_item_id is required', 422);

        $db   = getDb();
        $stmt = $db->prepare("DELETE FROM cart_items WHERE id = ? AND user_id = ?");
        $stmt->bind_param('ii', $cartItemId, $userId);
        $stmt->execute();
        $affected = $stmt->affected_rows;
        $stmt->close();

        if (!$affected) sendError('Cart item not found', 404);
        sendSuccess(null, 'Item removed from cart');
    }

    // ─── POST /api/cart/clear ─────────────────────────────────────────────────
    public static function clearCart(): void {
        $user   = AuthController::requireAuth();
        $userId = $user['id'];
        $db     = getDb();

        $stmt = $db->prepare("DELETE FROM cart_items WHERE user_id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $stmt->close();

        sendSuccess(null, 'Cart cleared');
    }
}
