<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
include '../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

// Solo roles 1, 2, 4
$roleId = isset($_SESSION['user']['roleId']) ? (int)$_SESSION['user']['roleId'] : 0;
$isSuper = isset($_SESSION['user']['isSuper']) && (int)$_SESSION['user']['isSuper'] === 1;
$canSeeContabilidad = $isSuper || in_array($roleId, [1, 2, 4], true);

if (!$canSeeContabilidad) {
    http_response_code(403);
    die('No autorizado');
}

function getTextColor(string $hex): string
{
    $h = ltrim($hex, '#');
    $r = hexdec(substr($h, 0, 2));
    $g = hexdec(substr($h, 2, 2));
    $b = hexdec(substr($h, 4, 2));
    $lum = ($r * 0.299 + $g * 0.587 + $b * 0.114) / 255;
    return $lum > 0.5 ? '#000000' : '#ffffff';
}

function fmt($val)
{
    if ($val == 0) return '-';
    return '$ ' . number_format(abs($val), 0, '', '.');
}

function fmtDateTime(?string $val): string
{
    if (!$val) return '-';
    try {
        $dt = new DateTime($val);
        return $dt->format('d-M-y g:i a');
    } catch (Exception $e) {
        return '-';
    }
}

function cpnParseBreakdownMap($raw, bool $showPercent = false): array
{
    if (is_string($raw)) {
        $decoded = json_decode($raw, true);
    } elseif (is_array($raw)) {
        $decoded = $raw;
    } else {
        $decoded = [];
    }

    if (!is_array($decoded)) return [];

    $out = [];
    foreach ($decoded as $it) {
        if (!is_array($it)) continue;

        $name = trim((string)($it['nombre'] ?? ''));
        if ($name === '') continue;

        $val = (float)($it['valor'] ?? 0);
        if (abs($val) < 0.000001) continue;

        $label = $name;
        if ($showPercent && isset($it['porcentaje']) && $it['porcentaje'] !== null && $it['porcentaje'] !== '') {
            $pct = (float)$it['porcentaje'];
            $pct = abs($pct) <= 1 ? ($pct * 100) : $pct;
            $dec = (abs($pct - round($pct)) < 0.0001) ? 0 : 2;
            $label .= ' ' . number_format($pct, $dec, '.', '') . '%';
        }

        if (!isset($out[$label])) $out[$label] = 0;
        $out[$label] += $val;
    }

    return $out;
}

// Paginación
$page      = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$filter_limit = trim((string)($_GET['filter_limit'] ?? '50'));
if (!in_array($filter_limit, ['20', '50', 'all'], true)) $filter_limit = '50';
$isAllRows = ($filter_limit === 'all');
$limit = $isAllRows ? 1000000 : (int)$filter_limit;
if ($limit <= 0) $limit = 50;
if ($isAllRows) $page = 1;

// Filtros
$filter_empresa  = isset($_GET['filter_empresa']) && $_GET['filter_empresa'] !== '0' && $_GET['filter_empresa'] !== ''
    ? intval($_GET['filter_empresa'])
    : '';
$filter_anio = isset($_GET['filter_anio']) && $_GET['filter_anio'] !== ''
    ? intval($_GET['filter_anio'])
    : '';

$rawFilterMes = $_GET['filter_mes'] ?? [];
$filterMesList = [];
if (is_array($rawFilterMes)) {
    foreach ($rawFilterMes as $m) {
        $mi = intval($m);
        if ($mi >= 1 && $mi <= 12) $filterMesList[] = str_pad((string)$mi, 2, '0', STR_PAD_LEFT);
    }
} else {
    $raw = trim((string)$rawFilterMes);
    if ($raw !== '') {
        foreach (explode(',', $raw) as $m) {
            $mi = intval(trim($m));
            if ($mi >= 1 && $mi <= 12) $filterMesList[] = str_pad((string)$mi, 2, '0', STR_PAD_LEFT);
        }
    }
}
$filterMesList = array_values(array_unique($filterMesList));
sort($filterMesList);
$filter_mes = implode(',', $filterMesList);

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

// Fetch meta
$metaResp = cpn_node_request('GET', $base . '/api/ventas/meta', $token);
$meta = (isset($metaResp['ok']) && $metaResp['ok'] === true) ? ($metaResp['data'] ?? []) : [];

