<?php
ini_set('display_errors', 0);
error_reporting(0);

require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');
if (session_status() === PHP_SESSION_NONE) { session_start(); }

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

$submitted_token = $_POST['order_token'] ?? '';
$session_token = $_SESSION['order_token'] ?? null;

if (empty($submitted_token) || empty($session_token) || $submitted_token !== $session_token) {
    http_response_code(409);
    echo json_encode(['status' => 'error', 'message' => 'Lỗi phiên tạo đơn, đơn hàng có thể đã được tạo. Vui lòng tải lại trang.']);
    exit();
}

unset($_SESSION['order_token']);

$conn->begin_transaction();
try {
    $customer_id = intval($_POST['customer_id'] ?? 1);
    $items_json = $_POST['cart_items'] ?? '[]';
    $items = json_decode($items_json, true);

    if (empty($items) || !is_array($items) || json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Giỏ hàng trống hoặc dữ liệu không hợp lệ.");
    }

    $product_ids = array_column($items, 'id');
    if (empty($product_ids)) {
        throw new Exception("Không có sản phẩm nào trong giỏ hàng.");
    }
    
    $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
    $types = str_repeat('i', count($product_ids));

    $stmt_check = $conn->prepare("SELECT ID, prd_name, prd_sls, prd_average_cost FROM cms_products WHERE ID IN ($ids_placeholder) FOR UPDATE");
    $stmt_check->bind_param($types, ...$product_ids);
    $stmt_check->execute();
    $products_from_db = array_column($stmt_check->get_result()->fetch_all(MYSQLI_ASSOC), null, 'ID');
    $stmt_check->close();

    $total_price = 0;
    $total_origin_price = 0;
    $total_quantity = 0;

    foreach ($items as &$item) {
        $product_id = intval($item['id']);
        if (!isset($products_from_db[$product_id])) {
            throw new Exception("Sản phẩm '{$item['name']}' không tồn tại.");
        }
        $db_product = $products_from_db[$product_id];
        $item['origin_price'] = floatval($db_product['prd_average_cost']);

        if (floatval($item['quantity']) > floatval($db_product['prd_sls'])) {
            throw new Exception("Sản phẩm '{$db_product['prd_name']}' không đủ tồn kho (còn {$db_product['prd_sls']}).");
        }
        
        $total_price += floatval($item['price']) * floatval($item['quantity']);
        $total_origin_price += $item['origin_price'] * floatval($item['quantity']);
        $total_quantity += floatval($item['quantity']);
    }
    unset($item);

    $items_json_updated = json_encode($items);
    $store_id = $_SESSION['store_id'] ?? 0;
    $last_id_result = $conn->query("SELECT ID FROM cms_orders ORDER BY ID DESC LIMIT 1");
    $last_id = $last_id_result ? ($last_id_result->fetch_row()[0] ?? 0) : 0;
    $output_code = 'BH' . str_pad($last_id + 1, 6, '0', STR_PAD_LEFT);
    
    $sql_order = "INSERT INTO cms_orders (output_code, store_id, customer_id, sell_date, total_price, 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);
    
    $total_money = $total_price;
    $lack = 0;
    $stmt_order->bind_param('siidddsisdd', $output_code, $store_id, $customer_id, $total_price, $total_money, $total_origin_price, $items_json_updated, $user_id, $total_quantity, $total_money, $lack);
    $stmt_order->execute();

    if ($stmt_order->affected_rows === 0) {
        throw new Exception("Không thể lưu đơn hàng vào CSDL.");
    }
    $new_order_id = $conn->insert_id;
    $stmt_order->close();

    $stmt_update_product = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ? WHERE ID = ?");
    $update_qty = 0;
    $update_id = 0;
    $stmt_update_product->bind_param("di", $update_qty, $update_id);
    foreach ($items as $item) {
        $update_qty = floatval($item['quantity']);
        $update_id = intval($item['id']);
        $stmt_update_product->execute();
    }
    $stmt_update_product->close();

    $conn->commit();
    echo json_encode(['status' => 'success', 'message' => "Đơn hàng {$output_code} đã được tạo thành công!", 'order_id' => $new_order_id]);

} catch (Exception $e) {
    $conn->rollback();
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>