<?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();

// (nuevo) Si llaman con action=update_checklist, ejecuto el procedimiento y recargo sin ese parámetro
if (isset($_GET['action']) && $_GET['action'] === 'update_checklist') {
    cpn_node_request('POST', $base . '/api/productos/items/checklist', $token, null);
    // recargo sin el parámetro action para evitar re-ejecución al refrescar
    $qs = $_GET;
    unset($qs['action']);
    header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($qs));
    exit;
}
// (nuevo) Si llaman con action=view_all, guardo TODO el listado en sesión


// ===== Obtener lista de proveedores para el filtro =========
$metaResp = cpn_node_request('GET', $base . '/api/productos/items/meta', $token, null);
$providers = $metaResp['data']['proveedores'] ?? [];


$page    = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit   = 50;
$filter1 = (string)($_GET['filter_referenciaCPN']   ?? '');
$filter2 = (string)($_GET['filter_referenciaProv']  ?? '');
$filter3 = (string)($_GET['filter_nombre']          ?? '');
$filterProvId = isset($_GET['filter_proveedor']) ? intval($_GET['filter_proveedor']) : 0;

// Nuevo filtro: checklist group
// Default: mostrar "mal publicados" + "con pendientes"
$filterChecklistGroup = (string)($_GET['filter_checklist_group'] ?? '');
if ($filterChecklistGroup === '') {
    $filterChecklistGroup = 'issues';
}

$listQuery = [
    'page' => $page,
    'limit' => $limit,
    'filter_referenciaCPN' => $filter1,
    'filter_referenciaProv' => $filter2,
    'filter_nombre' => $filter3,
    'filter_checklist_group' => $filterChecklistGroup,
];
if ($filterProvId) $listQuery['filter_proveedor'] = $filterProvId;

// Stats para contadores de botones (no depende del filtro por checklist)
$statsQuery = [
    'filter_referenciaCPN' => $filter1,
    'filter_referenciaProv' => $filter2,
    'filter_nombre' => $filter3,
];
if ($filterProvId) $statsQuery['filter_proveedor'] = $filterProvId;
$qsStats = http_build_query($statsQuery);
$statsResp = cpn_node_request('GET', $base . '/api/productos/items/stats' . ($qsStats ? ('?' . $qsStats) : ''), $token, null);
$stats = $statsResp['data'] ?? ['mal_publicados' => 0, 'pendientes' => 0, 'sin_publicar' => 0, 'total' => 0];

if (isset($_GET['action']) && $_GET['action'] === 'view_all') {
    $idsQuery = $listQuery;
    unset($idsQuery['page'], $idsQuery['limit']);
    $qs = http_build_query($idsQuery);
    $idsResp = cpn_node_request('GET', $base . '/api/productos/items/ids' . ($qs ? ('?' . $qs) : ''), $token, null);
    $ids = $idsResp['data']['ids'] ?? [];
    $_SESSION['item_list'] = $ids;

    if (!empty($ids)) {
        header('Location: producto.php?id=' . $ids[0]);
        exit;
    }

    $qs2 = $_GET;
    unset($qs2['action']);
    header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($qs2));
    exit;
}

$qsList = http_build_query($listQuery);
$listResp = cpn_node_request('GET', $base . '/api/productos/items' . ($qsList ? ('?' . $qsList) : ''), $token, null);
$items = $listResp['data']['items'] ?? [];
$totalPages = (int)($listResp['data']['totalPages'] ?? 1);
$page = (int)($listResp['data']['page'] ?? $page);
?>
<?php include '../templates/header.php'; ?>

<style>
    /* Compacto (solo esta pantalla) */
    #content .container-fluid .table {
        font-size: 12px;
    }

    #content .container-fluid .table th,
    #content .container-fluid .table td {
        padding: .25rem .35rem;
        line-height: 1.15;
    }

    #content .container-fluid .form-control,
    #content .container-fluid .custom-select,
    #content .container-fluid .form-select {
        font-size: 12px !important;
        padding: .2rem .4rem;
        height: calc(1.2em + .5rem + 2px);
    }

    #content .container-fluid .btn {
        font-size: 12px;
        padding: .25rem .5rem;
    }

    #content .container-fluid h1.h3,
    #content .container-fluid .h3 {
        font-size: 1.1rem;
    }
