<?php
class Cart {
    private $db;

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

    public function addItemToCart($userId, $itemId, $quantity, $totalPrice) {
        $sql = "INSERT INTO cart (user_id, item_id, quantity, total_price) 
                VALUES ('$userId', '$itemId', '$quantity', '$totalPrice') 
                ON DUPLICATE KEY UPDATE 
                quantity = quantity + VALUES(quantity), 
                total_price = total_price + VALUES(total_price)";
        $this->db->query($sql);
    }

    public function getItemsByUserId($userId) {
        $userId = $this->db->escape($userId);

        return $this->db->query("
        SELECT c.item_id, 
               i.name as item_name, 
               i.price as unit_price,
               SUM(c.quantity) as total_quantity, 
               SUM(c.total_price) as total_price
        FROM cart c 
        JOIN items i ON c.item_id = i.id 
        WHERE c.user_id = '" . $userId . "'
        GROUP BY c.item_id, i.price;
        ")->rows;
    }

    public function updateItemQuantity($userId, $itemId, $quantity) {
        $userId = $this->db->escape($userId);
        $itemId = $this->db->escape($itemId);
        $quantity = $this->db->escape($quantity);

        $sql = "UPDATE cart 
                SET quantity = '$quantity', 
                    total_price = '$quantity' * (SELECT price FROM items WHERE id = '$itemId')
                WHERE user_id = '$userId' AND item_id = '$itemId'";
        $this->db->query($sql);
    }

    public function createOrderAndClearCart($userId) {
        $this->db->query("START TRANSACTION");

        try {
            $cartItems = $this->db->query("SELECT item_id, quantity, items.price, items.name AS item_name
                                        FROM cart
                                        JOIN items ON cart.item_id = items.id
                                        WHERE cart.user_id = '$userId'")->rows;
            foreach ($cartItems as $item) {
                $orderNumber = $userId . date('YmdHis');
                $this->db->query("INSERT INTO orders (user_id, item_id, item_name, unit_price, quantity, stock) 
                                  VALUES ('$userId', '{$item['item_id']}', '{$item['item_name']}', '{$item['price']}', '{$item['quantity']}', '{$item['quantity']}')
                                  ON DUPLICATE KEY UPDATE 
                                  quantity = quantity + VALUES(quantity), 
                                  stock = stock + VALUES(stock)");
                if ($this->db->countAffected() <= 0) {
                    error_log('Failed to insert or update order for user: ' . $userId);
                    throw new Exception('Failed to create or update order.');
                }
            }

            // Clear the cart
            $this->db->query("DELETE FROM cart WHERE user_id = '$userId'");
            if ($this->db->countAffected() <= 0 && count($cartItems) > 0) {
                error_log('Failed to clear cart for user: ' . $userId);
                throw new Exception('Failed to clear cart.');
            }

            $this->db->query("COMMIT");
            return ['success' => true, 'message' => 'Order created or updated and cart cleared'];
        } catch (Exception $e) {
            $this->db->query("ROLLBACK");
            error_log('Transaction failed: ' . $e->getMessage());
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }

    public function removeItemFromCart($userId, $itemId) {
        $userId = $this->db->escape($userId);
        $itemId = $this->db->escape($itemId);

        $sql = "DELETE FROM cart WHERE user_id = '$userId' AND item_id = '$itemId'";
        $this->db->query($sql);

        return $this->db->countAffected() > 0;
    }
}
?>