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

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

if (!isset($data['user_id'])) {
    echo json_encode(['success' => false, 'msg' => 'User ID missing']);
    exit;
}

$user_id = intval($data['user_id']);

// 1. Fetch cart items
$cartItems = [];
$total_amount = 0.0;

$query = "SELECT product_id, service_id, quantity, unit_price, total_price
          FROM tblcart
          WHERE user_id = $user_id";

$result = $conn->query($query);
while ($row = $result->fetch_assoc()) {
    $cartItems[] = $row;
    $total_amount += floatval($row['total_price']);
}

if (empty($cartItems)) {
    echo json_encode(['success' => false, 'msg' => 'Cart is empty']);
    exit;
}

$conn->begin_transaction();
try {
    // 2. Insert into tbl_order
    $stmt = $conn->prepare("INSERT INTO tbl_order (user_id, total_amount) VALUES (?, ?)");
    $stmt->bind_param("id", $user_id, $total_amount);
    $stmt->execute();
    $order_id = $stmt->insert_id;
    $stmt->close();

    // 3. Insert into tbl_order_items
    $stmt = $conn->prepare("INSERT INTO tbl_order_items 
        (order_id, product_id, service_id, quantity, unit_price, total_price)
        VALUES (?, ?, ?, ?, ?, ?)");

    foreach ($cartItems as $item) {
        $stmt->bind_param(
            "iiiidd",
            $order_id,
            $item['product_id'],
            $item['service_id'],
            $item['quantity'],
            $item['unit_price'],
            $item['total_price']
        );
        $stmt->execute();
    }
    $stmt->close();

    // 4. Clear cart
    $conn->query("DELETE FROM tblcart WHERE user_id = $user_id");

    $conn->commit();
    echo json_encode(['success' => true, 'order_id' => $order_id]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'msg' => 'Transaction failed']);
}
?>