</style>
<h1 class="h3 mb-4 text-gray-800">Lista de Items</h1>
<div class="mb-3">
    <a
        href="?<?= http_build_query(array_merge($_GET, ['action' => 'update_checklist'])) ?>"
        class="btn btn-success">
        Actualizar Checklist
    </a>
    <a
        href="?<?= http_build_query(array_merge($_GET, ['action' => 'view_all'])) ?>"
        target="_blank"
        class="btn btn-info">Revisar seleccionados</a>
</div>

<div class="mb-3">
    <?php
    $baseQs = $_GET;
    unset($baseQs['page']);
    $btnMal = http_build_query(array_merge($baseQs, ['filter_checklist_group' => 'mal_publicados', 'page' => 1]));
    $btnPend = http_build_query(array_merge($baseQs, ['filter_checklist_group' => 'pendientes', 'page' => 1]));
    $btnSinPub = http_build_query(array_merge($baseQs, ['filter_checklist_group' => 'sin_publicar', 'page' => 1]));
    $btnAll = http_build_query(array_merge($baseQs, ['filter_checklist_group' => 'all', 'page' => 1]));
    $activeClass = function ($key) use ($filterChecklistGroup) {
        return $filterChecklistGroup === $key ? ' active' : '';
    };
    ?>

    <a href="?<?= $btnMal ?>" class="btn btn-outline-danger<?= $activeClass('mal_publicados') ?>">
        Mal publicados (<?= (int)($stats['mal_publicados'] ?? 0) ?>)
    </a>
    <a href="?<?= $btnPend ?>" class="btn btn-outline-warning<?= $activeClass('pendientes') ?>">
        Con pendientes para publicar (<?= (int)($stats['pendientes'] ?? 0) ?>)
    </a>
    <a href="?<?= $btnSinPub ?>" class="btn btn-outline-secondary<?= $activeClass('sin_publicar') ?>">
        Sin publicar (<?= (int)($stats['sin_publicar'] ?? 0) ?>)
    </a>
    <a href="?<?= $btnAll ?>" class="btn btn-outline-dark<?= $activeClass('all') ?>">
        Ver todos
    </a>
</div>

