<?php
require_once __DIR__ . '/../../core/init.php';

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die('Không có khách hàng nào được chọn.');
}
$customer_id = intval($_GET['id']);

$stmt = $conn->prepare("SELECT c.*, g.group_name FROM cms_customers c LEFT JOIN cms_customers_group g ON c.customer_group = g.ID WHERE c.ID = ?");
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$customer = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$customer) {
    die('Không tìm thấy khách hàng.');
}

$customer_groups = [
    ['ID' => '0', 'group_name' => 'Khách sỉ'],
    ['ID' => '1', 'group_name' => 'Khách lẻ']
];

$order_history_result = $conn->query("SELECT o.*, u.display_name as cashier_name FROM cms_orders o LEFT JOIN cms_users u ON o.user_init = u.id WHERE o.customer_id = {$customer_id} AND o.deleted = 0 ORDER BY sell_date ASC");
$order_history = $order_history_result ? $order_history_result->fetch_all(MYSQLI_ASSOC) : [];

$debt_orders = array_filter($order_history, function ($order) {
    return isset($order['lack']) && $order['lack'] > 0;
});
$total_invoices = count($order_history);
$total_spent = array_sum(array_column($order_history, 'total_money'));
$total_debt = array_sum(array_column($order_history, 'lack'));

$total_debt_invoices = count($debt_orders);
$total_debt_value = array_sum(array_column($debt_orders, 'total_money'));

require_once __DIR__ . '/../../templates/header.php';
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<style>
    .customer-info-card .info-item {
        margin-bottom: 1rem;
    }

    .customer-info-card .info-label {
        font-weight: 600;
        color: #858796;
        display: block;
    }

    .customer-info-card .info-value {
        font-size: 1.1rem;
        color: #3a3b45;
    }

    #purchaseHistoryTable thead th,
    #debtCollectionTable thead th {
        background-color: #4e73df !important;
        color: #ffffff !important;
        font-weight: bold;
        vertical-align: middle;
    }

    #purchaseHistoryTable tbody tr:nth-child(even),
    #debtCollectionTable tbody tr:nth-child(even) {
        background-color: #f8f9fc;
    }

    #purchaseHistoryTable tbody tr:hover,
    #debtCollectionTable tbody tr:hover {
        background-color: #eaecf4;
    }

    .details-control {
        cursor: pointer;
        width: 25px;
    }

    .child-row-container {
        padding: 1rem;
        background-color: #f8f9fc;
        border-left: 3px solid #4e73df;
        margin: 5px 0;
    }

    .child-summary {
        margin-bottom: 1rem;
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .child-summary span {
        padding: 6px 12px;
        border-radius: 16px;
        color: white;
        font-size: .9em;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
        white-space: nowrap;
    }

    .child-summary strong {
        color: white;
        margin-left: 4px;
    }

    .child-summary span:nth-child(1) {
        background-color: #4e73df;
    }

    .child-summary span:nth-child(2) {
        background-color: #1cc88a;
    }

    .child-summary span:nth-child(3) {
        background-color: #f6c23e;
    }

    .child-summary span:nth-child(4) {
        background-color: #36b9cc;
    }

    .child-summary span:nth-child(5) {
        background-color: #e74a3b;
    }

    #purchaseHistoryTable .table-sm>thead {
        background-color: #4e73df;
        color: white;
        border-color: #4e73df;
    }

    #purchaseHistoryTable .table-sm>thead th {
        font-weight: 600;
    }

    #purchaseHistoryTable .table-sm>tbody>tr:hover {
        background-color: #eaecf4;
    }

    #purchaseHistoryTable .table-sm>tbody td:last-child {
        font-weight: 700;
        color: #2e59d9;
    }

    #debtCollectionForm .form-check-label {
        cursor: pointer;
    }

    .debt-collection-header {
        padding: 1rem;
    }

    .debt-collection-header .form-control {
        border-radius: 0.375rem;
        height: 38px;
    }

    .debt-collection-header .btn-success {
        background-color: #1cc88a;
        border-color: #1cc88a;
    }

    .debt-collection-header .btn-success:hover {
        background-color: #17a673;
        border-color: #17a673;
    }

    .debt-collection-header .btn-secondary {
        background-color: #858796;
        border-color: #858796;
    }

    .debt-collection-header .btn-secondary:hover {
        background-color: #717384;
        border-color: #717384;
    }
