<?php
class CartController {
    private $cartModel;

    public function __construct($cartModel) {
        $this->cartModel = $cartModel;
    }

    public function getCartItems($userId) {
        return $this->cartModel->getItemsByUserId($userId);
    }

    public function addToCart($userId, $itemId, $quantity, $totalPrice) {
        $this->cartModel->addItemToCart($userId, $itemId, $quantity, $totalPrice);
    }

    public function updateItemQuantity() {
        $userId = $_SESSION['user_id'];
        $data = json_decode(file_get_contents('php://input'), true);
        if (isset($data['itemId'], $data['quantity'])) {
            $itemId = $data['itemId'];
            $quantity = $data['quantity'];
            $this->cartModel->updateItemQuantity($userId, $itemId, $quantity);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid data']);
        }
    }

    public function confirmOrder() {
        $userId = $_SESSION['user_id'];
        $result = $this->cartModel->createOrderAndClearCart($userId);
        echo json_encode($result);
    }

    public function removeItem() {
        $userId = $_SESSION['user_id'];
        $data = json_decode(file_get_contents('php://input'), true);
        if (isset($data['itemId'])) {
            $itemId = $data['itemId'];
            $result = $this->cartModel->removeItemFromCart($userId, $itemId);
            if ($result) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete item']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid data']);
        }
    }
}
?>