<?php
require_once 'includes/init.php';
require_login();

// Initialize cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'add':
            $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
            $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;

            if ($product_id > 0 && $quantity > 0) {
                // If product is already in cart, update quantity
                if (isset($_SESSION['cart'][$product_id])) {
                    $_SESSION['cart'][$product_id] += $quantity;
                } else {
                    $_SESSION['cart'][$product_id] = $quantity;
                }
            }
            break;

        case 'update':
            $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
            $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;

            if ($product_id > 0) {
                if ($quantity > 0) {
                    $_SESSION['cart'][$product_id] = $quantity;
                } else {
                    // Remove item if quantity is 0 or less
                    unset($_SESSION['cart'][$product_id]);
                }
            }
            break;

        case 'remove':
            $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
            if ($product_id > 0) {
                unset($_SESSION['cart'][$product_id]);
            }
            break;
    }

    if ($action === 'add' && isset($product_id)) {
        header('Location: related_suggestions.php?product_id=' . $product_id . '&qty=' . $quantity);
    } else {
        // Redirect back to the appropriate page
        $redirect_url = $_POST['redirect_to'] ?? 'index.php';
        header('Location: ' . $redirect_url);
    }
    exit;
}