</style>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Chi tiết Khách hàng: <?php echo htmlspecialchars($customer['customer_name']); ?></h1>
        <div>
            <button type="button" class="btn btn-sm btn-warning shadow-sm" id="btnEditCustomer"><i class="fas fa-edit fa-sm text-white-50"></i> Sửa thông tin</button>
            <a href="list.php" class="btn btn-sm btn-secondary shadow-sm"><i class="fas fa-arrow-left fa-sm text-white-50"></i> Quay lại danh sách</a>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Thông tin cá nhân</h6>
                </div>
                <div class="card-body customer-info-card">
                    <div class="row">
                        <div class="col-md-4 info-item"><span class="info-label">Mã khách hàng:</span><span class="info-value"><?php echo htmlspecialchars($customer['customer_code']); ?></span></div>
                        <div class="col-md-4 info-item"><span class="info-label">Nhóm:</span><span class="info-value"><?php echo htmlspecialchars($customer['group_name'] ?? 'Chưa có'); ?></span></div>
                        <div class="col-md-4 info-item"><span class="info-label">Số điện thoại:</span><span class="info-value"><?php echo htmlspecialchars($customer['customer_phone'] ?? 'Chưa có'); ?></span></div>
                        <div class="col-md-8 info-item"><span class="info-label">Địa chỉ:</span><span class="info-value"><?php echo htmlspecialchars($customer['customer_addr'] ?? 'Chưa có'); ?></span></div>
                        <div class="col-md-4 info-item"><span class="info-label">Mã số thuế:</span><span class="info-value"><?php echo htmlspecialchars($customer['notes'] ?? 'Chưa có'); ?></span></div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($total_debt > 0) : ?>
            <div class="col-lg-12">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Thu nợ</h6>
                    </div>
                    <div class="card-body p-0">
                        <form id="debtCollectionForm">
                            <div class="debt-collection-header">
                                <div class="row g-3 align-items-center">
                                    <div class="col-auto"><strong>Hình thức:</strong></div>
                                    <div class="col-auto d-flex">
                                        <div class="form-check form-check-inline me-3"><input class="form-check-input" type="radio" name="payment_method" id="pay_cash" value="1" checked><label class="form-check-label" for="pay_cash">Tiền mặt</label></div>
                                        <div class="form-check form-check-inline me-3"><input class="form-check-input" type="radio" name="payment_method" id="pay_card" value="2"><label class="form-check-label" for="pay_card">Thẻ</label></div>
                                        <div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="payment_method" id="pay_transfer" value="3"><label class="form-check-label" for="pay_transfer">CK</label></div>
                                    </div>
                                    <div class="col-md-3 col-lg-2"><input type="text" id="debt_notes" class="form-control" placeholder="Ghi chú..."></div>
                                    <div class="col-md-2 col-lg-2"><input type="date" id="receipt_date" class="form-control" value="<?php echo date('Y-m-d'); ?>"></div>
                                    <div class="col-md-3 col-lg-2"><input type="text" id="total_amount_to_collect" class="form-control" placeholder="Nhập số tiền thu" data-total-debt="<?php echo $total_debt; ?>"></div>
                                    <div class="col-auto ms-auto">
                                        <button type="button" id="btn-collect-total" class="btn btn-success"><i class="fas fa-hand-holding-usd me-1"></i> Thu nợ</button>
                                        <button type="reset" class="btn btn-secondary"><i class="fas fa-times me-1"></i> Hủy</button>
                                    </div>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-bordered table-hover" id="debtCollectionTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Mã đơn hàng</th>
                                            <th>Kho xuất</th>
                                            <th>Ngày bán</th>
                                            <th>Thu ngân</th>
                                            <th class="text-center">Trạng thái</th>
                                            <th class="text-end">Tổng tiền</th>
                                            <th class="text-end">Đã trả</th>
                                            <th class="text-end">Nợ</th>
                                            <th style="width:150px;">Thu nợ</th>
                                            <th style="width:80px;" class="text-center">Thu</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($debt_orders as $order) : ?>
                                            <tr class="debt-row" data-order-id="<?php echo $order['ID']; ?>" data-debt-amount="<?php echo $order['lack']; ?>">
                                                <td><?php echo htmlspecialchars($order['output_code']); ?></td>
                                                <td>Chí Bằng Vị Thanh I</td>
                                                <td><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></td>
                                                <td><?php echo htmlspecialchars($order['cashier_name'] ?? 'N/A'); ?></td>
                                                <td class="text-center"><span class="badge bg-success">Hoàn thành</span></td>
                                                <td class="text-end"><?php echo number_format($order['total_money']); ?></td>
                                                <td class="text-end"><?php echo number_format($order['customer_pay']); ?></td>
                                                <td class="text-end fw-bold text-danger"><?php echo number_format($order['lack']); ?></td>
                                                <td><input type="text" class="form-control form-control-sm amount-to-collect" placeholder="Số tiền thu" data-max-debt="<?php echo $order['lack']; ?>"></td>
                                                <td class="text-center"><button type="button" class="btn btn-sm btn-primary btn-collect-single">Thu</button></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot class="table-light fw-bold">
                                        <tr>
                                            <td colspan="5" class="text-end">Tổng cộng:</td>
                                            <td class="text-end"><?php echo number_format($total_debt_value); ?></td>
                                            <td class="text-end"></td>
                                            <td class="text-end text-danger"><?php echo number_format($total_debt); ?></td>
                                            <td colspan="2"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Lịch sử mua hàng</h6>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="purchaseHistoryTable" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>Mã đơn hàng</th>
                                    <th>Ngày bán</th>
                                    <th>Thu ngân</th>
                                    <th class="text-center">Trạng thái</th>
                                    <th class="text-end">Tổng tiền</th>
                                    <th class="text-end">Đã trả</th>
                                    <th class="text-end">Nợ</th>
                                    <th class="text-center">Hành động</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($order_history)) : foreach ($order_history as $order) : ?>
                                        <tr data-order-id="<?php echo $order['ID']; ?>">
                                            <td class="details-control text-center"><i class="fas fa-plus-circle text-primary"></i></td>
                                            <td><a href="/quanlybanhang/modules/pos/pos.php?edit_order_id=<?php echo $order['ID']; ?>" class="fw-bold"><?php echo htmlspecialchars($order['output_code']); ?></a></td>
                                            <td><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></td>
                                            <td><?php echo htmlspecialchars($order['cashier_name'] ?? 'N/A'); ?></td>
                                            <td class="text-center"><span class="badge bg-success">Hoàn thành</span></td>
                                            <td class="text-end"><?php echo number_format($order['total_money']); ?></td>
                                            <td class="text-end"><?php echo number_format($order['customer_pay']); ?></td>
                                            <td class="text-end fw-bold text-danger"><?php echo number_format($order['lack']); ?></td>
                                            <td class="text-center"><a href="/quanlybanhang/modules/pos/print_invoice.php?order_id=<?php echo $order['ID']; ?>" class="btn btn-sm btn-info" target="_blank" title="In phiếu"><i class="fas fa-print"></i></a></td>
                                        </tr>
                                    <?php endforeach;
                                else : ?><tr>
                                        <td colspan="9" class="text-center p-4">Chưa có lịch sử mua hàng.</td>
                                    </tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-end fw-bold"><span>Tổng số HĐ: <span class="text-primary"><?php echo $total_invoices; ?></span></span><span class="ms-4">Tổng mua: <span class="text-primary"><?php echo number_format($total_spent); ?></span></span><span class="ms-4">Tổng nợ: <span class="text-danger"><?php echo number_format($total_debt); ?></span></span></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="customerModal" tabindex="-1" aria-labelledby="customerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="customerForm">
                <input type="hidden" name="customer_id" id="customer_id">
                <div class="modal-header">
                    <h5 class="modal-title" id="customerModalLabel">Tạo mới khách hàng</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nhóm KH</label>
                            <select name="customer_group" id="customer_group" class="form-select" style="width: 100%;">
                                <?php foreach ($customer_groups as $group) {
                                    echo "<option value='{$group['ID']}'>" . htmlspecialchars($group['group_name']) . "</option>";
                                } ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3"><label class="form-label">Mã khách hàng</label><input type="text" name="customer_code" id="customer_code" class="form-control" placeholder="Tự sinh nếu bỏ trống"></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Tên khách hàng <span class="text-danger">*</span></label><input type="text" name="customer_name" id="customer_name" class="form-control" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label">Số điện thoại</label><input type="text" name="customer_phone" id="customer_phone" class="form-control"></div>
                        <div class="col-md-12 mb-3"><label class="form-label">Địa chỉ</label><input type="text" name="customer_addr" id="customer_addr" class="form-control"></div>
                        <div class="col-md-12 mb-3"><label class="form-label">Mã số thuế</label><input type="text" name="notes" id="notes" class="form-control"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Bỏ qua</button>
                    <button type="submit" class="btn btn-primary">Lưu</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
    $(document).ready(function() {
        const parseNumber = str => parseFloat(String(str).replace(/\./g, '').replace(',', '.')) || 0;
        const formatNumber = num => (parseNumber(num) || 0).toLocaleString('vi-VN');

        $('#customer_group').select2({
            theme: "bootstrap-5",
            dropdownParent: $('#customerModal'),
            minimumResultsForSearch: Infinity
        });

        $('#btnEditCustomer').on('click', function(e) {
            e.preventDefault();
            var customerId = <?php echo $customer_id; ?>;
            $.get('/quanlybanhang/ajax/customers_ajax.php', {
                action: 'get_customer_details',
                id: customerId
            }, function(response) {
                if (response.status === 'success') {
                    var c = response.data;
                    $('#customer_id').val(c.ID);
                    $('#customerModalLabel').text('Chỉnh sửa khách hàng: ' + c.customer_name);
                    $('#customerForm [name="customer_group"]').val(c.customer_group).trigger('change');
                    $('#customerForm [name="customer_code"]').val(c.customer_code);
                    $('#customerForm [name="customer_name"]').val(c.customer_name);
                    $('#customerForm [name="customer_phone"]').val(c.customer_phone);
                    $('#customerForm [name="customer_addr"]').val(c.customer_addr);
                    $('#customerForm [name="notes"]').val(c.notes);
                    var customerModal = new bootstrap.Modal(document.getElementById('customerModal'));
                    customerModal.show();
                } else {
                    alert(response.message);
                }
            }, 'json');
        });

        $('#customerForm').on('submit', function(e) {
            e.preventDefault();
            var formData = $(this).serialize() + '&action=save_customer';
            $.post('/quanlybanhang/ajax/customers_ajax.php', formData, function(response) {
                alert(response.message);
                if (response.status === 'success') {
                    location.reload();
                }
            }, 'json');
        });

        $('#total_amount_to_collect, .amount-to-collect').on('input', function(e) {
            let originalVal = $(this).val();
            let caretPos = this.selectionStart;
            let numVal = originalVal.replace(/[^\d]/g, '');
            $(this).val(numVal.replace(/\B(?=(\d{3})+(?!\d))/g, "."));
            let newVal = $(this).val();
            caretPos = caretPos + (newVal.length - originalVal.length);
            this.setSelectionRange(caretPos, caretPos);
        });

        function formatDetails(response) {
            const order = response.order;
            const items = response.items;
            if (!order || !items) return '<div class="p-3 text-center text-muted">Không có dữ liệu.</div>';

            const totalDiscount = (parseNumber(order.total_discount)) + (parseNumber(order.discount_item));

            let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatNumber(order.total_quantity)}</strong></span><span>Tiền hàng: <strong>${formatNumber(order.total_price)}</strong></span><span>Giảm giá: <strong>${formatNumber(totalDiscount)}</strong></span><span>Tổng tiền: <strong>${formatNumber(order.total_money)}</strong></span><span>Còn nợ: <strong>${formatNumber(order.lack)}</strong></span></div>`;
            let productsHtml = `<table class="table table-sm table-hover"><thead><tr><th>STT</th><th>Mã SP</th><th>Tên sản phẩm</th><th>SL</th><th>Đơn giá</th><th>Thành tiền</th></tr></thead><tbody>`;
            if (items.length > 0) {
                items.forEach((item, index) => {
                    let lineTotal = (parseNumber(item.quantity)) * (parseNumber(item.price));
                    productsHtml += `<tr><td>${index + 1}</td><td>${item.code || 'N/A'}</td><td>${item.name || 'N/A'}</td><td class="text-right">${formatNumber(item.quantity)}</td><td class="text-right">${formatNumber(item.price)}</td><td class="text-right">${formatNumber(lineTotal)}</td></tr>`;
                });
            } else {
                productsHtml += `<tr><td colspan="6" class="text-center">Đơn hàng không có sản phẩm.</td></tr>`;
            }
            productsHtml += '</tbody></table></div>';
            return summaryHtml + productsHtml;
        }

        $('#purchaseHistoryTable tbody').on('click', 'td.details-control', function() {
            var tr = $(this).closest('tr');
            var icon = $(this).find('i');
            var orderId = tr.data('order-id');
            var colCount = tr.prop('cells').length;
            var is_open = tr.next().hasClass('child-row');

            $('#purchaseHistoryTable tbody tr.child-row').remove();
            $('#purchaseHistoryTable tbody td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');

            if (is_open) {
                return;
            }
            if (!orderId) return;

            icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
            var loadingRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center">Đang tải...</div></td></tr>');
            tr.after(loadingRow);

            $.ajax({
                url: '/quanlybanhang/ajax/orders_ajax.php',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'get_order_details',
                    order_id: orderId
                },
                success: function(response) {
                    loadingRow.remove();
                    if (response.status === 'success') {
                        var detailHtml = formatDetails(response);
                        var detailRow = $('<tr class="child-row"><td colspan="' + colCount + '">' + detailHtml + '</td></tr>');
                        tr.after(detailRow);
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                    } else {
                        var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi: ' + response.message + '</div></td></tr>');
                        tr.after(errorRow);
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                    }
                },
                error: function() {
                    loadingRow.remove();
                    var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi kết nối.</div></td></tr>');
                    tr.after(errorRow);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            });
        });

        function collectDebt(orderId, amount, $button) {
            let payment_method = $('input[name="payment_method"]:checked').val();
            let notes = $('#debt_notes').val();
            let receipt_date = $('#receipt_date').val();

            if ($button) {
                $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
            }

            return $.ajax({
                url: '/quanlybanhang/ajax/customers_ajax.php',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'collect_debt',
                    order_id: orderId,
                    amount: parseNumber(amount),
                    payment_method: payment_method,
                    notes: notes,
                    receipt_date: receipt_date
                }
            }).fail(function() {
                alert('Lỗi khi gửi yêu cầu thu nợ cho đơn hàng ' + orderId);
            }).always(function() {
                if ($button) {
                    $button.prop('disabled', false).text('Thu');
                }
            });
        }

        $('#debtCollectionTable').on('click', '.btn-collect-single', function() {
            var $button = $(this);
            var $row = $button.closest('tr');
            var orderId = $row.data('order-id');
            var amount = $row.find('.amount-to-collect').val();

            if (parseNumber(amount) <= 0) {
                alert('Vui lòng nhập số tiền hợp lệ.');
                return;
            }

            if (confirm(`Bạn có chắc muốn thu nợ ${amount} VNĐ cho đơn hàng này?`)) {
                collectDebt(orderId, amount, $button).done(function(response) {
                    alert(response.message);
                    if (response.status === 'success') {
                        location.reload();
                    }
                });
            }
        });

        $('#btn-collect-total').on('click', function() {
            const $collectBtn = $(this);
            let totalAmountToCollect = parseNumber($('#total_amount_to_collect').val());
            const totalDebt = parseNumber($('#total_amount_to_collect').data('total-debt'));

            if (totalAmountToCollect <= 0) {
                alert('Vui lòng nhập số tiền cần thu.');
                return;
            }

            if (totalAmountToCollect > totalDebt) {
                alert('Số tiền thu không được lớn hơn tổng nợ.');
                return;
            }

            if (!confirm(`Bạn có chắc chắn muốn thu tổng cộng ${formatNumber(totalAmountToCollect)} VNĐ công nợ không?`)) {
                return;
            }

            $collectBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Đang xử lý...');

            let remainingAmount = totalAmountToCollect;
            const promises = [];

            const debtRows = $('#debtCollectionTable tbody tr.debt-row').get();
            debtRows.sort((a, b) => {
                const dateA = new Date($(a).find('td:eq(2)').text().split('/').reverse().join('-'));
                const dateB = new Date($(b).find('td:eq(2)').text().split('/').reverse().join('-'));
                return dateA - dateB;
            });


            $(debtRows).each(function() {
                if (remainingAmount <= 0) return false;

                const $row = $(this);
                const orderId = $row.data('order-id');
                const debtAmount = parseNumber($row.data('debt-amount'));
                const $button = $row.find('.btn-collect-single');

                const amountToPay = Math.min(remainingAmount, debtAmount);

                if (amountToPay > 0) {
                    promises.push(collectDebt(orderId, amountToPay, $button));
                    remainingAmount -= amountToPay;
                }
            });

            if (promises.length > 0) {
                Promise.allSettled(promises).then(function(results) {
                    const allSuccess = results.every(res => res.status === 'fulfilled' && res.value.status === 'success');
                    if (allSuccess) {
                        alert('Thu nợ thành công!');
                    } else {
                        alert('Đã xảy ra lỗi trong quá trình thu nợ. Vui lòng kiểm tra lại.');
                    }
                    location.reload();
                });
            } else {
                alert('Số tiền thu không hợp lệ hoặc không có công nợ để thu.');
                $collectBtn.prop('disabled', false).html('<i class="fas fa-hand-holding-usd me-1"></i> Thu nợ');
            }
        });
    });
</script>