<?php
// recover_order.php - Công cụ khôi phục đơn hàng bị mất chi tiết
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Nạp các thiết lập và kết nối CSDL
require_once __DIR__ . '/core/init.php';

// Xử lý tìm kiếm sản phẩm cho autocomplete
if (isset($_GET['action']) && $_GET['action'] == 'search_products') {
    header('Content-Type: application/json; charset=utf-8');
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $stmt = $conn->prepare("SELECT ID, prd_code, prd_name, prd_sell_price FROM cms_products WHERE (prd_name LIKE ? OR prd_code LIKE ?) AND deleted = 0 LIMIT 10");
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = [
            'id' => $row['ID'],
            'label' => $row['prd_code'] . ' - ' . $row['prd_name'],
            'value' => $row['prd_name'],
            'code' => $row['prd_code'],
            'price' => $row['prd_sell_price']
        ];
    }
    $stmt->close();
    echo json_encode($products);
    exit;
}

// Xử lý khi người dùng gửi form tái tạo đơn hàng
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reconstruct') {
    $order_id = intval($_POST['order_id']);
    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $prices = $_POST['price'] ?? [];

    if ($order_id > 0 && !empty($product_ids)) {
        $conn->begin_transaction();
        try {
            $items_to_save = [];
            $total_quantity_new = 0;
            $total_price_new = 0;

            for ($i = 0; $i < count($product_ids); $i++) {
                $p_id = intval($product_ids[$i]);
                $p_qty = floatval($quantities[$i]);
                $p_price = floatval($prices[$i]);

                if ($p_id > 0 && $p_qty > 0) {
                    $stmt_prod = $conn->prepare("SELECT prd_code, prd_name, prd_average_cost FROM cms_products WHERE ID = ?");
                    $stmt_prod->bind_param("i", $p_id);
                    $stmt_prod->execute();
                    $prod_data = $stmt_prod->get_result()->fetch_assoc();
                    $stmt_prod->close();

                    $items_to_save[] = [
                        'id' => $p_id,
                        'code' => $prod_data['prd_code'] ?? 'N/A',
                        'quantity' => $p_qty,
                        'price' => $p_price,
                        'origin_price' => floatval($prod_data['prd_average_cost'] ?? 0),
                        'name' => $prod_data['prd_name'] ?? 'Sản phẩm không rõ'
                    ];

                    $total_quantity_new += $p_qty;
                    $total_price_new += ($p_qty * $p_price);
                }
            }
            
            $detail_order_json = json_encode($items_to_save, JSON_UNESCAPED_UNICODE);

            $stmt_old_order = $conn->prepare("SELECT discount_item, vat, customer_pay FROM cms_orders WHERE ID = ?");
            $stmt_old_order->bind_param("i", $order_id);
            $stmt_old_order->execute();
            $old_order = $stmt_old_order->get_result()->fetch_assoc();
            $stmt_old_order->close();

            $discount_item = floatval($old_order['discount_item'] ?? 0);
            $vat_percent = floatval($old_order['vat'] ?? 0);
            $customer_pay = floatval($old_order['customer_pay'] ?? 0);

            $total_money_new = ($total_price_new - $discount_item) * (1 + $vat_percent / 100);
            $lack_new = $total_money_new - $customer_pay;

            $stmt_update = $conn->prepare(
                "UPDATE cms_orders SET 
                    detail_order = ?, 
                    total_quantity = ?, 
                    total_price = ?, 
                    total_money = ?, 
                    lack = ?
                WHERE ID = ?"
            );
            $stmt_update->bind_param("sddddi", $detail_order_json, $total_quantity_new, $total_price_new, $total_money_new, $lack_new, $order_id);
            
            if (!$stmt_update->execute()) {
                throw new Exception("Lỗi khi cập nhật đơn hàng: " . $stmt_update->error);
            }
            $stmt_update->close();
            
            $conn->commit();
            $message = "<div class='message success'>Đã khôi phục thành công đơn hàng! Bạn có thể đóng trang này và kiểm tra lại.</div>";

        } catch (Exception $e) {
            $conn->rollback();
            $message = "<div class='message error'>Đã xảy ra lỗi: " . $e->getMessage() . "</div>";
        }
    } else {
        $message = "<div class='message error'>Dữ liệu không hợp lệ. Cần có ID đơn hàng và ít nhất một sản phẩm.</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Công Cụ Khôi Phục Đơn Hàng</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; }
        .container { max-width: 800px; margin: auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h1, h2 { text-align: center; color: #333; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"], input[type="number"] { width: 100%; padding: 8px; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; }
        .btn { display: inline-block; background-color: #28a745; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; }
        .btn-primary { background-color: #007bff; }
        .btn-danger { background-color: #dc3545; }
        .message { padding: 15px; margin-bottom: 20px; border-radius: 4px; text-align: center; font-weight: bold; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; padding: 10px; margin-top: 10px; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .text-right { text-align: right; }
        .ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden; }
    </style>
</head>
<body>
<div class="container">
    <h1>Công Cụ Khôi Phục Đơn Hàng</h1>
    <?php echo $message; ?>

    <?php if (isset($_GET['code']) && !empty($_GET['code']) && $_SERVER['REQUEST_METHOD'] !== 'POST'): ?>
        <?php
        $order_code = trim($_GET['code']);
        $stmt = $conn->prepare("SELECT o.*, c.customer_name FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID WHERE o.output_code = ?");
        $stmt->bind_param("s", $order_code);
        $stmt->execute();
        $order = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        ?>

        <?php if ($order): ?>
            <h2>Tái Tạo Đơn Hàng: <?php echo htmlspecialchars($order['output_code']); ?></h2>
            <div class="info">
                <strong>Khách hàng:</strong> <?php echo htmlspecialchars($order['customer_name'] ?? 'Khách lẻ'); ?><br>
                <strong>Ngày tạo:</strong> <?php echo date('d/m/Y H:i:s', strtotime($order['created'])); ?><br>
                <strong>Tổng tiền (đã lỗi):</strong> <?php echo number_format($order['total_money']); ?> đ
            </div>

            <form action="recover_order.php" method="POST">
                <input type="hidden" name="action" value="reconstruct">
                <input type="hidden" name="order_id" value="<?php echo $order['ID']; ?>">
                
                <h3>Chi Tiết Sản Phẩm Mới</h3>
                <table id="product-table">
                    <thead>
                        <tr>
                            <th>Sản Phẩm (gõ mã hoặc tên)</th>
                            <th width="15%">Số Lượng</th>
                            <th width="20%">Đơn Giá</th>
                            <th width="5%"></th>
                        </tr>
                    </thead>
                    <tbody id="product-list">
                        </tbody>
                </table>
                <button type="button" id="add-product" class="btn" style="margin-top: 10px;">+ Thêm Sản Phẩm</button>
                
                <div class="form-group" style="margin-top: 20px; text-align: right;">
                    <button type="submit" class="btn btn-primary">Tái Tạo Đơn Hàng</button>
                </div>
            </form>

        <?php else: ?>
            <div class="message error">Không tìm thấy đơn hàng với mã: <?php echo htmlspecialchars($order_code); ?></div>
        <?php endif; ?>

    <?php else: ?>
        <form action="recover_order.php" method="GET">
            <div class="form-group">
                <label for="code">Nhập Mã Đơn Hàng Cần Khôi Phục:</label>
                <input type="text" id="code" name="code" placeholder="Ví dụ: HD022585" required>
            </div>
            <button type="submit" class="btn btn-primary">Tìm & Khôi Phục</button>
        </form>
    <?php endif; ?>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
    let rowIdx = 0;

    function addProductRow() {
        let html = `
            <tr id="row-${rowIdx}">
                <td>
                    <input type="hidden" name="product_id[]" class="product-id">
                    <input type="text" name="product_name[]" class="product-search" placeholder="Gõ để tìm sản phẩm..." required>
                </td>
                <td><input type="number" name="quantity[]" class="quantity" value="1" min="0" step="any" required></td>
                <td><input type="number" name="price[]" class="price" value="0" min="0" step="any" required></td>
                <td><button type="button" class="btn btn-danger remove-row">-</button></td>
            </tr>
        `;
        $('#product-list').append(html);
        
        // Kích hoạt autocomplete cho dòng mới
        initAutocomplete(rowIdx);
        rowIdx++;
    }

    function initAutocomplete(idx) {
        $(`#row-${idx} .product-search`).autocomplete({
            source: 'recover_order.php?action=search_products',
            minLength: 2,
            select: function(event, ui) {
                let row = $(this).closest('tr');
                row.find('.product-id').val(ui.item.id);
                row.find('.price').val(ui.item.price);
            }
        });
    }

    $('#add-product').on('click', function() {
        addProductRow();
    });

    $('#product-table').on('click', '.remove-row', function() {
        $(this).closest('tr').remove();
    });

    // Thêm một dòng đầu tiên khi tải trang
    addProductRow();
});
</script>
</body>
</html>