// Fetch list
$query = [
    'limit' => $limit,
    'page' => $page,
    'filter_empresa' => $filter_empresa !== '' ? $filter_empresa : null,
    'filter_anio' => $filter_anio !== '' ? $filter_anio : null,
    'filter_mes' => $filter_mes !== '' ? $filter_mes : null,
];
$query = array_filter($query, function ($v) {
    return $v !== null;
});

$listUrl = $base . '/api/ventas/ordenes?' . http_build_query($query);
$listResp = cpn_node_request('GET', $listUrl, $token);
if (!isset($listResp['ok']) || $listResp['ok'] !== true) {
    $msg = $listResp['error']['message'] ?? 'Error cargando ventas.';
    echo '<script>alert(' . json_encode($msg) . ');</script>';
    $rows = [];
    $totalCount = 0;
} else {
    $rows = $listResp['data']['rows'] ?? [];
    $totalCount = (int)($listResp['data']['totalCount'] ?? 0);
}
if (!is_array($rows)) $rows = [];
$rows = array_values(array_filter($rows, function ($r) {
    return (float)($r['subtotal'] ?? 0) > 0;
}));

$taxColumns = [];
$dedColumns = [];
foreach ($rows as &$r) {
    $taxMap = cpnParseBreakdownMap($r['impuestosDetalle'] ?? null, true);
    $dedMap = cpnParseBreakdownMap($r['deduccionesDetalle'] ?? null, false);

    $r['_taxMap'] = $taxMap;
    $r['_dedMap'] = $dedMap;

    foreach (array_keys($taxMap) as $k) $taxColumns[$k] = true;
    foreach (array_keys($dedMap) as $k) $dedColumns[$k] = true;
}
unset($r);

$taxColumnList = array_keys($taxColumns);
$dedColumnList = array_keys($dedColumns);
sort($taxColumnList, SORT_NATURAL | SORT_FLAG_CASE);
sort($dedColumnList, SORT_NATURAL | SORT_FLAG_CASE);

$sumSubtotal = 0.0;
$sumEnvio = 0.0;
$sumTotal = 0.0;
$sumTaxCols = array_fill_keys($taxColumnList, 0.0);
$sumDedCols = array_fill_keys($dedColumnList, 0.0);
foreach ($rows as $r) {
    $sumSubtotal += (float)($r['subtotal'] ?? 0);
    $sumEnvio += (float)($r['envio'] ?? 0);
    $sumTotal += (float)($r['total'] ?? 0);
    foreach ($taxColumnList as $taxCol) $sumTaxCols[$taxCol] += (float)($r['_taxMap'][$taxCol] ?? 0);
    foreach ($dedColumnList as $dedCol) $sumDedCols[$dedCol] += (float)($r['_dedMap'][$dedCol] ?? 0);
}