<form class="form-inline mb-3" method="get">
    <input type="text" name="filter_referenciaCPN" class="form-control mr-2 mb-2" placeholder="Filtrar Ref. CPN" value="<?= htmlspecialchars($filter1) ?>">
    <input type="text" name="filter_referenciaProv" class="form-control mr-2 mb-2" placeholder="Filtrar Ref. Prov." value="<?= htmlspecialchars($filter2) ?>">
    <select id="filter_proveedor" name="filter_proveedor" class="form-control mr-2 mb-2" onchange="this.form.submit()">
        <option value="">— Todos los proveedores —</option>
        <?php foreach ($providers as $pr): ?>
            <option
                value="<?= $pr['id'] ?>"
                <?= $filterProvId === (int)$pr['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($pr['nombre']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <input type="text" name="filter_nombre" class="form-control mr-2 mb-2" placeholder="Filtrar Nombre" value="<?= htmlspecialchars($filter3) ?>">
    <button type="submit" class="btn btn-primary mb-2 mr-2">Buscar</button>

    <input type="hidden" name="filter_checklist_group" value="<?= htmlspecialchars($filterChecklistGroup) ?>">
</form>

<script>
    $(function() {
        var $prov = $('#filter_proveedor');
        if ($prov.length && $.fn.select2) {
            $prov.addClass('select2-dark');
            $prov.select2({
                width: 'resolve'
            });
            $prov.on('change', function() {
                this.form && this.form.submit();
            });
        }
    });
</script>

<div class="table-responsive mb-3">
    <table class="table table-bordered">
        <thead class="thead-light">
            <tr>
                <th class="text-center">Imagen</th>
                <th class="text-center">Ref. CPN</th>
                <th class="text-center">Ref. Prov.</th>
                <th class="text-center">Estado</th>
                <th class="text-center">Proveedor</th>
                <th class="text-center">Nombre</th>
                <th class="text-center">Publicado</th>
                <th class="text-center">Inventario</th>
                <th class="text-center">CheckList</th>
                <th class="text-center">Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $row): ?>
                <tr>
                    <td class="text-center">
                        <?php
                        $img = $row['Imagen']
                            ? str_replace('J:/', 'https://sistema.compranet.com.co/', $row['Imagen'])
                            : '/img/no-image.png';
                        ?>
                        <img src="<?= $img ?>" width="50" alt="">
                    </td>
                    <td><?= htmlspecialchars($row['referenciaCPN']) ?></td>
                    <td><?= htmlspecialchars($row['referenciaProveedor']) ?></td>
                    <td class="estado-cell estado-<?= $row['estadoId'] ?>">
                        <?= htmlspecialchars($row['Estado']) ?>
                    </td>
                    <td><?= htmlspecialchars($row['Proveedor']) ?></td>
                    <td>
                        <a href="<?= htmlspecialchars($row['urlExterna']) ?>" target="_blank">
                            <?= htmlspecialchars($row['nombre']) ?>
                        </a>
                    </td>
                    <td class="text-center">
                        <?php if ($row['wp_id']): ?>
                            <a href="https://compranet.com.co/?p=<?= $row['wp_id'] ?>" target="_blank" class="badge badge-success">Publicado</a>
                        <?php else: ?>
                            <?php if (in_array($row['estadoId'], [1, 3])): ?>
                                <span class="badge badge-danger">NO</span>
                            <?php else: ?>
                                <span class="badge badge-secondary">-</span>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                    <td class="text-right"><?= number_format($row['Inventario'], 0, '', '.') ?></td>

                    <?php
                    $cs = (int)($row['checklistStatus'] ?? -1);
                    $badge = 'badge-secondary';
                    $label = '—';
                    if ($cs === 0) {
                        $badge = 'badge-warning';
                        $label = 'Pendientes';
                    } elseif ($cs === 1) {
                        $badge = 'badge-success';
                        $label = 'Listo';
                    } elseif ($cs === 2) {
                        $badge = 'badge-secondary';
                        $label = 'No disponible';
                    } elseif ($cs === 3) {
                        $badge = 'badge-danger';
                        $label = 'Mal publicado';
                    }
                    ?>
                    <td>
                        <span class="badge <?= $badge ?>"><?= $label ?></span>
                        <?php if (!empty($row['checklistInfo'])): ?>
                            <div class="small text-muted mt-1"><?= nl2br(htmlspecialchars($row['checklistInfo'])) ?></div>
                        <?php endif; ?>
                    </td>


                    <td class="text-center">
                        <?php $productId = (int)($row['idProducto'] ?? $row['id'] ?? 0); ?>
                        <?php if ($productId > 0): ?>
                            <a href="/productos/producto.php?id=<?= $productId ?>" class="btn btn-sm btn-primary">
                                Editar
                            </a>
                        <?php else: ?>
                            <span class="btn btn-sm btn-secondary disabled" aria-disabled="true">Sin ID</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Paginación con ventana deslizante -->
<nav aria-label="Paginación">
    <ul class="pagination justify-content-center">
        <?php
        // Anterior
        if ($page > 1) {
            $prev = $page - 1;
            echo "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . http_build_query(array_merge($_GET, ['page' => $prev])) . "\">&laquo;</a></li>";
        }
        // Ventana de páginas
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        if ($start > 1) {
            echo "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . http_build_query(array_merge($_GET, ['page' => 1])) . "\">1</a></li>";
            if ($start > 2) {
                echo "<li class=\"page-item disabled\"><span class=\"page-link\">…</span></li>";
            }
        }
        for ($p = $start; $p <= $end; $p++) {
            $active = $p == $page ? ' active' : '';
            echo "<li class=\"page-item{$active}\"><a class=\"page-link\" href=\"?" . http_build_query(array_merge($_GET, ['page' => $p])) . "\">{$p}</a></li>";
        }
        if ($end < $totalPages) {
            if ($end < $totalPages - 1) {
                echo "<li class=\"page-item disabled\"><span class=\"page-link\">…</span></li>";
            }
            echo "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . http_build_query(array_merge($_GET, ['page' => $totalPages])) . "\">{$totalPages}</a></li>";
        }
        // Siguiente
        if ($page < $totalPages) {
            $next = $page + 1;
            echo "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . http_build_query(array_merge($_GET, ['page' => $next])) . "\">&raquo;</a></li>";
        }
        ?>
    </ul>
</nav>
</div>
</div>
<?php include '../templates/footer.php'; ?>
