<?php
require_once __DIR__ . '/core/init.php';
header('Content-Type: text/html; charset=utf-8');

echo "<!DOCTYPE html><html><head><title>Sửa Lỗi Tiền Vốn Đơn Hàng (V2 - Chẩn đoán)</title>";
echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">';
echo "<style>body { padding: 20px; font-family: monospace; } .table { max-width: 1000px; margin: auto; font-size: 0.9em; } </style>";
echo "</head><body><div class='container-fluid'>";
echo "<h1 class='text-center mb-4'>Tiến trình cập nhật tiền vốn cho các đơn hàng lỗi (V2)</h1>";
echo "<table class='table table-bordered table-striped'><thead><tr><th>Mã Đơn Hàng</th><th>Trạng Thái</th><th>Tiền Vốn Mới</th><th>Chi tiết tính toán</th></tr></thead><tbody>";

$sql_orders = "SELECT id, output_code, detail_order FROM cms_orders WHERE total_origin_price = 0 AND deleted = 0";
$orders_result = $conn->query($sql_orders);
$orders_to_fix = $orders_result->fetch_all(MYSQLI_ASSOC);

if (count($orders_to_fix) === 0) {
    echo "<tr><td colspan='4' class='text-center alert alert-success'>Không tìm thấy đơn hàng nào có tiền vốn bằng 0. Dữ liệu đã chính xác!</td></tr>";
} else {
    $stmt_product_cost = $conn->prepare("SELECT IF(prd_average_cost > 0, prd_average_cost, prd_origin_price) as correct_cost FROM cms_products WHERE id = ?");
    $stmt_update_order = $conn->prepare("UPDATE cms_orders SET total_origin_price = ? WHERE id = ?");
    $updated_count = 0;

    foreach ($orders_to_fix as $order) {
        $order_id = $order['id'];
        $order_code = $order['output_code'];
        $products = json_decode($order['detail_order'], true);
        $new_total_cost = 0;
        $calculation_details = '';

        if (is_array($products) && !empty($products)) {
            foreach ($products as $product_item) {
                $product_id = (int)($product_item['id'] ?? 0);
                $quantity = (float)($product_item['quantity'] ?? 0);

                if ($product_id > 0 && $quantity > 0) {
                    $stmt_product_cost->bind_param("i", $product_id);
                    $stmt_product_cost->execute();
                    $product_cost_data = $stmt_product_cost->get_result()->fetch_assoc();

                    if ($product_cost_data) {
                        $correct_cost = (float)$product_cost_data['correct_cost'];
                        $new_total_cost += $quantity * $correct_cost;
                        $calculation_details .= "SP ID#{$product_id} (SL:{$quantity}) * Vốn: " . number_format($correct_cost) . "; ";
                    } else {
                        $calculation_details .= "SP ID#{$product_id} (KHÔNG TÌM THẤY); ";
                    }
                }
            }
        } else {
             $calculation_details = "Lỗi đọc chi tiết đơn hàng (JSON).";
        }

        if (empty($calculation_details)) {
            $calculation_details = "Không có sản phẩm trong đơn hàng.";
        }

        $stmt_update_order->bind_param("di", $new_total_cost, $order_id);
        if ($stmt_update_order->execute()) {
            echo "<tr><td>{$order_code}</td><td><span class='badge bg-success'>Thành công</span></td><td>" . number_format($new_total_cost, 2) . "</td><td>{$calculation_details}</td></tr>";
            $updated_count++;
        } else {
            echo "<tr><td>{$order_code}</td><td><span class='badge bg-danger'>Thất bại</span></td><td>Lỗi CSDL</td><td>{$calculation_details}</td></tr>";
        }
    }
    
    $stmt_product_cost->close();
    $stmt_update_order->close();

    echo "</tbody></table>";
    echo "<div class='alert alert-info text-center mt-4'><strong>Hoàn tất!</strong> Đã xử lý <strong>{$updated_count}</strong> đơn hàng. Vui lòng kiểm tra cột 'Chi tiết tính toán'.</div>";
}

echo "</div></body></html>";
$conn->close();
?>