$totalPages = max(1, (int)ceil($totalCount / $limit));
?>
<?php include '../templates/header.php'; ?>
<div class="ordenes-container">
    <h1 class="h3 mb-4 text-gray-800">Contabilidad - Ventas</h1>
    <p class="text-muted">Vista de solo lectura para análisis contable</p>

    <form class="form-inline mb-3" method="get">
        <select name="filter_empresa" class="form-control mr-2 mb-2">
            <option value="0">Todas las empresas</option>
            <?php
            $empresas = is_array($meta['empresas'] ?? null) ? $meta['empresas'] : [];
            foreach ($empresas as $emp) {
                $eid = (int)($emp['id'] ?? 0);
                $sigla = (string)($emp['sigla'] ?? '');
                $sel = ($filter_empresa !== '' && (int)$filter_empresa === $eid) ? 'selected' : '';
                echo "<option value=\"{$eid}\" {$sel}>" . htmlspecialchars($sigla) . "</option>";
            }
            ?>
        </select>

        <select name="filter_anio" id="filterAnio" class="form-control mr-2 mb-2" style="width: 130px;">
            <option value="">Todos los anos</option>
            <?php
            $currentYear = (int)date('Y');
            for ($yy = $currentYear + 1; $yy >= 2023; $yy--) {
                $sel = ($filter_anio !== '' && (int)$filter_anio === $yy) ? 'selected' : '';
                echo "<option value=\"{$yy}\" {$sel}>{$yy}</option>";
            }
            ?>
        </select>

        <select name="filter_mes[]" id="filterMes" class="form-control mr-2 mb-2" multiple="multiple" style="width: 300px;">
            <option value="">Todos los meses</option>
        </select>

        <select name="filter_limit" class="form-control mr-2 mb-2" style="width: 130px;">
            <option value="20" <?= $filter_limit === '20' ? 'selected' : '' ?>>20</option>
            <option value="50" <?= $filter_limit === '50' ? 'selected' : '' ?>>50</option>
            <option value="all" <?= $filter_limit === 'all' ? 'selected' : '' ?>>Todo</option>
        </select>

        <button class="btn btn-primary mb-2">Filtrar</button>
        <button type="button" id="btnExportExcel" class="btn btn-success mb-2 ml-2">Exportar a Excel</button>
        <a href="ventas.php" class="btn btn-secondary mb-2 ml-2">Limpiar</a>
    </form>

    <div class="table-responsive mb-3">
        <table class="table table-bordered table-sm" id="tablaVentasContabilidad">
            <thead class="thead-light">
                <tr>
                    <th class="text-center">Orden</th>
                    <th class="text-center">Fecha</th>
                    <th class="text-center">Ref</th>
                    <th class="text-center">NIT</th>
                    <th class="text-center">Cliente</th>
                    <th class="text-center">Empresa</th>
                    <th class="text-center">Estado</th>
                    <th class="text-center">Tipo</th>
                    <th class="text-right">Subtotal</th>
                    <?php foreach ($taxColumnList as $taxCol): ?>
                        <th class="text-right" style="background-color:#0d6efd;color:#fff;"><?= htmlspecialchars($taxCol) ?></th>
                    <?php endforeach; ?>
                    <th class="text-right">Envío</th>
                    <th class="text-right">Total</th>
                    <?php foreach ($dedColumnList as $dedCol): ?>
                        <th class="text-right" style="background-color:#dc3545;color:#fff;"><?= htmlspecialchars($dedCol) ?></th>
                    <?php endforeach; ?>
                    <th class="text-center">Det. Ded.</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r): ?>
                    <tr>
                        <td class="text-center"><strong><?= (int)($r['id'] ?? 0) ?></strong></td>
                        <td class="text-center"><?= fmtDateTime($r['fechaOrden'] ?? null) ?></td>
                        <td class="text-center"><?= htmlspecialchars((string)($r['refExt'] ?? '')) ?></td>
                        <td class="text-center"><?= htmlspecialchars((string)($r['cliNit'] ?? '')) ?></td>
                        <td><?= htmlspecialchars(trim((string)($r['cliNombre'] ?? '') . ' ' . (string)($r['cliApellido'] ?? ''))) ?></td>
                        <td class="text-center">
                            <div style="background-color: <?= htmlspecialchars((string)($r['empColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['empColor'] ?? '#ffffff')) ?>; padding: 2px;">
                                <?= htmlspecialchars((string)($r['empSigla'] ?? '')) ?>
                            </div>
                        </td>
                        <td class="text-center" style="background-color: <?= htmlspecialchars((string)($r['estadoColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['estadoColor'] ?? '#ffffff')) ?>; padding: 2px;">
                            <?= htmlspecialchars((string)($r['estado'] ?? '')) ?>
                        </td>
                        <td class="text-center" style="background-color: <?= htmlspecialchars((string)($r['tipoColor'] ?? '')) ?>; color: <?= getTextColor((string)($r['tipoColor'] ?? '#ffffff')) ?>; padding: 2px;">
                            <?= htmlspecialchars((string)($r['Tipo'] ?? '')) ?>
                        </td>
                        <td class="text-right"><strong><?= fmt($r['subtotal'] ?? 0) ?></strong></td>
                        <?php foreach ($taxColumnList as $taxCol): ?>
                            <td class="text-right"><strong><?= fmt($r['_taxMap'][$taxCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                        <td class="text-right"><strong><?= fmt($r['envio'] ?? 0) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['total'] ?? 0) ?></strong></td>
                        <?php foreach ($dedColumnList as $dedCol): ?>
                            <td class="text-right"><strong><?= fmt($r['_dedMap'][$dedCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                        <td class="text-center">
                            <button
                                type="button"
                                class="btn btn-sm btn-outline-secondary js-ver-deducciones"
                                data-bs-toggle="modal"
                                data-bs-target="#deduccionesModal"
                                data-idventa="<?= (int)($r['id'] ?? 0) ?>"
                                title="Ver deducciones">
                                <i class="fas fa-list"></i>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($isAllRows && count($rows) > 0): ?>
                    <tr style="background-color:#f1f4fb;font-weight:700;">
                        <td class="text-center" colspan="8">TOTAL</td>
                        <td class="text-right"><strong><?= fmt($sumSubtotal) ?></strong></td>
                        <?php foreach ($taxColumnList as $taxCol): ?>
                            <td class="text-right"><strong><?= fmt($sumTaxCols[$taxCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                        <td class="text-right"><strong><?= fmt($sumEnvio) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($sumTotal) ?></strong></td>
                        <?php foreach ($dedColumnList as $dedCol): ?>
                            <td class="text-right"><strong><?= fmt($sumDedCols[$dedCol] ?? 0) ?></strong></td>
                        <?php endforeach; ?>
                        <td></td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Paginación -->
    <?php if (!$isAllRows): ?>
    <nav>
        <ul class="pagination justify-content-center">
            <?php if ($page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">&laquo;</a>
                </li>
            <?php endif;
            $start = max(1, $page - 2);
            $end   = min($totalPages, $page + 2);
            if ($start > 1): ?>
                <li class="page-item"><a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => 1])) ?>">1</a></li>
                <?php if ($start > 2): ?>
                    <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif;
            endif;
            for ($p = $start; $p <= $end; $p++):
                $act = $p == $page ? ' active' : '';
                ?>
                <li class="page-item<?= $act ?>">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"><?= $p ?></a>
                </li>
                <?php endfor;
            if ($end < $totalPages):
                if ($end < $totalPages - 1): ?>
                    <li class="page-item disabled"><span class="page-link">…</span></li>
                <?php endif; ?>
                <li class="page-item">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $totalPages])) ?>"><?= $totalPages ?></a>
                </li>
            <?php endif;
            if ($page < $totalPages): ?>
                <li class="page-item">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">&raquo;</a>
                </li>
            <?php endif; ?>
        </ul>
    </nav>
    <?php endif; ?>

