<?php
session_start();
$page_title = "Wiki Oficial";

// --- INICIALIZAÇÃO DA CONEXÃO PDO ---
try {
    // AJUSTE ESTAS CREDENCIAIS PARA AS SUAS (localhost, pokemonteste, root, '')
    $host = 'localhost';
    $dbname = 'pokemonteste';
    $user = 'root';
    $password = ''; 
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Erro de conexão com o banco de dados: " . $e->getMessage());
}
// ----------------------------------------------------


// --- CONFIGURAÇÃO DE ROTA ---
$viewCategory = $_GET['cat'] ?? null;
$viewArticle = $_GET['article'] ?? null;
$searchQuery = $_GET['search'] ?? null;

// --- FUNÇÕES DE BUSCA ---

// Busca todas as categorias
$categories = $pdo->query("SELECT * FROM wiki_categories ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);

$currentCategory = null;
$articlesList = [];
$article = null;

// Se um artigo específico for solicitado
if ($viewArticle) {
    $stmt = $pdo->prepare("
        SELECT a.*, c.name as category_name, c.slug as category_slug 
        FROM wiki_articles a 
        JOIN wiki_categories c ON a.category_id = c.id
        WHERE a.slug = ?
    ");
    $stmt->execute([$viewArticle]);
    $article = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($article) {
        // Atualiza views (correto)
        $pdo->prepare("UPDATE wiki_articles SET views = views + 1 WHERE id = ?")->execute([$article['id']]);
        $page_title = htmlspecialchars($article['title']) . " | Wiki";
    }
} 
// Se uma categoria for solicitada
elseif ($viewCategory) {
    $stmtCat = $pdo->prepare("SELECT id, name, description, slug FROM wiki_categories WHERE slug = ?");
    $stmtCat->execute([$viewCategory]);
    $currentCategory = $stmtCat->fetch(PDO::FETCH_ASSOC);

    if ($currentCategory) {
        // Seleciona as colunas necessárias para a lista (correto)
        $stmtArticles = $pdo->prepare("SELECT id, title, slug, tags, updated_at FROM wiki_articles WHERE category_id = ? ORDER BY title ASC");
        $stmtArticles->execute([$currentCategory['id']]);
        $articlesList = $stmtArticles->fetchAll(PDO::FETCH_ASSOC);
        $page_title = htmlspecialchars($currentCategory['name']) . " | Wiki";
    }
}
// Se uma pesquisa for realizada
elseif ($searchQuery) {
    $search = '%' . $searchQuery . '%';
    $stmtArticles = $pdo->prepare("
        SELECT a.id, a.title, a.slug, a.tags, c.name as category_name, a.updated_at
        FROM wiki_articles a
        JOIN wiki_categories c ON a.category_id = c.id
        WHERE a.title LIKE ? OR a.content LIKE ? OR a.tags LIKE ?
        ORDER BY a.title ASC
    ");
    $stmtArticles->execute([$search, $search, $search]);
    $articlesList = $stmtArticles->fetchAll(PDO::FETCH_ASSOC);
    $page_title = "Resultados da Pesquisa | Wiki";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700;900&family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    
    <style>
        /* 🎨 VARIÁVEIS TEMA POKÉMON/TIBIA */
        :root {
            --poke-blue: #3b4cca; /* Azul Principal */
            --poke-yellow: #ffcb05; /* Amarelo Destaque */
            --poke-red: #cc0000; /* Vermelho Ação/Alerta */
            --tibia-stone: #4e4e4e; /* Cinza de fundo (pedra) */
            --wiki-bg: #e9e9e9; /* Fundo Leve */
            --sidebar-bg: #f8f9fa; /* Fundo da Sidebar */
            --main-bg: #ffffff; /* Fundo do Conteúdo */
            --border-color: #ced4da;
            --header-gradient: linear-gradient(90deg, #cc0000, #ffcb05, #cc0000); /* Gradiente de Título */
        }

        body {
            font-family: 'Open Sans', sans-serif;
            background-color: var(--wiki-bg);
            color: #343a40;
            line-height: 1.6;
        }

        /* BANNER HEADER PROFISSIONAL */
        .wiki-header-banner {
            background: var(--poke-blue);
            padding: 30px 0;
            text-align: center;
            border-bottom: 5px solid var(--poke-yellow);
        }
        .wiki-header-banner h1 {
            font-family: 'Montserrat', sans-serif;
            font-weight: 900;
            color: white;
            font-size: 2.5rem;
            letter-spacing: 3px;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.4), 0 0 5px rgba(0, 0, 0, 0.8);
            margin: 0;
        }

        /* CONTAINER DO LAYOUT */
        .wiki-container-wrapper {
            max-width: 1400px;
            margin: 30px auto;
            background-color: var(--main-bg);
            border-radius: 12px;
            box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }

        /* BARRA LATERAL ESQUERDA (NAVEGAÇÃO) */
        .wiki-nav-sidebar {
            background-color: var(--sidebar-bg);
            padding: 20px 0;
            border-right: 1px solid var(--border-color);
        }
        .wiki-nav-sidebar .list-group-item {
            border: none;
            border-radius: 0;
            padding: 12px 20px;
            font-weight: 600;
            color: var(--poke-blue);
            transition: background-color 0.2s, color 0.2s, border-left 0.2s;
            border-left: 5px solid transparent;
        }
        .wiki-nav-sidebar .list-group-item:hover {
            background-color: #e2e6ea;
            border-left: 5px solid var(--poke-yellow);
        }
        .wiki-nav-sidebar .list-group-item.active {
            background-color: var(--poke-blue);
            color: white;
            border-left: 5px solid var(--poke-yellow);
        }
        .wiki-nav-sidebar .sidebar-heading {
            color: var(--poke-blue);
            font-family: 'Montserrat', sans-serif;
            font-size: 1rem;
            font-weight: 700;
            padding: 10px 20px;
            margin-top: 20px;
            margin-bottom: 10px;
            border-bottom: 2px solid var(--poke-yellow);
            text-transform: uppercase;
        }
        /* CAMPO DE PESQUISA */
        .input-group button.btn-warning {
             background-color: var(--poke-yellow);
             border-color: var(--poke-yellow);
        }
        .input-group button.btn-warning:hover {
             background-color: #e6b800;
             border-color: #e6b800;
        }


        /* CONTEÚDO PRINCIPAL (ARTIGOS/LISTAS) */
        .wiki-main-content {
            padding: 30px;
        }
        .article-card-body {
            font-size: 1.05rem;
            color: #212529;
        }
        .breadcrumb a { 
            color: var(--poke-blue) !important; 
            text-decoration: none; 
            font-weight: 600;
        }
        .list-articles a { 
            border-left: 8px solid var(--poke-yellow); /* Borda mais grossa de destaque */
            margin-bottom: 10px;
            transition: background-color 0.2s, transform 0.2s;
            border-radius: 5px;
        }
        .list-articles a:hover {
             background-color: #fffde7;
             transform: translateX(5px);
        }
        .card-category-link:hover .card-body {
            background-color: #e9ecef;
        }
        .card-category-link {
            transition: transform 0.2s;
            border: 1px solid var(--border-color) !important;
        }
        .card-category-link:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1) !important;
        }


        /* BARRA LATERAL DIREITA (NOVIDADES/ADS) - POKÉDEX STYLE */
        .wiki-news-sidebar {
            background-color: #f8f9fa; /* Fundo claro para contraste */
            padding: 20px;
            border-left: 1px solid var(--border-color);
        }
        .wiki-news-sidebar .news-card {
            background-color: white;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            transition: transform 0.2s;
        }
        .wiki-news-sidebar .news-card:hover {
            transform: translateY(-2px);
        }
        .wiki-news-sidebar .news-card img {
            width: 100%;
            height: 100px;
            object-fit: cover;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
        }
        .wiki-news-sidebar h5 {
            color: var(--poke-red);
            font-weight: 700;
        }
        .wiki-news-sidebar .btn-outline-secondary {
            color: var(--poke-red);
            border-color: var(--poke-red);
            transition: all 0.2s;
        }
        .wiki-news-sidebar .btn-outline-secondary:hover {
            background-color: var(--poke-red);
            color: white;
        }

        /* 📱 RESPONSIVIDADE - AJUSTES FINOS */
        @media (max-width: 991px) {
            .wiki-container-wrapper {
                margin: 0;
                border-radius: 0;
                box-shadow: none;
            }
            .wiki-nav-sidebar {
                order: 1; 
                border-bottom: 1px solid var(--border-color);
                border-right: none;
            }
            .wiki-main-content {
                order: 2; 
                padding: 20px;
            }
            .wiki-news-sidebar {
                order: 3; 
                border-top: 1px solid var(--border-color);
                border-left: none;
            }
            .wiki-header-banner h1 {
                font-size: 2rem;
            }
        }
        @media (max-width: 767px) {
             .list-group-item small {
                display: none !important; /* Esconde tags em mobile para economizar espaço */
             }
        }
    </style>
</head>
<body>

<div class="wiki-header-banner">
    <h1 class="display-4"><i class="fas fa-compass me-2 text-warning"></i> WIKI DTPOKÉMON</h1>
</div>

<div class="wiki-container-wrapper container-fluid"> 
    <div class="row g-0">

        <div class="col-lg-3 wiki-nav-sidebar">
            
            <a href="wiki.php" class="list-group-item list-group-item-action mb-3 fw-bold text-center <?php echo (!$viewArticle && !$viewCategory && !$searchQuery) ? 'active' : ''; ?>">
                <i class="fas fa-home me-2"></i> Página Principal
            </a>
            
            <form action="wiki.php" method="GET" class="px-3 mb-4">
                <div class="input-group">
                    <input type="text" name="search" class="form-control form-control-sm" placeholder="Pesquisar..." value="<?php echo htmlspecialchars($searchQuery ?? ''); ?>" required>
                    <button class="btn btn-warning btn-sm" type="submit"><i class="fas fa-search text-dark"></i></button>
                </div>
            </form>

            <h6 class="sidebar-heading">
                <i class="fas fa-stream me-2"></i> Categorias
            </h6>
            <div class="list-group list-group-flush">
                <?php foreach ($categories as $cat): ?>
                    <a href="?cat=<?php echo $cat['slug']; ?>" class="list-group-item list-group-item-action <?php echo ($viewCategory === $cat['slug']) ? 'active' : ''; ?>">
                        <?php echo htmlspecialchars($cat['name']); ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <h6 class="sidebar-heading">
                <i class="fas fa-external-link-alt me-2"></i> Outros Links
            </h6>
            <div class="list-group list-group-flush">
                <a href="index.php" class="list-group-item list-group-item-action">
                    Voltar ao Site
                </a>
                <a href="suporte.php" class="list-group-item list-group-item-action">
                    Suporte
                </a>
            </div>
        </div>

        <div class="col-lg-7 wiki-main-content">
            
            <?php if ($article): ?>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="wiki.php">Wiki</a></li>
                        <li class="breadcrumb-item"><a href="?cat=<?php echo $article['category_slug']; ?>"><?php echo htmlspecialchars($article['category_name']); ?></a></li>
                        <li class="breadcrumb-item active" aria-current="page"><?php echo htmlspecialchars($article['title']); ?></li>
                    </ol>
                </nav>
                <div class="card shadow-lg mb-4 border-0">
                    <div class="card-header bg-light border-bottom-0 py-3 d-flex justify-content-between align-items-center">
                        <h2 class="h3 fw-bold text-poke-blue"><?php echo htmlspecialchars($article['title']); ?></h2>
                        <span class="badge bg-secondary"><i class="fas fa-eye me-1"></i> <?php echo number_format($article['views']); ?> Views</span>
                    </div>
                    <div class="card-body p-4 article-card-body">
                        <?php echo nl2br($article['content']); ?>
                    </div>
                    <div class="card-footer small text-muted text-end">
                        <i class="fas fa-clock me-1"></i> Última Atualização: <?php echo date('d/m/Y H:i', $article['updated_at']); ?>
                    </div>
                </div>

            <?php elseif ($currentCategory || $searchQuery): ?>
                <?php if ($searchQuery): ?>
                    <h2 class="h3 fw-bold mb-2 text-dark"><i class="fas fa-search me-2"></i> Resultados para "<?php echo htmlspecialchars($searchQuery); ?>"</h2>
                    <p class="text-muted border-bottom pb-3">Encontrados **<?php echo count($articlesList); ?>** artigos.</p>
                <?php else: ?>
                    <h2 class="h3 fw-bold mb-2 text-poke-blue"><i class="fas fa-list me-2"></i> <?php echo htmlspecialchars($currentCategory['name']); ?></h2>
                    <p class="text-muted border-bottom pb-3"><?php echo htmlspecialchars($currentCategory['description']); ?></p>
                <?php endif; ?>

                <div class="list-group shadow list-articles">
                    <?php if (!empty($articlesList)): ?>
                        <?php foreach ($articlesList as $art): ?>
                            <a href="?article=<?php echo $art['slug']; ?>" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="mb-1 fw-bold text-dark"><?php echo htmlspecialchars($art['title']); ?></h5>
                                    <?php if ($searchQuery): ?>
                                         <small class="text-secondary d-block">Categoria: <span class="fw-semibold"><?php echo htmlspecialchars($art['category_name']); ?></span></small>
                                    <?php endif; ?>
                                </div>
                                <span class="badge rounded-pill bg-light text-muted small ms-2 d-none d-md-inline">
                                    <i class="fas fa-clock me-1"></i> <?php echo date('d/m/Y', $art['updated_at']); ?>
                                </span>
                            </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="list-group-item text-center text-muted p-4 border-0">
                            <i class="fas fa-info-circle me-2"></i> Nenhum artigo encontrado nesta seção.
                        </div>
                    <?php endif; ?>
                </div>

            <?php else: ?>
                <h2 class="h3 fw-bold mb-4 text-poke-red"><i class="fas fa-book-open me-2"></i> Sistemas e Guias Principais</h2>
                <p class="text-muted">Explore os guias mais importantes e os sistemas-chave do jogo. Utilize a busca ou a navegação lateral para encontrar o que precisa.
                

[Image of Top-Down RPG World Map]

                </p>
                
                <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
                    <?php foreach ($categories as $cat): ?>
                        <div class="col">
                            <a href="?cat=<?php echo $cat['slug']; ?>" class="card card-category-link shadow-sm h-100 text-decoration-none bg-white">
                                <div class="card-body">
                                    <h5 class="card-title fw-bold text-poke-blue"><i class="fas fa-folder-open me-2 text-warning"></i> <?php echo htmlspecialchars($cat['name']); ?></h5>
                                    <p class="card-text text-muted small"><?php echo htmlspecialchars($cat['description']); ?></p>
                                </div>
                            </a>
                        </div>
                    <?php endforeach; ?>
                    
                    <?php if (empty($categories)): ?>
                        <div class="col-12"><div class="alert alert-info text-center">Nenhuma categoria criada ainda. Acesse o Painel Admin.</div></div>
                    <?php endif; ?>
                </div>

            <?php endif; ?>
        </div>

        <div class="col-lg-2 wiki-news-sidebar d-none d-lg-block">
            <h5 class="fw-bold text-uppercase mb-3">
                <i class="fas fa-bullhorn me-2"></i> Novidades
            </h5>
            
            <div class="news-card">
                <img src="https://via.placeholder.com/200x100/cc0000/ffcb05?text=Update+23.22" alt="Novidade 1">
                <div class="p-3 small">
                    <p class="mb-1 fw-bold text-poke-blue">Update 23.22</p>
                    <p class="mb-0 text-muted">Confira os novos pokémon e quests!</p>
                </div>
            </div>

            <div class="news-card">
                <img src="https://via.placeholder.com/200x100/3b4cca/ffcb05?text=Novo+Evento" alt="Novidade 2">
                <div class="p-3 small">
                    <p class="mb-1 fw-bold text-poke-blue">Evento da Semana</p>
                    <p class="mb-0 text-muted">Bônus de XP e loots raros!</p>
                </div>
            </div>

            <button class="btn btn-outline-secondary btn-sm w-100 mt-3 fw-bold"><i class="fas fa-file-alt me-1"></i> PATCH NOTES</button>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>