<?php
session_start();
include '../includes/session_control.php';
require_once '../cotizaciones/api/_node.php';

function cpn_fmt_dt(?string $dt): string
{
    if (!$dt) return '-';
    $ts = strtotime($dt);
    if (!$ts) return htmlspecialchars($dt);
    return date('d-M-y g:i a', $ts);
}

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

// → PAGINACIÓN
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit  = 100;

$view = cpn_node_request(
    'GET',
    $base . '/api/banners/listado/view?page=' . urlencode((string)$page) . '&limit=' . urlencode((string)$limit),
    $token
);
if (!($view['ok'] ?? false)) {
    $msg = $view['error']['message'] ?? 'No se pudo cargar banners.';
    http_response_code(($view['_http'] ?? 500) ?: 500);
    exit($msg);
}

$data = $view['data'] ?? [];
$banners = $data['banners'] ?? [];
$ubicaciones = $data['ubicaciones'] ?? [];
$estados = $data['estados'] ?? [];
$pagination = $data['pagination'] ?? [];

$totalPages = intval($pagination['totalPages'] ?? 1);
$totalCount = intval($pagination['totalCount'] ?? 0);
?>
<?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;
        vertical-align: middle;
    }

    #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;
    }

    .cpn-banner-thumb {
        max-width: 120px;
        max-height: 60px;
        width: auto;
        height: auto;
        object-fit: contain;
    }
</style>

<h1 class="h3 mb-4 text-gray-800">Listado de Banners</h1>

<button class="btn btn-success mb-3" data-bs-toggle="modal" data-bs-target="#newBannerModal">
    Agregar Nuevo Banner
</button>

<div class="table-responsive mb-4">
    <table class="table table-bordered table-sm align-middle">
        <thead>
            <tr>
                <th>Banner</th>
                <th>Ubicación</th>
                <th>No. Orden</th>
                <th>Fecha Desde</th>
                <th>Fecha Hasta</th>
                <th>Estado</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($banners as $r): ?>
                <tr>
                    <td>
                        <img src="<?= htmlspecialchars($r['urlImagen']) ?>" class="cpn-banner-thumb" alt="Banner">
                    </td>
                    <td><?= htmlspecialchars($r['ubicacion']) ?></td>
                    <td>
                        <input type="number" class="form-control form-control-sm edit-orden" data-id="<?= $r['id'] ?>" value="<?= $r['noOrden'] ?>">
                    </td>
                    <td><?= cpn_fmt_dt($r['fechaDesde'] ?? null) ?></td>
                    <td><?= cpn_fmt_dt($r['fechaHasta'] ?? null) ?></td>
                    <td><?= htmlspecialchars($r['estado']) ?></td>
                    <td>
                        <a href="editar_banner.php?id=<?= $r['id'] ?>" class="btn btn-primary btn-sm">Editar</a>

                        <form method="post" action="eliminar_banner.php" style="display:inline-block; margin-left:.5em;" onsubmit="return confirm('¿Eliminar este banner?');">
                            <input type="hidden" name="id" value="<?= $r['id'] ?>">
                            <button type="submit" class="btn btn-sm btn-danger">Eliminar</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- PAGINACIÓN -->
<nav>
    <ul class="pagination justify-content-center">
        <?php if ($page > 1): ?>
            <li class="page-item"><a class="page-link" href="?page=<?= $page - 1 ?>">&laquo;</a></li>
        <?php endif; ?>

        <?php
        $start = max(1, $page - 2);
        $end   = min($totalPages, $page + 2);
        for ($p = $start; $p <= $end; $p++): ?>
            <li class="page-item <?= $p == $page ? 'active' : '' ?>"><a class="page-link" href="?page=<?= $p ?>"><?= $p ?></a></li>
        <?php endfor; ?>

        <?php if ($page < $totalPages): ?>
            <li class="page-item"><a class="page-link" href="?page=<?= $page + 1 ?>">&raquo;</a></li>
        <?php endif; ?>
    </ul>
</nav>

<!-- MODAL: Nuevo Banner -->
<div class="modal fade" id="newBannerModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="post" action="guardar_banner.php" enctype="multipart/form-data" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Agregar Nuevo Banner</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>Ubicación</label>
                    <select name="idUbicacion" class="form-control form-control-sm" required>
                        <option value="">Seleccione...</option>
                        <?php foreach ($ubicaciones as $u): ?>
                            <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['nombre']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label>Estado</label>
                    <select name="idEstado" class="form-control" required>
                        <option value="">Seleccione...</option>
                        <?php foreach ($estados as $e): ?>
                            <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['nombre']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label>No. Orden</label>
                    <input type="number" name="noOrden" class="form-control" required>
                </div>

                <div class="row g-2 mb-3">
                    <div class="col">
                        <label>Fecha Desde</label>
                        <input type="datetime-local" name="fechaDesde" class="form-control">
                    </div>
                    <div class="col">
                        <label>Fecha Hasta</label>
                        <input type="datetime-local" name="fechaHasta" class="form-control">
                    </div>
                </div>

                <div class="mb-3">
                    <label>Imagen</label>
                    <input type="file" name="imagen" class="form-control" accept="image/*" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                <button type="submit" class="btn btn-primary">Guardar</button>
            </div>
        </form>
    </div>
</div>

<script>
    document.querySelectorAll('.edit-orden').forEach(input => {
        input.addEventListener('change', () => {
            const id = input.dataset.id;
            const noOrden = input.value;
            fetch('update_banner.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    id,
                    noOrden
                })
            });
        });
    });

    $(function() {
        try {
            $('#newBannerModal select').select2({
                width: '100%'
            });
        } catch (e) {
            // Si select2 no está disponible, continuar sin romper la página.
        }
    });
</script>

<?php include '../templates/footer.php'; ?>