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

include '../connection.php';

$user_id = isset($_POST['user_id']) ? $_POST['user_id'] : '';

if (empty($user_id)) {
    echo json_encode(["error" => "Missing user_id"]);
    exit;
}

$sql = "SELECT
            c.id,
            c.user_id,
            c.product_id,
            c.service_id,
            c.quantity,
            c.unit_price,
            c.total_price,
            p.name as product_name,
            s.name as service_name
        FROM tblcart c
        LEFT JOIN tbl_product_type p ON c.product_id = p.id
        LEFT JOIN tbl_service_type s ON c.service_id = s.id
        WHERE c.user_id = '".mysqli_real_escape_string($conn, $user_id)."'";

$result = mysqli_query($conn, $sql);

if (!$result) {
    echo json_encode(["error" => mysqli_error($conn)]);
    exit;
}

$cart = [];
while ($row = mysqli_fetch_assoc($result)) {
    // Ensure numeric fields are returned in a consistent way
    $row['quantity'] = isset($row['quantity']) ? (int)$row['quantity'] : 0;
    // Cast decimals to string so JSON keeps precision; the client will parse to double
    $row['unit_price'] = isset($row['unit_price']) ? (string)$row['unit_price'] : "0.00";
    $row['total_price'] = isset($row['total_price']) ? (string)$row['total_price'] : null;

    $cart[] = $row;
}

echo json_encode($cart);

