<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $cartDataFromClient = json_decode($input, true);

    if (json_last_error() === JSON_ERROR_NONE && is_array($cartDataFromClient)) {
        // Transform client data to match server-side expectations if necessary
        // The client sends: { title: "Product", price: "₱5.00", quantity: 1 }
        // The server (getCartItemsForReceipt) expects: { name: "Product", price: 5.00, quantity: 1 }
        
        $processedCartData = [];
        foreach ($cartDataFromClient as $item) {
            $priceString = isset($item['price']) ? str_replace('₱', '', $item['price']) : '0';
            $processedCartData[] = [
                'name' => $item['title'] ?? 'Unknown Item',
                'price' => isset($item['price']) ? floatval($priceString) : 0.0,
                'quantity' => $item['quantity'] ?? 0
            ];
        }
        $_SESSION['cart'] = $processedCartData;
        echo json_encode(['success' => true, 'message' => 'Cart updated successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid cart data received. Error: ' . json_last_error_msg()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?> 