<?php
// Cart Functions
class Cart {
    private $items = [];
    
    public function __construct() {
        if (!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = [];
        }
        $this->items = &$_SESSION['cart'];
    }
    
    // Add item to cart
    public function add($product, $quantity = 1, $size = null, $color = null) {
        $key = $this->generateKey($product['id'], $size, $color);
        
        if (isset($this->items[$key])) {
            $this->items[$key]['quantity'] += $quantity;
        } else {
            $this->items[$key] = [
                'id' => $product['id'],
                'name' => $product['name'],
                'price' => $product['price'],
                'image_url' => $product['image_url'],
                'quantity' => $quantity,
                'size' => $size,
                'color' => $color
            ];
        }
        
        return ['success' => true];
    }
    
    // Update item quantity
    public function update($key, $quantity) {
        if (isset($this->items[$key])) {
            if ($quantity > 0) {
                $this->items[$key]['quantity'] = $quantity;
            } else {
                unset($this->items[$key]);
            }
            return ['success' => true];
        }
        return ['success' => false, 'message' => 'Item not found'];
    }
    
    // Remove item from cart
    public function remove($key) {
        if (isset($this->items[$key])) {
            unset($this->items[$key]);
            return ['success' => true];
        }
        return ['success' => false, 'message' => 'Item not found'];
    }
    
    // Clear cart
    public function clear() {
        $this->items = [];
        return ['success' => true];
    }
    
    // Get cart items
    public function getItems() {
        return $this->items;
    }
    
    // Get cart count
    public function getCount() {
        $count = 0;
        foreach ($this->items as $item) {
            $count += $item['quantity'];
        }
        return $count;
    }
    
    // Get cart total
    public function getTotal() {
        $total = 0;
        foreach ($this->items as $item) {
            $total += $item['price'] * $item['quantity'];
        }
        return $total;
    }
    
    // Generate unique key for cart item
    private function generateKey($productId, $size, $color) {
        return $productId . '-' . ($size ?: 'no-size') . '-' . ($color ?: 'no-color');
    }
    
    // Get items formatted for order
    public function getOrderItems() {
        $items = [];
        foreach ($this->items as $key => $item) {
            $items[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'price' => $item['price'],
                'quantity' => $item['quantity'],
                'size' => $item['size'],
                'color' => $item['color']
            ];
        }
        return $items;
    }
}
