<?php
// checklistml.php
session_start();
include '../../includes/session_control.php';
require_once '../../cotizaciones/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

function json_out($payload)
{
    header('Content-Type: application/json');

    $flags = 0;
    if (defined('JSON_UNESCAPED_UNICODE')) $flags |= JSON_UNESCAPED_UNICODE;
    if (defined('JSON_UNESCAPED_SLASHES')) $flags |= JSON_UNESCAPED_SLASHES;
    if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) $flags |= JSON_INVALID_UTF8_SUBSTITUTE;

    $json = json_encode($payload, $flags);
    if ($json === false) {
        echo '{"ok":false,"error":"Respuesta JSON inválida"}';
        exit;
    }

    echo $json;
    exit;
}

// AJAX: listar logs de checklist MercadoLibre
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'list') {
    $page = isset($_POST['page']) ? max(1, intval($_POST['page'])) : 1;
    $limit = isset($_POST['limit']) ? max(1, min(500, intval($_POST['limit']))) : 100;

    $q = isset($_POST['q']) ? trim((string)$_POST['q']) : '';
    $instancia = isset($_POST['instancia']) ? trim((string)$_POST['instancia']) : '';
    $days = isset($_POST['days']) ? max(1, min(365, intval($_POST['days']))) : 30;
    $onlyChecklist = !empty($_POST['onlyChecklist']) ? 1 : 0;

    $query = [
        'page' => $page,
        'limit' => $limit,
        'q' => $q,
        'days' => $days,
        'onlyChecklist' => $onlyChecklist,
    ];
    if ($instancia !== '') $query['instancia'] = $instancia;

    $url = $base . '/api/integrations/mercadolibre/checklist/logs?' . http_build_query($query);
    $r = cpn_node_request('GET', $url, $token, null);

    if (!empty($r['ok'])) {
        json_out(['ok' => true, 'data' => $r['data'] ?? []]);
    }

    $msg = '';
    if (isset($r['error']['message'])) $msg = $r['error']['message'];
    elseif (isset($r['error'])) $msg = is_string($r['error']) ? $r['error'] : '';
    json_out(['ok' => false, 'error' => $msg ?: 'No se pudo listar']);
}

?>
<?php include '../../templates/header.php'; ?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <h1 class="h3 mb-0 text-gray-800">MercadoLibre – Checklist (Logs)</h1>
    <div class="small text-muted" id="mlChecklistSummary"></div>
</div>

<div class="card shadow mb-3">
    <div class="card-body">
        <div class="form-row">
            <div class="form-group col-md-5">
                <label class="small">Buscar</label>
                <input type="text" id="q" class="form-control form-control-sm" placeholder="Texto en el log (ej: MCO..., sku, ...)">
            </div>
            <div class="form-group col-md-3">
                <label class="small">Instancia</label>
                <input type="text" id="instancia" class="form-control form-control-sm" placeholder="(opcional)">
            </div>
            <div class="form-group col-md-2">
                <label class="small">Días</label>
                <select id="days" class="form-control form-control-sm">
                    <option value="7">7</option>
                    <option value="15">15</option>
                    <option value="30" selected>30</option>
                    <option value="60">60</option>
                    <option value="90">90</option>
                    <option value="365">365</option>
                </select>
            </div>
            <div class="form-group col-md-2">
                <label class="small">Límite</label>
                <select id="limit" class="form-control form-control-sm">
                    <option value="50">50</option>
                    <option value="100" selected>100</option>
                    <option value="200">200</option>
                    <option value="500">500</option>
                </select>
            </div>
        </div>

        <div class="form-row align-items-end">
            <div class="form-group col-md-6">
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" id="onlyChecklist" checked>
                    <label class="custom-control-label" for="onlyChecklist">Solo mensajes de conexión (no conectado)</label>
                </div>
            </div>
            <div class="form-group col-md-6 text-right">
                <button class="btn btn-sm btn-primary" id="btnBuscar">Buscar</button>
            </div>
        </div>

        <div style="overflow-x:auto">
            <table class="table table-sm table-bordered mb-0" id="mlChecklistTable">
                <thead>
                    <tr>
                        <th>Fecha</th>
                        <th>Instancia</th>
                        <th>Mensaje</th>
                        <th>ML IDs</th>
                        <th>Encontrado en Compranet</th>
                        <th>Acción</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>

        <div class="d-flex justify-content-between align-items-center mt-2">
            <button class="btn btn-sm btn-outline-secondary" id="prevPage">«</button>
            <div class="small text-muted" id="pager"></div>
            <button class="btn btn-sm btn-outline-secondary" id="nextPage">»</button>
        </div>
    </div>
