<?php
$uploadDir = 'uploads/';
$images = glob($uploadDir . '*.{jpg,jpeg,png,webp}', GLOB_BRACE);

// Ordenar las imágenes por fecha de subida (últimas subidas primero)
usort($images, function($a, $b) {
    return filemtime($b) - filemtime($a);
});

// Configuración de la paginación
$imagesPerPage = 24; // Mostrar 20 imágenes por página
$totalImages = count($images);
$totalPages = ceil($totalImages / $imagesPerPage);
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
if ($page > $totalPages) $page = $totalPages;

$start = ($page - 1) * $imagesPerPage;
$currentImages = array_slice($images, $start, $imagesPerPage);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['delete'])) {
        $fileToDelete = $_POST['delete'];
        if (file_exists($fileToDelete)) {
            unlink($fileToDelete);
        }
    } elseif (isset($_POST['download'])) {
        $fileToDownload = $_POST['download'];
        if (file_exists($fileToDownload)) {
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($fileToDownload));
            header('Content-Length: ' . filesize($fileToDownload));
            readfile($fileToDownload);
            exit;
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Visualizar imagenes</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        .image-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: center;
        }
        .image-wrapper {
            position: relative;
            display: inline-block;
            width: 150px; /* Ancho fijo */
            height: 150px; /* Alto fijo */
            overflow: hidden;
        }
        .image-wrapper img {
            width: 100%;
            height: 100%;
            object-fit: cover; /* Asegura que la imagen se ajuste al contenedor manteniendo la relación de aspecto */
            cursor: pointer;
        }
        .image-wrapper form {
            position: absolute;
            top: 0;
            right: 0;
            display: flex;
            gap: 5px;
        }
        .image-wrapper button {
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            padding: 5px;
            cursor: pointer;
            border-radius: 3px;
        }
        .image-wrapper button:hover {
            background-color: rgba(0, 0, 0, 0.8);
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.9);
        }
        .modal-content {
            margin: auto;
            display: block;
            max-width: 80%;
            max-height: 80%;
        }
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #fff;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover,
        .close:focus {
            color: #bbb;
            text-decoration: none;
            cursor: pointer;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination a {
            margin: 0 5px;
            padding: 10px 15px;
            text-decoration: none;
            color: #333;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        .pagination a.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        .pagination a:hover {
            background-color: #ddd;
        }
    </style>
</head>
<body>
    <h1>Visualizar imagenes</h1>
    <div class="image-container">
        <?php if (!empty($currentImages)): ?>
            <?php foreach ($currentImages as $image): ?>
                <div class="image-wrapper">
                    <img src="<?php echo $image; ?>" alt="Image">
                    <form method="post">
                        <button type="submit" name="download" value="<?php echo $image; ?>">Descargar</button>
                        <button type="submit" name="delete" value="<?php echo $image; ?>">Eliminar</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <p>No hay imágenes para mostrar.</p>
        <?php endif; ?>
    </div>

    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?php echo $i; ?>" class="<?php if ($i == $page) echo 'active'; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>

    <div id="myModal" class="modal">
        <span class="close">&times;</span>
        <img class="modal-content" id="img01">
    </div>

    <script>
        var modal = document.getElementById("myModal");
        var modalImg = document.getElementById("img01");
        var images = document.querySelectorAll(".image-wrapper img");

        images.forEach(image => {
            image.onclick = function() {
                modal.style.display = "block";
                modalImg.src = this.src;
            }
        });

        var span = document.getElementsByClassName("close")[0];

        span.onclick = function() {
            modal.style.display = "none";
        }
    </script>
</body>
</html>
