<?php
require_once 'config.php';

$pdo = getDBConnection();

// Parametri URL
$page = max(1, (int)($_GET['page'] ?? 1));
$categoria = $_GET['categoria'] ?? '';
$search = $_GET['search'] ?? '';
$slug = $_GET['slug'] ?? '';

$articlesPerPage = 6;
$offset = ($page - 1) * $articlesPerPage;

// Se è richiesto un articolo specifico
if ($slug) {
    $stmt = $pdo->prepare("SELECT * FROM articoli WHERE slug = ? AND stato = 'pubblicato'");
    $stmt->execute([$slug]);
    $article = $stmt->fetch();
    
    if ($article) {
        // Incrementa visualizzazioni
        $updateViews = $pdo->prepare("UPDATE articoli SET visualizzazioni = visualizzazioni + 1 WHERE id = ?");
        $updateViews->execute([$article['id']]);
        
        // Articoli correlati
        $related = $pdo->prepare("SELECT id, titolo, slug, riassunto, data_pubblicazione, immagine 
                                  FROM articoli 
                                  WHERE categoria = ? AND id != ? AND stato = 'pubblicato' 
                                  ORDER BY data_pubblicazione DESC LIMIT 3");
        $related->execute([$article['categoria'], $article['id']]);
        $relatedArticles = $related->fetchAll();
    }
} else {
    // Lista articoli con filtri
    $whereConditions = ["stato = 'pubblicato'"];
    $params = [];
    
    if ($categoria) {
        $whereConditions[] = "categoria = ?";
        $params[] = $categoria;
    }
    
    if ($search) {
        $whereConditions[] = "(titolo LIKE ? OR contenuto LIKE ? OR tags LIKE ?)";
        $searchTerm = "%$search%";
        $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    // Conta totale articoli
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM articoli WHERE $whereClause");
    $countStmt->execute($params);
    $totalArticles = $countStmt->fetchColumn();
    $totalPages = ceil($totalArticles / $articlesPerPage);
    
    // Recupera articoli per la pagina corrente
    $stmt = $pdo->prepare("SELECT * FROM articoli WHERE $whereClause 
                           ORDER BY data_pubblicazione DESC 
                           LIMIT $articlesPerPage OFFSET $offset");
    $stmt->execute($params);
    $articles = $stmt->fetchAll();
    
    // Articoli in evidenza (ultimi 3 pubblicati)
    $featured = $pdo->query("SELECT id, titolo, slug, riassunto, data_pubblicazione, immagine, categoria 
                             FROM articoli WHERE stato = 'pubblicato' 
                             ORDER BY data_pubblicazione DESC LIMIT 3");
    $featuredArticles = $featured->fetchAll();
}

// Funzione per pulire il testo dai problemi di encoding
function cleanText($text) {
    if (empty($text)) return '';
    
    // Decodifica le entità HTML
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    
    return $text;
}

// Funzione per pulire riassunti
function cleanExcerpt($text, $length = 150) {
    if (empty($text)) return '';
    
    // Decodifica entità HTML
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    
    // Rimuovi tag HTML
    $text = strip_tags($text);
    
    // Tronca il testo
    return truncateText($text, $length);
}

// Meta tags per SEO
$pageTitle = $slug ? ($article ? cleanText($article['titolo']) . ' | GMDSS Italia Blog' : 'Articolo non trovato') : 'Blog GMDSS Italia - Certificazioni Marittime';
$metaDescription = $slug ? ($article ? ($article['meta_description'] ? cleanText($article['meta_description']) : cleanExcerpt($article['contenuto'])) : '') : DEFAULT_META_DESCRIPTION;
$metaKeywords = $slug ? ($article ? cleanText($article['meta_keywords']) : '') : DEFAULT_META_KEYWORDS;
?>
<!DOCTYPE html>
<html lang="it">
<head>
    <link rel="shortcut icon" href="/assets/img/favicon.png" type="image/png">
    <link rel="apple-touch-icon" href="/assets/img/favicon.png">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($metaDescription); ?>">
    <meta name="keywords" content="<?php echo htmlspecialchars($metaKeywords); ?>">
    
    <!-- Open Graph -->
    <meta property="og:title" content="<?php echo htmlspecialchars($pageTitle); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
    <meta property="og:type" content="<?php echo $slug ? 'article' : 'website'; ?>">
    <meta property="og:url" content="<?php echo BLOG_URL . ($_SERVER['REQUEST_URI'] ?? ''); ?>">
    
    <?php if ($slug && $article && $article['immagine']): ?>
        <meta property="og:image" content="<?php echo BLOG_URL . '/' . UPLOAD_DIR . $article['immagine']; ?>">
    <?php endif; ?>
    
    <!-- Schema.org markup -->
    <?php if ($slug && $article): ?>
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "<?php echo addslashes(cleanText($article['titolo'])); ?>",
        "description": "<?php echo addslashes($article['riassunto'] ? cleanExcerpt($article['riassunto']) : cleanExcerpt($article['contenuto'])); ?>",
        "author": {
            "@type": "Organization",
            "name": "GMDSS Italia"
        },
        "publisher": {
            "@type": "Organization",
            "name": "GMDSS Italia",
            "url": "<?php echo SITE_URL; ?>"
        },
        "datePublished": "<?php echo date('Y-m-d', strtotime($article['data_pubblicazione'])); ?>",
        "dateModified": "<?php echo date('Y-m-d', strtotime($article['data_modifica'])); ?>"
    }
    </script>
    <?php endif; ?>
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: #f8f9fa;
        }
        
        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 2rem 0;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }
        
        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .nav-breadcrumb {
            background: white;
            padding: 1rem 0;
            border-bottom: 1px solid #e1e5e9;
        }
        
        .nav-breadcrumb .container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .nav-breadcrumb a {
            color: #2a5298;
            text-decoration: none;
        }
        
        .nav-breadcrumb a:hover {
            text-decoration: underline;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 3rem;
            margin: 3rem auto;
        }
        
        .content-area {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .sidebar {
            space-y: 2rem;
        }
        
        .search-box, .category-filter, .featured-posts {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        
        .search-box h3, .category-filter h3, .featured-posts h3 {
            color: #1e3c72;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .search-form {
            display: flex;
            gap: 8px;
        }
        
        .search-form input {
            flex: 1;
            padding: 10px;
            border: 2px solid #e1e5e9;
            border-radius: 5px;
        }
        
        .search-form button {
            padding: 10px 16px;
            background: #2a5298;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .category-list {
            list-style: none;
        }
        
        .category-list li {
            margin-bottom: 8px;
        }
        
        .category-list a {
            color: #333;
            text-decoration: none;
            display: block;
            padding: 8px 12px;
            border-radius: 5px;
            transition: background 0.3s;
        }
        
        .category-list a:hover,
        .category-list a.active {
            background: #f0f7ff;
            color: #2a5298;
        }
        
        .article-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 2rem;
            padding: 2rem;
        }
        
        .article-card {
            border-radius: 10px;
            overflow: hidden;
            transition: transform 0.3s, box-shadow 0.3s;
            background: white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .article-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .article-image {
            height: 200px;
            background: linear-gradient(45deg, #1e3c72, #2a5298);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .article-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .article-content {
            padding: 1.5rem;
        }
        
        .article-meta {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
            font-size: 0.9rem;
            color: #666;
        }
        
        .category-badge {
            background: #e3f2fd;
            color: #1976d2;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .article-title {
            color: #1e3c72;
            font-size: 1.3rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            line-height: 1.4;
        }
        
        .article-title a {
            color: inherit;
            text-decoration: none;
        }
        
        .article-title a:hover {
            color: #2a5298;
        }
        
        .article-excerpt {
            color: #666;
            margin-bottom: 1rem;
            line-height: 1.5;
        }
        
        .read-more {
            color: #2a5298;
            text-decoration: none;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .read-more:hover {
            color: #1e3c72;
        }
        
        /* Articolo singolo */
        .single-article {
            padding: 3rem;
        }
        
        .single-article .article-header {
            text-align: center;
            margin-bottom: 3rem;
            padding-bottom: 2rem;
            border-bottom: 2px solid #f0f7ff;
        }
        
        .single-article .article-title {
            font-size: 2.5rem;
            color: #1e3c72;
            margin-bottom: 1rem;
        }
        
        .single-article .article-subtitle {
            font-size: 1.3rem;
            color: #666;
            margin-bottom: 1.5rem;
        }
        
        .single-article .article-content {
            font-size: 1.1rem;
            line-height: 1.8;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .single-article .article-content h3 {
            color: #1e3c72;
            margin: 2rem 0 1rem 0;
            font-size: 1.5rem;
        }
        
        .single-article .article-content ul,
        .single-article .article-content ol {
            margin: 1rem 0;
            padding-left: 2rem;
        }
        
        .single-article .article-content li {
            margin-bottom: 0.5rem;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            padding: 2rem;
        }
        
        .pagination a,
        .pagination span {
            padding: 10px 16px;
            border: 1px solid #e1e5e9;
            border-radius: 5px;
            text-decoration: none;
            color: #333;
        }
        
        .pagination a:hover {
            background: #f0f7ff;
            color: #2a5298;
        }
        
        .pagination .current {
            background: #2a5298;
            color: white;
            border-color: #2a5298;
        }
        
        .featured-post {
            border-bottom: 1px solid #e1e5e9;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }
        
        .featured-post:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .featured-post h4 {
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }
        
        .featured-post h4 a {
            color: #333;
            text-decoration: none;
        }
        
        .featured-post h4 a:hover {
            color: #2a5298;
        }
        
        .featured-post .meta {
            font-size: 0.8rem;
            color: #666;
        }
        
        .related-articles {
            background: #f8f9fa;
            padding: 2rem;
            margin-top: 3rem;
        }
        
        .related-articles h3 {
            color: #1e3c72;
            margin-bottom: 1.5rem;
            text-align: center;
        }
        
        .related-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
                gap: 2rem;
            }
            
            .article-grid {
                grid-template-columns: 1fr;
                padding: 1rem;
            }
            
            .single-article {
                padding: 1.5rem;
            }
            
            .single-article .article-title {
                font-size: 2rem;
            }
            
            .header h1 {
                font-size: 2rem;
                flex-direction: column;
                gap: 8px;
            }
            
            .container {
                padding: 0 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>
                <i class="fas fa-anchor"></i>
                Universo GMDSS Italia Blog
            </h1>
            <p>Certificazioni Marittime, Aggiornamenti Normativi e Guide Tecniche</p>
        </div>
    </div>
    
    <div class="nav-breadcrumb">
        <div class="container">
            <a href="<?php echo SITE_URL; ?>"><i class="fas fa-home"></i> Home</a>
            <span>→</span>
            <a href="blog.php">Blog</a>
            <?php if ($slug && $article): ?>
                <span>→</span>
                <span><?php echo cleanText($article['titolo']); ?></span>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="container">
        <?php if ($slug): ?>
            <?php if ($article): ?>
                <!-- Articolo singolo -->
                <div class="content-area">
                    <article class="single-article">
                        <div class="article-header">
                            <h1 class="article-title"><?php echo cleanText($article['titolo']); ?></h1>
                            <?php if ($article['sottotitolo']): ?>
                                <p class="article-subtitle"><?php echo cleanText($article['sottotitolo']); ?></p>
                            <?php endif; ?>
                            <div class="article-meta">
                                <span class="category-badge"><?php echo $categories[$article['categoria']] ?? $article['categoria']; ?></span>
                                <span><i class="fas fa-calendar"></i> <?php echo formatItalianDate($article['data_pubblicazione']); ?></span>
                                <span><i class="fas fa-eye"></i> <?php echo $article['visualizzazioni']; ?> visualizzazioni</span>
                            </div>
                        </div>
                        
                        <?php if ($article['immagine']): ?>
                            <div class="article-image" style="height: 300px; margin-bottom: 2rem;">
                                <img src="<?php echo UPLOAD_DIR . $article['immagine']; ?>" 
                                     alt="<?php echo cleanText($article['titolo']); ?>">
                            </div>
                        <?php endif; ?>
                        
                        <div class="article-content">
                            <?php echo html_entity_decode($article['contenuto'], ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                        
                        <?php if ($article['tags']): ?>
                            <div style="margin-top: 2rem; padding-top: 2rem; border-top: 1px solid #e1e5e9;">
                                <strong>Tags:</strong>
                                <?php
                                $tags = explode(',', $article['tags']);
                                foreach ($tags as $tag):
                                    $tag = trim($tag);
                                ?>
                                    <span style="background: #e3f2fd; color: #1976d2; padding: 4px 8px; border-radius: 12px; font-size: 0.8rem; margin-right: 8px;"><?php echo cleanText($tag); ?></span>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </article>
                    
                    <?php if ($relatedArticles): ?>
                        <div class="related-articles">
                            <h3>Articoli Correlati</h3>
                            <div class="related-grid">
                                <?php foreach ($relatedArticles as $related): ?>
                                    <div class="article-card">
                                        <div class="article-image">
                                            <?php if ($related['immagine']): ?>
                                                <img src="<?php echo UPLOAD_DIR . $related['immagine']; ?>" 
                                                     alt="<?php echo cleanText($related['titolo']); ?>">
                                            <?php else: ?>
                                                <i class="fas fa-ship"></i>
                                            <?php endif; ?>
                                        </div>
                                        <div class="article-content">
                                            <h4 class="article-title">
                                                <a href="blog.php?slug=<?php echo $related['slug']; ?>">
                                                    <?php echo cleanText($related['titolo']); ?>
                                                </a>
                                            </h4>
                                            <p class="article-excerpt">
                                                <?php echo cleanExcerpt($related['riassunto'] ?: $related['contenuto']); ?>
                                            </p>
                                            <a href="blog.php?slug=<?php echo $related['slug']; ?>" class="read-more">
                                                Leggi tutto <i class="fas fa-arrow-right"></i>
                                            </a>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="content-area">
                    <div style="padding: 3rem; text-align: center;">
                        <h1>Articolo non trovato</h1>
                        <p>L'articolo richiesto non esiste o non è più disponibile.</p>
                        <a href="blog.php" class="read-more">← Torna al blog</a>
                    </div>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <!-- Lista articoli -->
            <div class="main-content">
                <div class="content-area">
                    <?php if ($articles): ?>
                        <div class="article-grid">
                            <?php foreach ($articles as $article): ?>
                                <article class="article-card">
                                    <div class="article-image">
                                        <?php if ($article['immagine']): ?>
                                            <img src="<?php echo UPLOAD_DIR . $article['immagine']; ?>" 
                                                 alt="<?php echo cleanText($article['titolo']); ?>">
                                        <?php else: ?>
                                            <i class="fas fa-ship"></i>
                                        <?php endif; ?>
                                    </div>
                                    <div class="article-content">
                                        <div class="article-meta">
                                            <span class="category-badge"><?php echo $categories[$article['categoria']] ?? $article['categoria']; ?></span>
                                            <span><i class="fas fa-calendar"></i> <?php echo formatItalianDate($article['data_pubblicazione']); ?></span>
                                        </div>
                                        <h2 class="article-title">
                                            <a href="blog.php?slug=<?php echo $article['slug']; ?>">
                                                <?php echo cleanText($article['titolo']); ?>
                                            </a>
                                        </h2>
                                        <?php if ($article['sottotitolo']): ?>
                                            <p style="color: #666; font-style: italic; margin-bottom: 1rem;">
                                                <?php echo cleanText($article['sottotitolo']); ?>
                                            </p>
                                        <?php endif; ?>
                                        <p class="article-excerpt">
                                            <?php echo cleanExcerpt($article['riassunto'] ?: $article['contenuto']); ?>
                                        </p>
                                        <a href="blog.php?slug=<?php echo $article['slug']; ?>" class="read-more">
                                            Leggi tutto <i class="fas fa-arrow-right"></i>
                                        </a>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                        
                        <?php if ($totalPages > 1): ?>
                            <div class="pagination">
                                <?php if ($page > 1): ?>
                                    <a href="?page=<?php echo $page - 1; ?><?php echo $categoria ? "&categoria=$categoria" : ''; ?><?php echo $search ? "&search=" . urlencode($search) : ''; ?>">
                                        <i class="fas fa-chevron-left"></i> Precedente
                                    </a>
                                <?php endif; ?>
                                
                                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                    <?php if ($i == $page): ?>
                                        <span class="current"><?php echo $i; ?></span>
                                    <?php else: ?>
                                        <a href="?page=<?php echo $i; ?><?php echo $categoria ? "&categoria=$categoria" : ''; ?><?php echo $search ? "&search=" . urlencode($search) : ''; ?>">
                                            <?php echo $i; ?>
                                        </a>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <?php if ($page < $totalPages): ?>
                                    <a href="?page=<?php echo $page + 1; ?><?php echo $categoria ? "&categoria=$categoria" : ''; ?><?php echo $search ? "&search=" . urlencode($search) : ''; ?>">
                                        Successiva <i class="fas fa-chevron-right"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div style="padding: 3rem; text-align: center;">
                            <h2>Nessun articolo trovato</h2>
                            <p>Non ci sono articoli che corrispondono ai criteri di ricerca.</p>
                            <a href="blog.php" class="read-more">← Visualizza tutti gli articoli</a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <aside class="sidebar">
                    <!-- Ricerca -->
                    <div class="search-box">
                        <h3><i class="fas fa-search"></i> Cerca Articoli</h3>
                        <form class="search-form" method="GET">
                            <input type="text" name="search" placeholder="Cerca nel blog..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit"><i class="fas fa-search"></i></button>
                        </form>
                    </div>
                    
                    <!-- Filtro categorie -->
                    <div class="category-filter">
                        <h3><i class="fas fa-tags"></i> Categorie</h3>
                        <ul class="category-list">
                            <li><a href="blog.php" <?php echo !$categoria ? 'class="active"' : ''; ?>>Tutte le categorie</a></li>
                            <?php foreach ($categories as $key => $value): ?>
                                <li>
                                    <a href="blog.php?categoria=<?php echo $key; ?>" 
                                       <?php echo $categoria === $key ? 'class="active"' : ''; ?>>
                                        <?php echo $value; ?>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    
                    <!-- Articoli in evidenza -->
                    <?php if ($featuredArticles): ?>
                        <div class="featured-posts">
                            <h3><i class="fas fa-star"></i> Articoli in Evidenza</h3>
                            <?php foreach ($featuredArticles as $featured): ?>
                                <div class="featured-post">
                                    <h4>
                                        <a href="blog.php?slug=<?php echo $featured['slug']; ?>">
                                            <?php echo cleanText($featured['titolo']); ?>
                                        </a>
                                    </h4>
                                    <div class="meta">
                                        <span class="category-badge"><?php echo $categories[$featured['categoria']] ?? $featured['categoria']; ?></span>
                                        <br>
                                        <small><?php echo formatItalianDate($featured['data_pubblicazione']); ?></small>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </aside>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>