<?php
header('Content-Type: application/json');
require_once('config.php');

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$cart = isset($data['cart']) ? $data['cart'] : [];

if (empty($cart)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid cart data'
    ]);
    exit;
}

try {
    // Begin transaction
    $con->begin_transaction();

    foreach ($cart as $item) {
        $productId = (int)$item['id'];
        $quantity = (int)$item['quantity'];

        // Update stock (allow negative values)
        $query = "UPDATE tbl_stock_items 
                  SET status='Confirmed',stock = stock - ? 
                  WHERE id = ?";
        $stmt = $con->prepare($query);
        $stmt->bind_param("ii", $quantity, $productId);
        $stmt->execute();

        if ($stmt->affected_rows === 0) {
            throw new Exception("Failed to update stock for product ID: $productId");
        }
    }

    // Commit transaction
    $con->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Stock updated successfully'
    ]);

} catch (Exception $e) {
    $con->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to update stock: ' . $e->getMessage()
    ]);
}
?>
