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

function buildBlogImageUrl($url)
{
    $url = trim((string) $url);
    if ($url === '') {
        return '';
    }
    if (preg_match('~^(?:f|ht)tps?://~i', $url) || strpos($url, '//') === 0) {
        return $url;
    }
    return '/' . ltrim($url, '/');
}

$blogs = [];
if ($pdo) {
    try {
        $stmt = $pdo->query("SELECT * FROM blogs WHERE esta_publicado = 1 ORDER BY fecha_publicacion DESC");
        $blogs = $stmt->fetchAll();
    } catch (PDOException $e) {
        $error = "Error al obtener blogs: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <?php
    $pageTitle = "Blog Técnico - Servicio Técnico de PC";
    $pageDescription = "Consejos expertos, guías de reparación y las últimas noticias sobre tecnología y mantenimiento de computadoras en nuestro Blog Técnico.";
    include 'includes/head.php';
    ?>
</head>

<body>
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-K43KQM6J" height="0" width="0"
            style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
    <?php include 'includes/nav.php'; ?>

    <header class="blog-header fade-in-up">
        <div class="container">
            <h1 class="display-4 fw-bold">Blog Técnico</h1>
            <p class="lead text-secondary">Consejos, noticias y novedades sobre tecnología y reparación de PC.</p>
        </div>
    </header>

    <main class="container py-5">
        <?php if (empty($blogs)): ?>
            <div class="text-center py-5">
                <i class="fas fa-newspaper fa-4x mb-4 text-secondary opacity-25"></i>
                <h3>Próximamente más contenido</h3>
                <p class="text-secondary">Estamos preparando artículos muy interesantes para ti.</p>
                <a href="/index.php" class="btn btn-outline-primary mt-3">Volver al inicio</a>
            </div>
            <?php
        else: ?>
            <div class="row g-4">
                <?php foreach ($blogs as $b): ?>
                    <div class="col-md-6 col-lg-4 fade-in-up">
                        <article class="blog-card">
                            <div class="blog-card-media">
                                <?php if (!empty($b['imagen_url'])):
                                    $img_url = buildBlogImageUrl($b['imagen_url']);
                                    ?>
                                    <img src="<?php echo htmlspecialchars($img_url); ?>"
                                        alt="<?php echo htmlspecialchars($b['titulo']); ?>" class="blog-card-img">
                                    <?php
                                else: ?>
                                    <div
                                        class="blog-card-img blog-card-placeholder d-flex align-items-center justify-content-center bg-dark">
                                        <i class="fas fa-image fa-3x text-secondary opacity-25"></i>
                                    </div>
                                    <?php
                                endif; ?>
                                <span class="blog-card-badge" title="Temática / Etiqueta">
                                    <?php echo htmlspecialchars(!empty($b['tema']) ? $b['tema'] : 'Blog'); ?>
                                </span>
                            </div>
                            <div class="blog-card-body">
                                <div class="blog-date">
                                    <i class="far fa-calendar-alt me-2"></i>
                                    <?php echo date('d M, Y', strtotime($b['fecha_publicacion'])); ?>
                                </div>
                                <h2 class="blog-title">
                                    <?php echo htmlspecialchars($b['titulo']); ?>
                                </h2>
                                <p class="blog-resumen">
                                    <?php echo htmlspecialchars($b['resumen'] ?: mb_strimwidth(strip_tags($b['contenido']), 0, 120, "...")); ?>
                                </p>
                                <div class="mt-auto">
                                    <a href="/blog/<?php echo htmlspecialchars($b['slug']); ?>" class="btn-read-more">
                                        Leer más <i class="fas fa-arrow-right"></i>
                                    </a>
                                </div>
                            </div>
                        </article>
                    </div>
                    <?php
                endforeach; ?>
            </div>
            <?php
        endif; ?>
    </main>

    <script>
        // Intersection Observer for scroll animations
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                }
            });
        }, observerOptions);

        document.querySelectorAll('.fade-in-up').forEach(el => observer.observe(el));
    </script>
    <?php include 'includes/footer.php'; ?>
</body>

</html>