<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once 'db/config.php';
$db = db();

// Fetch products for dropdown
$products = $db->query("SELECT id, nombre FROM products ORDER BY nombre ASC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch kanban columns
$kanban_columns = $db->query("SELECT id, nombre FROM kanban_columns ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

// Fetch existing info cards
$info_cards = $db->query("
    SELECT ip.*, p.nombre as producto_nombre, kc.nombre as column_nombre
    FROM info_productos ip
    LEFT JOIN products p ON ip.producto_id = p.id
    LEFT JOIN kanban_columns kc ON ip.column_id = kc.id
    ORDER BY ip.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

include 'layout_header.php';
?>

<div class="container mt-5">
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success">
            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
        </div>
    <?php endif; ?>
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger">
            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
        </div>
    <?php endif; ?>

    <!-- Form to add/edit info card -->
    <div class="card mb-5">
        <div class="card-header">
            <h2>Gestionar Tarjetas de Información</h2>
        </div>
        <div class="card-body">
            <form action="save_info_producto.php" method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" id="info-id">
                <div class="form-group">
                    <label for="producto_id">Producto</label>
                    <select name="producto_id" id="producto_id" class="form-control">
                        <option value="">Selecciona un producto</option>
                        <?php foreach ($products as $product): ?>
                            <option value="<?php echo $product['id']; ?>"><?php echo htmlspecialchars($product['nombre']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="texto_informativo">Texto Informativo</label>
                    <textarea name="texto_informativo" id="texto_informativo" class="form-control" rows="3" required></textarea>
                </div>
                <div class="form-group">
                    <label for="imagen">Imagen</label>
                    <div id="image-preview" class="mt-2 mb-2"></div>
                    <input type="file" name="imagen" id="imagen" class="form-control-file">
                    <input type="hidden" name="current_imagen" id="current_imagen">
                    <small class="form-text text-muted">Sube una imagen si quieres añadir una nueva o reemplazar la actual.</small>
                </div>
                <div class="form-group">
                    <label for="column_id">Columna Kanban</label>
                    <select name="column_id" id="column_id" class="form-control" required>
                        <option value="">Selecciona una columna</option>
                        <?php foreach ($kanban_columns as $column): ?>
                            <option value="<?php echo $column['id']; ?>"><?php echo htmlspecialchars($column['nombre']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-primary">Guardar Tarjeta</button>
                <button type="button" class="btn btn-secondary" onclick="resetForm()">Limpiar Formulario</button>
            </form>
        </div>
    </div>

    <!-- List of existing info cards -->
    <div class="card mb-5">
        <div class="card-header">
            <h3>Tarjetas Existentes</h3>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Producto</th>
                            <th>Imagen</th>
                            <th>Texto</th>
                            <th>Columna</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($info_cards)): ?>
                            <tr>
                                <td colspan="5" class="text-center">No hay tarjetas de información creadas.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($info_cards as $card): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($card['producto_nombre'] ?: 'N/A'); ?></td>
                                    <td>
                                        <?php if (!empty($card['imagen_url'])): ?>
                                            <img src="<?php echo htmlspecialchars($card['imagen_url']); ?>?t=<?php echo time(); ?>" alt="Imagen" style="width: 100px; height: auto; border-radius: 5px;">
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo nl2br(htmlspecialchars($card['texto_informativo'])); ?></td>
                                    <td><?php echo htmlspecialchars($card['column_nombre'] ?: 'Sin asignar'); ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-info mb-1" onclick='editCard(<?php echo json_encode($card); ?>)'>Editar</button>
                                        <a href="delete_info_producto.php?id=<?php echo $card['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Estás seguro de que quieres eliminar esta tarjeta?')">Eliminar</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function editCard(card) {
    document.getElementById('info-id').value = card.id;
    document.getElementById('producto_id').value = card.producto_id;
    document.getElementById('texto_informativo').value = card.texto_informativo;
    document.getElementById('column_id').value = card.column_id;
    document.getElementById('current_imagen').value = card.imagen_url;
    
    const imagePreview = document.getElementById('image-preview');
    imagePreview.innerHTML = '';
    if (card.imagen_url) {
        imagePreview.innerHTML = `<p class="mb-1">Imagen actual:</p><img src="${card.imagen_url}?t=${new Date().getTime()}" style="width: 100px; height: auto; border-radius: 5px;"/>`;
    }
    
    // Scroll to the form
    const formCard = document.querySelector('.card');
    formCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function resetForm() {
    document.getElementById('info-id').value = '';
    document.querySelector('form').reset();
    document.getElementById('image-preview').innerHTML = '';
}
</script>

<?php include 'layout_footer.php'; ?>
