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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$response = ['status' => 'error', 'message' => 'Có lỗi không xác định.'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Yêu cầu không hợp lệ.';
    echo json_encode($response);
    exit();
}

$userId = $_SESSION['user_id'] ?? 0;
if ($userId === 0) {
    http_response_code(401);
    $response['message'] = 'Phiên làm việc đã hết hạn. Vui lòng đăng nhập lại.';
    echo json_encode($response);
    exit();
}

$customerId = (int)($_POST['customer_id'] ?? 0);
$cartItemsJSON = $_POST['cart_items'] ?? '[]';
$cartItems = json_decode($cartItemsJSON, true);

if (empty($cartItems) || !is_array($cartItems)) {
    $response['message'] = 'Đơn hàng không có sản phẩm.';
    echo json_encode($response);
    exit();
}

$conn->begin_transaction();

try {
    $totalMoney = 0;
    $totalOriginPrice = 0;
    $totalQuantity = 0;
    $finalCartItems = [];

    foreach ($cartItems as $item) {
        $productId = (int)$item['id'];
        $quantity = (int)$item['quantity'];
        $submittedPrice = (float)$item['current_price'];

        $stmt_check = $conn->prepare("SELECT prd_code, prd_sls, prd_origin_price, prd_average_cost FROM cms_products WHERE id = ? FOR UPDATE");
        $stmt_check->bind_param('i', $productId);
        $stmt_check->execute();
        $product = $stmt_check->get_result()->fetch_assoc();
        $stmt_check->close();

        if (!$product) throw new Exception("Sản phẩm ID {$productId} không tồn tại.");
        if ($quantity > $product['prd_sls']) throw new Exception("Sản phẩm '{$item['name']}' không đủ tồn kho.");
        
        $cost_price_for_item = ($product['prd_average_cost'] > 0) ? $product['prd_average_cost'] : $product['prd_origin_price'];

        if ($submittedPrice < $cost_price_for_item) {
            throw new Exception("Giá bán của '{$item['name']}' thấp hơn giá vốn.");
        }
        
        $totalMoney += $submittedPrice * $quantity;
        $totalOriginPrice += $cost_price_for_item * $quantity;
        $totalQuantity += $quantity;
        
        $finalCartItems[] = [
            'id' => $productId,
            'code' => $product['prd_code'],
            'quantity' => $quantity,
            'price' => $submittedPrice,
            'name' => $item['name'],
            'origin_price' => $cost_price_for_item
        ];
    }
    
    $orderCode = 'BH' . str_pad(($conn->query("SELECT ID FROM cms_orders ORDER BY ID DESC LIMIT 1")->fetch_row()[0] ?? 0) + 1, 6, '0', STR_PAD_LEFT);
    $storeId = $_SESSION['store_id'] ?? 0;

    $sql_order = "INSERT INTO cms_orders (output_code, store_id, customer_id, sell_date, total_money, total_origin_price, detail_order, user_init, order_status, total_quantity, customer_pay, lack) VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, 1, ?, ?, ?)";
    $stmt_order = $conn->prepare($sql_order);
    
    $customerPay = $totalMoney; 
    $lack = 0;
    
    $finalCartItemsJSON = json_encode($finalCartItems);
    $stmt_order->bind_param('siiddisidd', $orderCode, $storeId, $customerId, $totalMoney, $totalOriginPrice, $finalCartItemsJSON, $userId, $totalQuantity, $customerPay, $lack);
    $stmt_order->execute();
    
    if($stmt_order->affected_rows == 0) throw new Exception("Không thể tạo đơn hàng.");
    $stmt_order->close();

    foreach ($cartItems as $item) {
        $sql_update_stock = "UPDATE cms_products SET prd_sls = prd_sls - ? WHERE id = ?";
        $stmt_update = $conn->prepare($sql_update_stock);
        $stmt_update->bind_param('ii', $item['quantity'], $item['id']);
        $stmt_update->execute();
        $stmt_update->close();
    }
    
    $conn->commit();
    $response = ['status' => 'success', 'message' => 'Tạo đơn hàng thành công!', 'order_code' => $orderCode];

} catch (Exception $e) {
    $conn->rollback();
    $response['message'] = $e->getMessage();
}

$conn->close();
echo json_encode($response);
?>