<?php
session_start();
require_once __DIR__ . '/includes/config.php';

// Add to cart functionality
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_to_cart'])) {
    $product_id = intval($_POST['product_id']);
    $variant_id = isset($_POST['variant_id']) ? intval($_POST['variant_id']) : null;
    $quantity = intval($_POST['quantity']);
    
    // Initialize cart if not exists
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
    }
    
    // Check if item already in cart
    $found = false;
    foreach ($_SESSION['cart'] as &$item) {
        if ($item['product_id'] == $product_id && $item['variant_id'] == $variant_id) {
            $item['quantity'] += $quantity;
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $_SESSION['cart'][] = [
            'product_id' => $product_id,
            'variant_id' => $variant_id,
            'quantity' => $quantity
        ];
    }
    
    header("Location: cart.php");
    exit();
}

// Remove item from cart
if (isset($_GET['remove'])) {
    $index = intval($_GET['remove']);
    if (isset($_SESSION['cart'][$index])) {
        unset($_SESSION['cart'][$index]);
        $_SESSION['cart'] = array_values($_SESSION['cart']); // Reindex array
    }
    header("Location: cart.php");
    exit();
}

// Update quantities
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_cart'])) {
    foreach ($_POST['quantities'] as $index => $quantity) {
        if (isset($_SESSION['cart'][$index])) {
            $_SESSION['cart'][$index]['quantity'] = intval($quantity);
        }
    }
    header("Location: cart.php");
    exit();
}

$pageTitle = 'Shopping Cart';
require_once __DIR__ . '/includes/header.php';
?>

<main class="cart-page">
    <div class="container">
        <h1>Your Shopping Cart</h1>
        
        <?php if (empty($_SESSION['cart'])): ?>
            <div class="empty-cart">
                <p>Your cart is empty.</p>
                <a href="shop.php" class="btn">Continue Shopping</a>
            </div>
        <?php else: ?>
            <form action="cart.php" method="post">
                <table class="cart-table">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Price</th>
                            <th>Quantity</th>
                            <th>Subtotal</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $total = 0;
                        foreach ($_SESSION['cart'] as $index => $item): 
                            // Get product details
                            $product_sql = "SELECT name, base_price, image_url FROM products WHERE product_id = ?";
                            $stmt = $conn->prepare($product_sql);
                            $stmt->bind_param("i", $item['product_id']);
                            $stmt->execute();
                            $product_result = $stmt->get_result();
                            $product = $product_result->fetch_assoc();
                            
                            // Get variant details if exists
                            $variant_name = '';
                            $price = $product['base_price'];
                            
                            if ($item['variant_id']) {
                                $variant_sql = "SELECT variant_name, price FROM product_variants WHERE variant_id = ?";
                                $stmt = $conn->prepare($variant_sql);
                                $stmt->bind_param("i", $item['variant_id']);
                                $stmt->execute();
                                $variant_result = $stmt->get_result();
                                $variant = $variant_result->fetch_assoc();
                                
                                if ($variant) {
                                    $variant_name = $variant['variant_name'];
                                    $price = $variant['price'];
                                }
                            }
                            
                            $subtotal = $price * $item['quantity'];
                            $total += $subtotal;
                        ?>
                        <tr>
                            <td class="product-info">
                                <img src="<?php echo BASE_URL; ?>/images/products/<?php echo htmlspecialchars($product['image_url']); ?>" alt="<?php echo htmlspecialchars($product['name']); ?>">
                                <div>
                                    <h4><?php echo htmlspecialchars($product['name']); ?></h4>
                                    <?php if ($variant_name): ?>
                                        <p>Option: <?php echo htmlspecialchars($variant_name); ?></p>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="price">KShs <?php echo number_format($price, 2); ?></td>
                            <td class="quantity">
                                <input type="number" name="quantities[<?php echo $index; ?>]" 
                                       value="<?php echo $item['quantity']; ?>" min="1">
                            </td>
                            <td class="subtotal">KShs <?php echo number_format($subtotal, 2); ?></td>
                            <td class="remove">
                                <a href="cart.php?remove=<?php echo $index; ?>" class="remove-item">
                                    <i class="fas fa-times"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="total-label">Total</td>
                            <td colspan="2" class="total">KShs <?php echo number_format($total, 2); ?></td>
                        </tr>
                    </tfoot>
                </table>
                
                <div class="cart-actions">
                    <a href="shop.php" class="btn btn-secondary">Continue Shopping</a>
                    <button type="submit" name="update_cart" class="btn">Update Cart</button>
                    <a href="checkout.php" class="btn btn-primary">Proceed to Checkout</a>
                </div>
            </form>
        <?php endif; ?>
    </div>
</main>

<?php
require_once __DIR__ . '/includes/footer.php';
?>