</div>

<script>
    (function() {
        function esc(v) {
            return String(v == null ? '' : v)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function fmtDate(value) {
            const raw = String(value || '').trim();
            if (!raw) return '';

            // MySQL dateStrings: "YYYY-MM-DD HH:MM:SS"
            const d = new Date(raw.replace(' ', 'T'));
            if (isNaN(d.getTime())) return raw;

            const months = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
            const dd = String(d.getDate()).padStart(2, '0');
            const mon = months[d.getMonth()] || '';
            const yy = String(d.getFullYear()).slice(-2);

            let hh = d.getHours();
            const mm = String(d.getMinutes()).padStart(2, '0');
            const ampm = hh >= 12 ? 'pm' : 'am';
            hh = hh % 12;
            if (hh === 0) hh = 12;

            return dd + '-' + mon + '-' + yy + ' ' + hh + ':' + mm + ' ' + ampm;
        }

        const state = {
            page: 1,
            totalPages: 1,
        };

        function buildMatchesHtml(item) {
            const mpProducts = (item && item.matches && item.matches.marketplaceProducts) ? item.matches.marketplaceProducts : [];
            const mpVariants = (item && item.matches && item.matches.marketplaceVariants) ? item.matches.marketplaceVariants : [];

            const parts = [];

            if (item.kind === 'product_not_connected') {
                if (!mpProducts.length) {
                    parts.push('<div class="text-danger small">No existe en tb_marketplace_productos por refMP</div>');
                } else {
                    parts.push('<div class="small font-weight-bold">Producto:</div>');
                    mpProducts.forEach(function(p) {
                        const conectado = Number(p.conectado || 0) === 1;
                        const txt = 'MPProd #' + esc(p.idMarketplaceProducto) +
                            ' | idProducto=' + esc(p.idProducto) +
                            (p.referenciaCPN ? ' | ' + esc(p.referenciaCPN) : '') +
                            (p.nombreProducto ? ' | ' + esc(p.nombreProducto) : '') +
                            ' | conectado=' + (conectado ? '1' : '0');
                        parts.push('<div class="small">' + txt + '</div>');
                    });
                }
            }

            if (item.kind === 'variant_not_connected') {
                if (!mpVariants.length) {
                    parts.push('<div class="text-danger small">No existe en tb_marketplace_variantes por refMPVariante</div>');
                } else {
                    parts.push('<div class="small font-weight-bold">Variante:</div>');
                    mpVariants.forEach(function(v) {
                        const conectado = Number(v.conectado || 0) === 1;
                        const txt = 'MPVar #' + esc(v.idMarketplaceVariante) +
                            ' | idVariante=' + esc(v.idVariante) +
                            ' | sku=' + esc(v.skuMPVariante || '') +
                            ' | conectado=' + (conectado ? '1' : '0');
                        parts.push('<div class="small">' + txt + '</div>');
                    });
                }

                // También mostramos si el producto padre existe
                if (item.refMP) {
                    if (!mpProducts.length) {
                        parts.push('<div class="text-warning small">(Producto padre no encontrado por refMP)</div>');
                    } else {
                        parts.push('<div class="small text-muted">(Producto padre OK)</div>');
                    }
                }
            }

            if (item.kind === 'other') {
                parts.push('<div class="small text-muted">—</div>');
            }

            return parts.join('');
        }

        function buildActionHtml(item) {
            const mpProducts = (item && item.matches && item.matches.marketplaceProducts) ? item.matches.marketplaceProducts : [];
            const mpVariants = (item && item.matches && item.matches.marketplaceVariants) ? item.matches.marketplaceVariants : [];

            // Preferimos abrir el producto en Compranet si lo tenemos
            let idProducto = null;
            if (mpProducts.length) {
                idProducto = Number(mpProducts[0].idProducto || 0) || null;
            } else if (mpVariants.length) {
                idProducto = Number(mpVariants[0].idProducto || 0) || null;
            }

            const btns = [];
            if (idProducto) {
                btns.push('<a class="btn btn-sm btn-outline-primary" target="_blank" href="/productos/producto.php?id=' + esc(idProducto) + '">Abrir Producto</a>');
            }

            if (item.refMP) {
                btns.push('<button type="button" class="btn btn-sm btn-outline-secondary btn-copy" data-copy="' + esc(item.refMP) + '">Copiar MCO</button>');
            }
            if (item.refMPVariante) {
                btns.push('<button type="button" class="btn btn-sm btn-outline-secondary btn-copy" data-copy="' + esc(item.refMPVariante) + '">Copiar Var</button>');
            }

            return '<div class="d-flex flex-wrap" style="gap:6px">' + btns.join('') + '</div>';
        }

        function render(items) {
            const rows = (items || []).map(function(item) {
                const ids = [];
                if (item.refMP) ids.push('<div class="small"><b>Producto:</b> ' + esc(item.refMP) + '</div>');
                if (item.refMPVariante) ids.push('<div class="small"><b>Variante:</b> ' + esc(item.refMPVariante) + '</div>');
                if (!ids.length) ids.push('<div class="small text-muted">—</div>');

                return [
                    '<tr>',
                    '<td style="min-width:140px">' + esc(fmtDate(item.fechaHora)) + '</td>',
                    '<td style="min-width:140px">' + esc(item.instancia || '') + '</td>',
                    '<td style="min-width:420px">' + esc(item.mensaje || '') + '</td>',
                    '<td style="min-width:160px">' + ids.join('') + '</td>',
                    '<td style="min-width:420px">' + buildMatchesHtml(item) + '</td>',
                    '<td style="min-width:220px">' + buildActionHtml(item) + '</td>',
                    '</tr>'
                ].join('');
            }).join('');

            $('#mlChecklistTable tbody').html(rows || '<tr><td colspan="6" class="text-center text-muted">Sin resultados</td></tr>');
        }

        function load() {
            $('#mlChecklistSummary').text('Cargando…');

            return $.ajax({
                    url: window.location.pathname,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'list',
                        page: state.page,
                        limit: $('#limit').val(),
                        q: $('#q').val(),
                        instancia: $('#instancia').val(),
                        days: $('#days').val(),
                        onlyChecklist: $('#onlyChecklist').is(':checked') ? 1 : 0,
                    }
                })
                .done(function(res) {
                    if (!res || !res.ok) {
                        $('#mlChecklistSummary').text('Error');
                        alert((res && res.error) ? res.error : 'No se pudo listar');
                        return;
                    }

                    const data = res.data || {};
                    const items = data.items || [];
                    state.totalPages = Number(data.totalPages || 1) || 1;

                    $('#pager').text('Página ' + String(data.page || state.page) + ' / ' + String(state.totalPages) + ' — Total: ' + String(data.totalCount || 0));
                    $('#mlChecklistSummary').text('Últimos ' + String($('#days').val()) + ' días');

                    render(items);
                })
                .fail(function(xhr) {
                    console.error(xhr && xhr.responseText);
                    $('#mlChecklistSummary').text('Error');
                    alert('Error de red');
                });
        }

        $(function() {
            $('#btnBuscar').on('click', function() {
                state.page = 1;
                load();
            });

            $('#q').on('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    state.page = 1;
                    load();
                }
            });

            $('#prevPage').on('click', function() {
                state.page = Math.max(1, state.page - 1);
                load();
            });
            $('#nextPage').on('click', function() {
                state.page = Math.min(state.totalPages || 1, state.page + 1);
                load();
            });

            $('#mlChecklistTable').on('click', '.btn-copy', function() {
                const txt = $(this).data('copy');
                if (!txt) return;
                navigator.clipboard.writeText(String(txt));
            });

            load();
        });
    })();
</script>

<?php include '../../templates/footer.php'; ?>