<?php
// ==================== SESSION AND AUTHENTICATION ====================
session_start();

if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit;
}

require '../src/db.php';

// ==================== DATA FETCHING ====================
$userId = $_SESSION['user']['id'];

// Get chat history
$stmt = $pdo->prepare("SELECT * FROM mensajes WHERE usuario_id = ? ORDER BY fecha ASC");
$stmt->execute([$userId]);
$chatHistory = $stmt->fetchAll();

// Get books with categories for management
$manageBooks = $pdo
    ->query("SELECT l.id, l.titulo, l.autor, l.categoria_id, l.descripcion, c.nombre AS categoria
             FROM libros l
             JOIN categorias c ON c.id = l.categoria_id")
    ->fetchAll();

// Get user notes
$stmtNotes = $pdo->prepare("
    SELECT id, contenido, color 
    FROM anotaciones 
    WHERE usuario_id = ? 
    ORDER BY fecha DESC
");
$stmtNotes->execute([$userId]);
$notes = $stmtNotes->fetchAll();

// Get all books for display
$books = $pdo->query("
    SELECT l.*, c.nombre AS categoria
    FROM libros l
    JOIN categorias c ON c.id = l.categoria_id
")->fetchAll();

// Get categories for forms
$cats = $pdo->query("SELECT * FROM categorias")->fetchAll();

// ==================== FLASH MESSAGES & ACTIVE TAB ====================
$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);

$activeTab = $_GET['tab'] ?? 'books';

// 🗂️ 1. Cargar publicaciones con el autor - FIXED: Include all necessary columns
$posts = $pdo->query("
  SELECT p.*, u.email AS autor
  FROM publicaciones p
  JOIN usuarios u ON u.id = p.usuario_id
  ORDER BY p.fecha DESC
")->fetchAll();

// 💬 2. Adjuntar comentarios por publicación
foreach ($posts as &$p) {
  $stmt = $pdo->prepare("
    SELECT c.texto, u.email AS autor
    FROM comentarios_post c
    JOIN usuarios u ON u.id = c.usuario_id
    WHERE c.post_id = ?
    ORDER BY c.fecha ASC
  ");
  $stmt->execute([$p['id']]);
  $p['comentarios'] = $stmt->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Dashboard | Biblioteca Virtual</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>
    <div class="dashboard-container d-flex">
        
        <!-- ==================== SIDEBAR ==================== -->
        <aside class="sidebar d-flex flex-column justify-content-between">
            <!-- Menú superior -->
            <div>
                <h4 class="text-center mt-3">📚 Biblioteca</h4>
                <nav class="nav flex-column mt-4">
                <a class="nav-link" href="#" onclick="showSection('books')"><i class="fas fa-book-open me-2"></i>Mi Biblioteca</a>
                <a class="nav-link" href="#" onclick="showSection('feed')"><i class="fas fa-newspaper me-2"></i>Publicaciones</a>
                <a class="nav-link" href="#" onclick="showSection('manage')"><i class="fas fa-clock me-2"></i>Libros Recientes</a>
                <a class="nav-link" href="#" onclick="showSection('notes')"><i class="fas fa-sticky-note me-2"></i>Anotaciones</a>
                <a class="nav-link" href="#" onclick="showSection('chat')"><i class="fas fa-robot me-2"></i>Asistente Kayros</a>
                </nav>
            </div>

            <!-- Bloque inferior anclado -->
            <div class="mt-auto pt-3 border-top text-center">
                <nav class="nav flex-column">                
                </nav>
                <div class="user-email small text-muted mt-2">
                    <i class="fas fa-user me-1"></i>
                <?= htmlspecialchars($_SESSION['user']['email'] ?? '') ?>
                <p style="text-align: left;padding-left: 1em;color: #0e9f12;font-size: 0.9em;">Usuario activo</p>
                </div>
                <a class="nav-link text-muted config" href="profile.php"><i class="fas fa-cog me-2"></i>Configuración</a>
                <a class="nav-link text-danger config" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Cerrar Sesión</a>
            </div>
        </aside>

        <!-- ==================== MAIN CONTENT AREA ==================== -->
        <main class="content-area flex-grow-1">
            
            <!-- Flash Messages -->
            <?php if ($flash): ?>
                <div class="container mt-3">
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?= htmlspecialchars($flash) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </div>
            <?php endif; ?>

            <div class="container py-4">
                
                <!-- ==================== BOOKS SECTION ==================== -->
                <section id="section-books" class="section-dashboard">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2>Libros</h2>
                    </div>

                    <div class="input-group mb-4 w-100">
                        <span class="input-group-text">🔍</span>
                        <input type="text" id="search-input" class="form-control" 
                               placeholder="Buscar por título o autor…" onkeyup="filterBooks()">
                    </div>

                    <div class="row g-3" id="books-container">
                        <?php foreach ($books as $book): ?>
                            <div class="col-sm-6 col-md-4 col-lg-3">
                                <div class="card h-100">
                                    <img src="uploads/portadas/<?= htmlspecialchars($book['portada']) ?>" 
                                         class="card-img-top" alt="Portada">
                                    <div class="card-body d-flex flex-column p-2">
                                        <h6 class="card-title"><?= htmlspecialchars($book['titulo']) ?></h6>
                                        <p class="card-text mb-1">
                                            <small class="text-muted"><?= htmlspecialchars($book['autor']) ?></small>
                                        </p>
                                        <span class="badge bg-secondary mb-2">
                                            <?= htmlspecialchars($book['categoria']) ?>
                                        </span>
                                        <a href="uploads/pdfs/<?= htmlspecialchars($book['archivo']) ?>" 
                                           target="_blank" class="mt-auto btn btn-sm btn-outline-primary">
                                            Ver PDF
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>

                <!-- ==================== NOTES SECTION ==================== -->
                <section id="section-notes" class="section-dashboard" style="display:none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2>Anotaciones</h2>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addNoteModal">
                            + Agregar Nota
                        </button>
                    </div>

                    <div id="notes-container" class="d-flex flex-wrap gap-3">
                        <?php foreach($notes as $note): ?>
                            <div class="note-card" style="background: <?= htmlspecialchars($note['color']) ?>;">
                                <div class="note-actions">
                                    <button class="btn btn-sm btn-light edit-note-btn"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editNoteModal"
                                            data-note-id="<?= $note['id'] ?>"
                                            data-note-content="<?= htmlspecialchars($note['contenido'], ENT_QUOTES) ?>"
                                            data-note-color="<?= htmlspecialchars($note['color']) ?>">
                                        ✏️
                                    </button>
                                    <a href="delete_note.php?id=<?= $note['id'] ?>&tab=notes"
                                       class="btn btn-sm btn-light"
                                       onclick="return confirm('¿Eliminar nota?')">
                                        🗑️
                                    </a>
                                </div>
                                <div class="note-content">
                                    <?= nl2br(htmlspecialchars($note['contenido'])) ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>

                <!-- ==================== CHAT SECTION ==================== -->
                <section id="section-chat" class="section-dashboard" style="display:none;">
                    <h2>Asistente Virtual</h2>
                    <div id="chat-box">
                        <?php foreach($chatHistory as $message): 
                            $mensaje_limpio = strip_tags($message['mensaje'], '<br><br/>');
                            $mensaje_final = nl2br($mensaje_limpio);
                        ?>
                            <div class="message <?= $message['tipo'] === 'usuario' ? 'user' : 'bot' ?>">
                                <div class="message-content"><?= $mensaje_final ?></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <textarea id="user-input" class="form-control mb-2" 
                              placeholder="Escribe tu pregunta…" 
                              style="resize:none; height:80px"></textarea>
                    <button id="send-btn" class="btn btn-primary" onclick="enviarMensaje()">
                        Enviar
                    </button>
                </section>

                <!-- ==================== MANAGE BOOKS SECTION ==================== -->
                <section id="section-manage" class="section-dashboard" style="display:none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2>Gestionar Libros</h2>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addBookModal">
                            + Agregar Libro
                        </button>
                    </div>

                    <div class="input-group mb-3 w-100">
                        <span class="input-group-text">🔍</span>
                        <input type="text" id="search-manage" class="form-control" 
                               placeholder="Buscar título o autor…" onkeyup="filterManage()">
                    </div>

                    <div class="table-responsive">
                        <table class="table table-striped align-middle">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Título</th>
                                    <th>Autor</th>
                                    <th>Categoría</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody id="manage-table-body">
                                <?php foreach ($manageBooks as $manageBook): ?>
                                    <tr data-id="<?= $manageBook['id'] ?>"
                                        data-titulo="<?= htmlspecialchars($manageBook['titulo'], ENT_QUOTES) ?>"
                                        data-autor="<?= htmlspecialchars($manageBook['autor'], ENT_QUOTES) ?>"
                                        data-categoria="<?= $manageBook['categoria_id'] ?>"
                                        data-descripcion="<?= htmlspecialchars($manageBook['descripcion'] ?? '', ENT_QUOTES) ?>">
                                        
                                        <td><?= $manageBook['id'] ?></td>
                                        <td><?= htmlspecialchars($manageBook['titulo']) ?></td>
                                        <td><?= htmlspecialchars($manageBook['autor']) ?></td>
                                        <td><?= htmlspecialchars($manageBook['categoria']) ?></td>
                                        <td>
                                            <button class="btn btn-sm btn-warning" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#editBookModal" 
                                                    onclick="fillEditModal(this.closest('tr'))">
                                                Editar
                                            </button>
                                            <a href="delete_book.php?id=<?= $manageBook['id'] ?>&tab=manage" 
                                               class="btn btn-sm btn-danger" 
                                               onclick="return confirm('¿Borrar libro <?= htmlspecialchars($manageBook['titulo']) ?>?')">
                                                Eliminar
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
                <!-- Reemplaza la sección de publicaciones en tu dashboard.php -->
                <section id="section-feed" class="section-dashboard" style="display:none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-newspaper me-2"></i> Publicaciones</h2>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createPostModal">
                            + Nueva Publicación
                        </button>
                    </div>

                    <!-- Listado de publicaciones -->
                    <div id="post-feed" class="d-flex flex-column gap-4">
                        <?php foreach ($posts as $p): ?>
                        <div class="card post-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <strong><?= htmlspecialchars($p['autor']) ?></strong>
                                    <small class="text-muted"><?= date('d M Y H:i', strtotime($p['fecha'])) ?></small>
                                </div>
                                <p class="mt-2" style="text-align: justify;"><?= nl2br(htmlspecialchars($p['texto'])) ?></p>

                                <?php if (!empty($p['media'])): ?>
                                    <?php 
                                    // Determinar tipo por extensión si no está definido
                                    $extension = strtolower(pathinfo($p['media'], PATHINFO_EXTENSION));
                                    $esImagen = in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp']);
                                    $esVideo = in_array($extension, ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm']);
                                    ?>
                                    
                                    <?php if ($esImagen): ?>
                                        <div class="mt-2"  style="text-align: center;">
                                            <img src="uploads/posts/<?= htmlspecialchars($p['media']) ?>" 
                                                class="img-fluid rounded" 
                                                alt="Imagen de publicación"
                                                style="max-height: 500px; object-fit: contain;">
                                        </div>
                                    <?php elseif ($esVideo): ?>
                                        <div class="mt-2">
                                            <video controls class="w-100 rounded" style="max-height: 400px;">
                                                <source src="uploads/posts/<?= htmlspecialchars($p['media']) ?>" type="video/<?= $extension ?>">
                                                Tu navegador no soporta el elemento de video.
                                            </video>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <div class="mt-3 d-flex justify-content-between align-items-center">
                                    <button class="btn btn-sm btn-outline-primary" onclick="likePost(<?= $p['id'] ?>)">
                                        <i class="fas fa-thumbs-up me-1"></i> <?= $p['likes'] ?> Me gusta
                                    </button>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="toggleComments(<?= $p['id'] ?>)">
                                        <i class="fas fa-comment-alt me-1"></i> Comentarios (<?= count($p['comentarios']) ?>)
                                    </button>
                                </div>

                                <div id="comments-<?= $p['id'] ?>" class="comments mt-3" style="display:none;">
                                    <?php foreach ($p['comentarios'] as $c): ?>
                                    <div class="border-bottom py-1">
                                        <strong><?= htmlspecialchars($c['autor']) ?>:</strong>
                                        <span><?= htmlspecialchars($c['texto']) ?></span>
                                    </div>
                                    <?php endforeach; ?>

                                    <form class="mt-2" onsubmit="commentPost(event, <?= $p['id'] ?>)">
                                        <input type="text" name="comentario" class="form-control" placeholder="Escribe un comentario..." required>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </section>                        
            </div>
        </main>
    </div>

    <!-- ==================== MODALS ==================== -->
    <!-- add publicacion-->
     <div class="modal fade" id="createPostModal" tabindex="-1">
        <div class="modal-dialog">
            <form class="modal-content" method="POST" action="post_guardar.php" enctype="multipart/form-data">
            <div class="modal-header">
                <h5 class="modal-title">Nueva Publicación</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <textarea name="texto" class="form-control mb-3" placeholder="¿Qué estás pensando?" required></textarea>
                <input type="file" name="media" accept="image/*,video/*" class="form-control">
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Publicar</button>
            </div>
            </form>
        </div>
    </div>
            <!-- Add Book Modal -->
    <div class="modal fade" id="addBookModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form action="add_book.php" method="post" enctype="multipart/form-data" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Agregar Nuevo Libro</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Título *</label>
                        <input type="text" name="titulo" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Autor *</label>
                        <input type="text" name="autor" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Categoría *</label>
                        <select name="categoria" class="form-select" required>
                            <option value="">-- Selecciona --</option>
                            <?php foreach($cats as $category): ?>
                                <option value="<?= $category['id'] ?>">
                                    <?= htmlspecialchars($category['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Descripción</label>
                        <textarea name="descripcion" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Archivo PDF *</label>
                        <input type="file" name="pdf" accept="application/pdf" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Portada *</label>
                        <input type="file" name="portada" accept="image/*" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Book Modal -->
    <div class="modal fade" id="editBookModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form action="edit_book.php?tab=manage" method="post" enctype="multipart/form-data" class="modal-content">
                <input type="hidden" name="id" id="edit-id">
                <div class="modal-header">
                    <h5 class="modal-title">Editar Libro</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Título *</label>
                        <input type="text" name="titulo" id="edit-titulo" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Autor *</label>
                        <input type="text" name="autor" id="edit-autor" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Categoría *</label>
                        <select name="categoria" id="edit-categoria" class="form-select" required>
                            <option value="">-- Selecciona --</option>
                            <?php foreach($cats as $category): ?>
                                <option value="<?= $category['id'] ?>">
                                    <?= htmlspecialchars($category['nombre']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Descripción</label>
                        <textarea name="descripcion" id="edit-descripcion" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reemplazar PDF</label>
                        <input type="file" name="pdf" accept="application/pdf" class="form-control">
                        <small class="text-muted">Dejar en blanco para conservar el actual.</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reemplazar Portada</label>
                        <input type="file" name="portada" accept="image/*" class="form-control">
                        <small class="text-muted">Dejar en blanco para conservar la actual.</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Actualizar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Note Modal -->
    <div class="modal fade" id="addNoteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form action="add_note.php?tab=notes" method="post" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Agregar Nota</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Contenido</label>
                        <textarea name="contenido" class="form-control" rows="4" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Color</label>
                        <input type="color" name="color" class="form-control form-control-color" value="#fef68a">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar Nota</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Note Modal -->
    <div class="modal fade" id="editNoteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form action="edit_note.php?tab=notes" method="post" class="modal-content">
                <input type="hidden" name="id" id="edit-note-id">
                <div class="modal-header">
                    <h5 class="modal-title">Editar Nota</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Contenido</label>
                        <textarea name="contenido" id="edit-note-content" class="form-control" rows="4" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Color</label>
                        <input type="color" name="color" id="edit-note-color" class="form-control form-control-color">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Actualizar Nota</button>
                </div>
            </form>
        </div>
    </div>

    <!-- ==================== SCRIPTS ==================== -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // ==================== SECTION NAVIGATION ====================
        // Reemplaza la función showSection en tu dashboard.php
function showSection(sec) {
    // Ocultar todas las secciones
    ['books', 'notes', 'chat', 'manage', 'feed'].forEach(s => {
        const section = document.getElementById('section-' + s);
        if (section) {
            section.style.display = (s === sec ? 'block' : 'none');
        }
    });
    
    // Actualizar la URL sin recargar la página
    const newUrl = new URL(window.location);
    newUrl.searchParams.set('tab', sec);
    window.history.replaceState({}, '', newUrl);
    
    // Actualizar clases activas en el menú
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // Marcar como activo el enlace correspondiente
    const activeLink = document.querySelector(`[onclick="showSection('${sec}')"]`);
    if (activeLink) {
        activeLink.classList.add('active');
    }
}

// También actualiza los enlaces del sidebar para usar esta función
// Reemplaza los enlaces en el sidebar con estos:
document.addEventListener('DOMContentLoaded', function() {
    // Configurar enlaces del sidebar
    const sidebarLinks = {
        'books': document.querySelector('[onclick="showSection(\'books\')"]'),
        'feed': document.querySelector('[onclick="showSection(\'feed\')"]'),
        'manage': document.querySelector('[onclick="showSection(\'manage\')"]'),
        'notes': document.querySelector('[onclick="showSection(\'notes\')"]'),
        'chat': document.querySelector('[onclick="showSection(\'chat\')"]')
    };
    
    // Obtener tab activo de la URL
    const urlParams = new URLSearchParams(window.location.search);
    const activeTab = urlParams.get('tab') || 'books';
    
    // Mostrar la sección activa
    showSection(activeTab);
});

// Función mejorada para el modal de publicaciones
document.getElementById('createPostModal')?.addEventListener('hidden.bs.modal', function () {
    // Limpiar el formulario cuando se cierre el modal
    const form = this.querySelector('form');
    if (form) {
        form.reset();
    }
});

// Interceptar el envío del formulario para mantener la sección activa
document.querySelector('#createPostModal form')?.addEventListener('submit', function() {
    // El formulario se enviará normalmente, pero post_guardar.php ya redirige a tab=feed
    console.log('Enviando nueva publicación...');
});

        // ==================== SEARCH FUNCTIONS ====================
        function filterBooks() {
            const query = document.getElementById('search-input').value.toLowerCase();
            const cards = document.querySelectorAll('#books-container .card');

            cards.forEach(card => {
                const titulo = card.querySelector('.card-title')?.textContent.toLowerCase() || '';
                const autor = card.querySelector('.card-text')?.textContent.toLowerCase() || '';
                
                if (titulo.includes(query) || autor.includes(query)) {
                    card.closest('.col-sm-6').style.display = '';
                } else {
                    card.closest('.col-sm-6').style.display = 'none';
                }
            });
        }

        function filterManage() {
            const query = document.getElementById('search-manage').value.toLowerCase();
            
            document.querySelectorAll('#manage-table-body tr').forEach(row => {
                row.style.display = row.innerText.toLowerCase().includes(query) ? '' : 'none';
            });
        }

        // ==================== MODAL FUNCTIONS ====================
        function fillEditModal(row) {
            const id = row.dataset.id;
            const titulo = row.dataset.titulo;
            const autor = row.dataset.autor;
            const categoria = row.dataset.categoria;
            const descripcion = row.dataset.descripcion;

            document.getElementById('edit-id').value = id;
            document.getElementById('edit-titulo').value = titulo;
            document.getElementById('edit-autor').value = autor;
            document.getElementById('edit-categoria').value = categoria;
            document.getElementById('edit-descripcion').value = descripcion;
        }

        // Handle note editing using event delegation
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('edit-note-btn')) {
                const noteId = e.target.getAttribute('data-note-id');
                const noteContent = e.target.getAttribute('data-note-content');
                const noteColor = e.target.getAttribute('data-note-color');
                
                document.getElementById('edit-note-id').value = noteId;
                document.getElementById('edit-note-content').value = noteContent;
                document.getElementById('edit-note-color').value = noteColor;
            }
        });

        // ==================== INITIALIZATION ====================
        document.addEventListener('DOMContentLoaded', function() {
            showSection('<?= $activeTab ?>');
        });
        // publicaciones
            // ==================== POSTS FUNCTIONS ====================

function likePost(postId) {
    fetch('like_post.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'post_id=' + postId
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Actualizar el contador de likes en la interfaz
            const likeButton = document.querySelector(`button[onclick="likePost(${postId})"]`);
            if (likeButton) {
                const icon = likeButton.querySelector('i');
                const text = likeButton.childNodes[2]; // El texto después del icono
                
                // Actualizar el texto del botón
                likeButton.innerHTML = `<i class="fas fa-thumbs-up me-1"></i> ${data.likes} Me gusta`;
                
                // Cambiar el estilo del botón según si está liked o no
                if (data.action === 'liked') {
                    likeButton.classList.remove('btn-outline-primary');
                    likeButton.classList.add('btn-primary');
                } else {
                    likeButton.classList.remove('btn-primary');
                    likeButton.classList.add('btn-outline-primary');
                }
            }
        } else {
            console.error('Error:', data.error);
            alert('Error al procesar el like');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error de conexión');
    });
}

function toggleComments(postId) {
    const comments = document.getElementById('comments-' + postId);
    if (comments) {
        comments.style.display = comments.style.display === 'none' ? 'block' : 'none';
    }
}

function commentPost(event, postId) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);
    formData.append('post_id', postId);
    
    const comentarioInput = form.querySelector('input[name="comentario"]');
    const comentario = comentarioInput.value.trim();
    
    if (!comentario) {
        alert('Por favor escribe un comentario');
        return;
    }
    
    fetch('add_comment.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Limpiar el input
            comentarioInput.value = '';
            
            // Agregar el nuevo comentario a la lista
            const commentsContainer = document.getElementById('comments-' + postId);
            const newCommentHtml = `
                <div class="border-bottom py-1">
                    <strong>${escapeHtml(data.comment.autor)}:</strong>
                    <span>${escapeHtml(data.comment.texto)}</span>
                </div>
            `;
            
            // Insertar antes del formulario
            const form = commentsContainer.querySelector('form');
            form.insertAdjacentHTML('beforebegin', newCommentHtml);
            
            // Actualizar contador de comentarios
            const commentButton = document.querySelector(`button[onclick="toggleComments(${postId})"]`);
            if (commentButton) {
                const currentCount = commentButton.textContent.match(/\d+/);
                const newCount = currentCount ? parseInt(currentCount[0]) + 1 : 1;
                commentButton.innerHTML = `<i class="fas fa-comment-alt me-1"></i> Comentarios (${newCount})`;
            }
        } else {
            console.error('Error:', data.error);
            alert('Error al agregar comentario: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error de conexión');
    });
}

// Función auxiliar para escapar HTML
function escapeHtml(text) {
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
    </script>
    
    <script src="chat.js"></script>
</body>
</html>