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

requireAdmin();

$pageTitle = 'Subir Imágenes Admin';

$success = '';
$error = '';

$galleryPath = __DIR__ . '/galeria';

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)) {
                $success = 'Imagen subida correctamente';
            } else {
                $error = 'Error al subir la imagen';
            }
        } else {
            $error = 'Tipo de archivo no válido';
        }
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-upload"></i> Subir Imágenes</h2>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload">
            
            <div class="mb-3">
                <label class="form-label">Seleccionar imagen</label>
                <input type="file" name="image" class="form-control" accept="image/*" required>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-upload"></i> Subir
            </button>
        </form>
    </div>
</div>

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