</div>

<!-- Modal: Deducciones -->
<div class="modal fade" id="deduccionesModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Deducciones de Venta <span class="text-muted" id="dedModalVentaId"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-sm table-bordered" id="dedTable">
                        <thead class="thead-light">
                            <tr>
                                <th style="width: 18%">Fecha</th>
                                <th>Concepto</th>
                                <th style="width: 12%" class="text-end">%</th>
                                <th style="width: 18%" class="text-end">Valor</th>
                                <th style="width: 22%">Ref</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot>
                            <tr class="font-weight-bold">
                                <td colspan="3" class="text-end">Total</td>
                                <td class="text-end" id="dedTotal">-</td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mt-3">
                    <h6 class="mb-2">Resumen por concepto</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered" id="dedResumen">
                            <thead class="thead-light">
                                <tr>
                                    <th>Concepto</th>
                                    <th style="width: 22%" class="text-end">Total</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/footer.php'; ?>
<script>
    jQuery(function($) {
        // Generar opciones de meses (01-12)
        const meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        const $select = $('#filterMes');

        for (let month = 1; month <= 12; month++) {
            const mm = String(month).padStart(2, '0');
            const monthName = meses[month - 1];
            $select.append(`<option value="${mm}">${monthName}</option>`);
        }

        // Inicializar Select2 con múltiples selecciones
        $select.select2({
            placeholder: 'Seleccionar meses...',
            allowClear: true,
            width: '100%'
        });

        // Restablecer valores seleccionados si existen
        const values = <?= json_encode(array_values($filterMesList), JSON_UNESCAPED_UNICODE) ?>;
        if (Array.isArray(values) && values.length > 0) {
            $select.val(values).trigger('change');
        }
    });
