<?php
require_once __DIR__ . '/includes/config.php';

$action = $_POST['action'] ?? '';

if ($action === 'add') {
    $productId = (int)($_POST['product_id'] ?? 0);
    $stmt = getDB()->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$productId]);
    $product = $stmt->fetch();

    if ($product) {
        $cart = $_SESSION['cart'] ?? [];
        if (isset($cart[$productId])) {
            $cart[$productId]['quantity']++;
        } else {
            $cart[$productId] = [
                'name'     => $product['name'],
                'quantity' => 1,
                'price'    => $product['discount_price'],
                'image'    => $product['image_url'],
                'slug'     => $product['slug'],
            ];
        }
        $_SESSION['cart'] = $cart;
        $_SESSION['success'] = 'Product added to cart successfully!';
    }
    header('Location: /cart.php');
    exit;
}

if ($action === 'remove') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id && isset($_SESSION['cart'][$id])) {
        unset($_SESSION['cart'][$id]);
        $_SESSION['success'] = 'Product removed successfully';
    }
    header('Location: /cart.php');
    exit;
}

header('Location: /');
exit;
