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

if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['product_id'])) {
    header("Location: shop.php");
    exit();
}

$product_id = intval($_POST['product_id']);
$variant_id = isset($_POST['variant_id']) ? intval($_POST['variant_id']) : null;
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

// 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();
?>