</script>
<script>
    function cpnExportTableToExcel(tableId, filename) {
        const table = document.getElementById(tableId);
        if (!table) return;

        const clone = table.cloneNode(true);
        clone.querySelectorAll('button').forEach((btn) => btn.remove());

        // Quitar columna de acciones (Det. Ded.) del archivo exportado.
        const headers = clone.querySelectorAll('thead tr th');
        let actionCol = -1;
        headers.forEach((th, idx) => {
            const txt = (th.textContent || '').trim().toLowerCase();
            if (txt === 'det. ded.') actionCol = idx;
        });
        if (actionCol >= 0) {
            clone.querySelectorAll('tr').forEach((tr) => {
                const cells = tr.children;
                if (cells && cells[actionCol]) cells[actionCol].remove();
            });
        }

        const html = `
        <html xmlns:o="urn:schemas-microsoft-com:office:office"
              xmlns:x="urn:schemas-microsoft-com:office:excel"
              xmlns="http://www.w3.org/TR/REC-html40">
        <head>
          <meta charset="UTF-8">
        </head>
        <body>${clone.outerHTML}</body>
        </html>`;

        const blob = new Blob([html], { type: 'application/vnd.ms-excel;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }

    document.getElementById('btnExportExcel')?.addEventListener('click', function() {
        const now = new Date();
        const pad = (n) => String(n).padStart(2, '0');
        const stamp = `${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}`;
        cpnExportTableToExcel('tablaVentasContabilidad', `contabilidad_ventas_${stamp}.xls`);
    });

    function cpnFmtMoney(val) {
        const n = Number(val || 0);
        if (!n) return '-';
        const abs = Math.abs(n);
        return '$ ' + abs.toLocaleString('es-CO', {
            maximumFractionDigits: 0
        });
    }

    function cpnFmtDateTime(val) {
        if (!val) return '-';
        const s = String(val);
        const m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?:[ T]([0-9]{2}):([0-9]{2})(?::([0-9]{2}))?)?/.exec(s);
        if (!m) return s;
        const y = Number(m[1]);
        const mo = Number(m[2]);
        const d = Number(m[3]);
        const hh = Number(m[4] || 0);
        const mm = Number(m[5] || 0);

        const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        const monTxt = months[(mo - 1) >= 0 ? (mo - 1) : 0] || 'Jan';

        const hour12 = (hh % 12) || 12;
        const ampm = hh >= 12 ? 'pm' : 'am';
        const minTxt = String(mm).padStart(2, '0');
        return `${String(d).padStart(2, '0')}-${monTxt}-${String(y).slice(-2)} ${hour12}:${minTxt} ${ampm}`;
    }

    $('#deduccionesModal').on('show.bs.modal', function(event) {
        const btn = $(event.relatedTarget);
        const idVenta = Number(btn.data('idventa') || 0);
        $('#dedModalVentaId').text(idVenta ? `#${idVenta}` : '');

        const $tbody = $('#dedTable tbody');
        const $tfootTotal = $('#dedTotal');
        const $resBody = $('#dedResumen tbody');
        $tbody.empty();
        $resBody.empty();
        $tfootTotal.text('-');

        if (!idVenta) return;

        $.getJSON('../ventas/ventas_deducciones_api.php', {
                action: 'list',
                idVenta
            })
            .done(function(rows) {
                if (!Array.isArray(rows)) rows = [];

                let total = 0;
                const byConcept = new Map();

                for (const r of rows) {
                    const concepto = (r && r.nombre) ? String(r.nombre) : '';
                    const pct = Number(r && r.porcentajeDeduccion != null ? r.porcentajeDeduccion : 0);
                    const valor = Number(r && r.valorDeduccion != null ? r.valorDeduccion : 0);
                    const ref = (r && r.refPago) ? String(r.refPago) : '';
                    const fecha = r && r.fecha ? cpnFmtDateTime(r.fecha) : '-';

                    total += valor;
                    if (concepto) {
                        byConcept.set(concepto, (byConcept.get(concepto) || 0) + valor);
                    }

                    $tbody.append(
                        `<tr>
                            <td>${fecha}</td>
                            <td>${$('<div>').text(concepto).html()}</td>
                            <td class="text-end">${pct ? pct : '-'}</td>
                            <td class="text-end"><strong>${cpnFmtMoney(valor)}</strong></td>
                            <td>${$('<div>').text(ref).html()}</td>
                        </tr>`
                    );
                }

                $tfootTotal.text(cpnFmtMoney(total));

                const sorted = Array.from(byConcept.entries()).sort((a, b) => (b[1] || 0) - (a[1] || 0));
                for (const [concepto, val] of sorted) {
                    $resBody.append(
                        `<tr>
                            <td>${$('<div>').text(concepto).html()}</td>
                            <td class="text-end"><strong>${cpnFmtMoney(val)}</strong></td>
                        </tr>`
                    );
                }

                if (rows.length === 0) {
                    $tbody.append('<tr><td colspan="5" class="text-center text-muted">Sin deducciones</td></tr>');
                }
                if (sorted.length === 0) {
                    $resBody.append('<tr><td colspan="2" class="text-center text-muted">Sin deducciones</td></tr>');
                }
            })
            .fail(function() {
                $tbody.append('<tr><td colspan="5" class="text-center text-danger">Error cargando deducciones</td></tr>');
                $resBody.append('<tr><td colspan="2" class="text-center text-danger">Error</td></tr>');
            });
    });
</script>
