<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php'; // defines $conn (MySQLi)

// Read raw POST input
$input = file_get_contents("php://input");
$data = json_decode($input, true);

if (!is_array($data) || empty($data['user_id']) || empty($data['items']) || !is_array($data['items'])) {
    echo json_encode(["success" => false, "message" => "Invalid payload"]);
    exit;
}

$user_id = (int)$data['user_id'];
$items   = $data['items'];

$conn->begin_transaction();

try {
    $stmt = $conn->prepare("
        INSERT INTO tblcart (user_id, product_id, service_id, quantity, unit_price, total_price)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    foreach ($items as $item) {
        $product_id  = (int)$item['product_id'];
        $service_id  = (int)$item['service_id'];
        $quantity    = (int)$item['quantity'];
        $unit_price  = (float)$item['unit_price'];
        $total_price = (float)$item['total_price'];

        $stmt->bind_param("iiiidd", $user_id, $product_id, $service_id, $quantity, $unit_price, $total_price);
        $stmt->execute();
    }

    $stmt->close();
    $conn->commit();

    echo json_encode(["success" => true, "message" => "Items added to cart"]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(["success" => false, "message" => "Database error: " . $e->getMessage()]);
}

$conn->close();
?>