<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
checkSession();

$pageTitle = 'Galería de Imágenes';

$galleryPath = __DIR__ . '/galeria';
$images = [];

if (is_dir($galleryPath)) {
    $files = scandir($galleryPath);
    foreach ($files as $file) {
        if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
            $images[] = $file;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'upload' && !empty($_FILES['image']['name'])) {
        $targetFile = $galleryPath . '/' . basename($_FILES['image']['name']);
        
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        if (in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
                logActivity(getCurrentUserId(), 'upload_image', 'Imagen subida: ' . $_FILES['image']['name']);
                header('Location: gallery.php');
                exit;
            }
        }
        
    } elseif ($action === 'delete' && !empty($_POST['filename'])) {
        $fileToDelete = $galleryPath . '/' . basename($_POST['filename']);
        if (file_exists($fileToDelete)) {
            unlink($fileToDelete);
            logActivity(getCurrentUserId(), 'delete_image', 'Imagen eliminada: ' . $_POST['filename']);
            header('Location: gallery.php');
            exit;
        }
        
    } elseif ($action === 'rename' && !empty($_POST['oldname']) && !empty($_POST['newname'])) {
        $oldFile = $galleryPath . '/' . basename($_POST['oldname']);
        $newFile = $galleryPath . '/' . basename($_POST['newname']);
        
        if (file_exists($oldFile) && !file_exists($newFile)) {
            rename($oldFile, $newFile);
            logActivity(getCurrentUserId(), 'rename_image', 'Imagen renombrada: ' . $_POST['oldname'] . ' -> ' . $_POST['newname']);
            header('Location: gallery.php');
            exit;
        }
    }
}

require_once __DIR__ . '/templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-images"></i> Galería de Imágenes</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadModal">
        <i class="bi bi-upload"></i> Subir Imagen
    </button>
</div>

<?php if (empty($images)): ?>
    <div class="alert alert-info">No hay imágenes en la galería</div>
<?php else: ?>
    <div class="row">
        <?php foreach ($images as $image): ?>
        <div class="col-md-3 col-sm-4 col-6 mb-4">
            <div class="card border-0 shadow-sm">
                <img src="galeria/<?= urlencode($image) ?>" class="card-img-top" alt="<?= htmlspecialchars($image) ?>" style="height: 150px; object-fit: cover;">
                <div class="card-body py-2">
                    <small class="d-block text-truncate"><?= htmlspecialchars($image) ?></small>
                    <div class="btn-group btn-group-sm mt-2">
                        <button class="btn btn-outline-primary" onclick="copyUrl('<?= urlencode($image) ?>')" title="Copiar URL">
                            <i class="bi bi-clipboard"></i>
                        </button>
                        <button class="btn btn-outline-secondary" onclick="renameImage('<?= htmlspecialchars($image) ?>')" title="Renombrar">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <form method="POST" onsubmit="return confirm('¿Eliminar esta imagen?');" class="d-inline">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="filename" value="<?= htmlspecialchars($image) ?>">
                            <button type="submit" class="btn btn-outline-danger" title="Eliminar">
                                <i class="bi bi-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload">
                <div class="modal-header">
                    <h5 class="modal-title">Subir Imagen</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="file" name="image" class="form-control" accept="image/*" required>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Subir</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="renameModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="rename">
                <div class="modal-header">
                    <h5 class="modal-title">Renombrar Imagen</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="oldname" id="renameOldname">
                    <div class="mb-3">
                        <label class="form-label">Nuevo nombre</label>
                        <input type="text" name="newname" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Renombrar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function copyUrl(filename) {
    const url = window.location.origin + '/galeria/' + filename;
    navigator.clipboard.writeText(url).then(() => {
        alert('URL copiada al portapapeles');
    });
}

function renameImage(filename) {
    document.getElementById('renameOldname').value = filename;
    const modal = new bootstrap.Modal(document.getElementById('renameModal'));
    modal.show();
}
</script>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
