<?php
require_once 'config.php';
require_once 'classes/Security.php';

$pageTitle = 'Knowledge Base - CryptoExchange Pro | Cryptocurrency Trading Guide';
$pageDescription = 'Learn about cryptocurrency trading, security, KYC verification, and how to use our P2P exchange platform safely and effectively.';

// Get knowledge base articles
$db = new Database();
$db->query("SELECT * FROM knowledge_base WHERE is_active = 1 ORDER BY category, title");
$articles = $db->resultSet();

// Group articles by category
$categories = [];
foreach ($articles as $article) {
    $categories[$article['category']][] = $article;
}

$selectedCategory = $_GET['category'] ?? '';
$selectedArticle = $_GET['article'] ?? '';

include 'includes/header.php';
?>

<main class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-book text-blue-600 mr-3"></i>Knowledge Base
            </h1>
            <p class="text-gray-600">Learn everything about cryptocurrency trading and our platform</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
            <!-- Categories Sidebar -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden sticky top-8">
                    <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-list text-blue-600 mr-2"></i>Categories
                        </h2>
                    </div>
                    <div class="p-6">
                        <ul class="space-y-2">
                            <li>
                                <a href="knowledge.php" class="block px-4 py-2 rounded-lg transition-colors duration-200 <?php echo !$selectedCategory ? 'bg-blue-100 text-blue-800 font-medium' : 'text-gray-700 hover:bg-gray-100'; ?>">
                                    <i class="fas fa-home mr-2"></i>All Articles
                                </a>
                            </li>
                            <?php foreach ($categories as $category => $categoryArticles): ?>
                            <li>
                                <a href="knowledge.php?category=<?php echo urlencode($category); ?>" class="block px-4 py-2 rounded-lg transition-colors duration-200 <?php echo $selectedCategory === $category ? 'bg-blue-100 text-blue-800 font-medium' : 'text-gray-700 hover:bg-gray-100'; ?>">
                                    <?php
                                    $categoryIcons = [
                                        'Getting Started' => 'fa-play-circle',
                                        'Security' => 'fa-shield-alt',
                                        'Trading' => 'fa-exchange-alt',
                                        'KYC' => 'fa-id-card',
                                        'Wallet' => 'fa-wallet',
                                        'Fees' => 'fa-dollar-sign'
                                    ];
                                    ?>
                                    <i class="fas <?php echo $categoryIcons[$category] ?? 'fa-file-alt'; ?> mr-2"></i>
                                    <?php echo $category; ?>
                                    <span class="text-xs bg-gray-200 text-gray-600 px-2 py-1 rounded-full ml-2"><?php echo count($categoryArticles); ?></span>
                                </a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="lg:col-span-3">
                <?php if ($selectedArticle): ?>
                <!-- Single Article View -->
                <?php
                $db->query("SELECT * FROM knowledge_base WHERE id = :id AND is_active = 1");
                $db->bind(':id', $selectedArticle);
                $article = $db->single();
                
                if ($article):
                    // Update view count
                    $db->query("UPDATE knowledge_base SET views = views + 1 WHERE id = :id");
                    $db->bind(':id', $selectedArticle);
                    $db->execute();
                ?>
                <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                    <div class="p-8">
                        <div class="mb-6">
                            <nav class="text-sm text-gray-500 mb-4">
                                <a href="knowledge.php" class="hover:text-blue-600">Knowledge Base</a>
                                <span class="mx-2">/</span>
                                <a href="knowledge.php?category=<?php echo urlencode($article['category']); ?>" class="hover:text-blue-600"><?php echo $article['category']; ?></a>
                                <span class="mx-2">/</span>
                                <span class="text-gray-800"><?php echo $article['title']; ?></span>
                            </nav>
                            <h1 class="text-3xl font-bold text-gray-800 mb-4"><?php echo $article['title']; ?></h1>
                            <div class="flex items-center text-sm text-gray-500 space-x-4">
                                <span><i class="fas fa-folder mr-1"></i><?php echo $article['category']; ?></span>
                                <span><i class="fas fa-eye mr-1"></i><?php echo number_format($article['views']); ?> views</span>
                                <span><i class="fas fa-calendar mr-1"></i><?php echo date('M j, Y', strtotime($article['created_at'])); ?></span>
                            </div>
                        </div>
                        
                        <div class="prose max-w-none">
                            <?php echo nl2br($article['content']); ?>
                        </div>
                        
                        <?php if ($article['tags']): ?>
                        <div class="mt-8 pt-6 border-t border-gray-200">
                            <h3 class="text-sm font-medium text-gray-500 mb-3">Tags:</h3>
                            <div class="flex flex-wrap gap-2">
                                <?php foreach (explode(',', $article['tags']) as $tag): ?>
                                <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"><?php echo trim($tag); ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php else: ?>
                <div class="bg-white rounded-xl shadow-xl overflow-hidden p-8 text-center">
                    <i class="fas fa-file-alt text-6xl text-gray-300 mb-4"></i>
                    <h2 class="text-2xl font-bold text-gray-600 mb-2">Article Not Found</h2>
                    <p class="text-gray-500 mb-6">The article you're looking for doesn't exist or has been removed.</p>
                    <a href="knowledge.php" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold transition-colors duration-200">
                        <i class="fas fa-arrow-left mr-2"></i>Back to Knowledge Base
                    </a>
                </div>
                <?php endif; ?>
                
                <?php else: ?>
                <!-- Articles List -->
                <?php
                $displayArticles = $selectedCategory ? ($categories[$selectedCategory] ?? []) : $articles;
                ?>
                
                <!-- Search Bar -->
                <div class="bg-white rounded-xl shadow-xl overflow-hidden mb-8">
                    <div class="p-6">
                        <div class="relative">
                            <input type="text" id="searchInput" placeholder="Search articles..." class="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <i class="fas fa-search text-gray-400"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Articles Grid -->
                <?php if (!empty($displayArticles)): ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6" id="articlesGrid">
                    <?php foreach ($displayArticles as $article): ?>
                    <div class="bg-white rounded-xl shadow-xl overflow-hidden hover:shadow-2xl transition-shadow duration-300 article-card" data-title="<?php echo strtolower($article['title']); ?>" data-content="<?php echo strtolower($article['content']); ?>" data-category="<?php echo strtolower($article['category']); ?>">
                        <div class="p-6">
                            <div class="flex items-center justify-between mb-4">
                                <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium">
                                    <?php echo $article['category']; ?>
                                </span>
                                <span class="text-sm text-gray-500">
                                    <i class="fas fa-eye mr-1"></i><?php echo number_format($article['views']); ?>
                                </span>
                            </div>
                            
                            <h3 class="text-xl font-bold text-gray-800 mb-3 hover:text-blue-600 transition-colors duration-200">
                                <a href="knowledge.php?article=<?php echo $article['id']; ?>"><?php echo $article['title']; ?></a>
                            </h3>
                            
                            <p class="text-gray-600 mb-4 line-clamp-3">
                                <?php echo substr(strip_tags($article['content']), 0, 150) . '...'; ?>
                            </p>
                            
                            <div class="flex items-center justify-between">
                                <span class="text-sm text-gray-500">
                                    <i class="fas fa-calendar mr-1"></i><?php echo date('M j, Y', strtotime($article['created_at'])); ?>
                                </span>
                                <a href="knowledge.php?article=<?php echo $article['id']; ?>" class="text-blue-600 hover:text-blue-800 font-medium text-sm transition-colors duration-200">
                                    Read More <i class="fas fa-arrow-right ml-1"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="bg-white rounded-xl shadow-xl overflow-hidden p-8 text-center">
                    <i class="fas fa-search text-6xl text-gray-300 mb-4"></i>
                    <h2 class="text-2xl font-bold text-gray-600 mb-2">No Articles Found</h2>
                    <p class="text-gray-500">
                        <?php if ($selectedCategory): ?>
                        No articles found in the "<?php echo $selectedCategory; ?>" category.
                        <?php else: ?>
                        No articles are available at the moment.
                        <?php endif; ?>
                    </p>
                </div>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Popular Articles Section -->
        <?php if (!$selectedArticle): ?>
        <div class="mt-12">
            <h2 class="text-2xl font-bold text-gray-800 mb-6">
                <i class="fas fa-fire text-orange-500 mr-2"></i>Popular Articles
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <?php
                $db->query("SELECT * FROM knowledge_base WHERE is_active = 1 ORDER BY views DESC LIMIT 3");
                $popularArticles = $db->resultSet();
                foreach ($popularArticles as $article):
                ?>
                <div class="bg-white rounded-xl shadow-xl overflow-hidden hover:shadow-2xl transition-shadow duration-300">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-3">
                            <span class="px-3 py-1 bg-orange-100 text-orange-800 rounded-full text-xs font-medium">
                                Popular
                            </span>
                            <span class="text-sm text-gray-500">
                                <i class="fas fa-eye mr-1"></i><?php echo number_format($article['views']); ?>
                            </span>
                        </div>
                        
                        <h3 class="text-lg font-bold text-gray-800 mb-2 hover:text-blue-600 transition-colors duration-200">
                            <a href="knowledge.php?article=<?php echo $article['id']; ?>"><?php echo $article['title']; ?></a>
                        </h3>
                        
                        <p class="text-gray-600 text-sm mb-3">
                            <?php echo substr(strip_tags($article['content']), 0, 100) . '...'; ?>
                        </p>
                        
                        <a href="knowledge.php?article=<?php echo $article['id']; ?>" class="text-blue-600 hover:text-blue-800 font-medium text-sm transition-colors duration-200">
                            Read More <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
// Search functionality
document.getElementById('searchInput')?.addEventListener('input', function() {
    const searchTerm = this.value.toLowerCase();
    const articles = document.querySelectorAll('.article-card');
    
    articles.forEach(article => {
        const title = article.dataset.title;
        const content = article.dataset.content;
        const category = article.dataset.category;
        
        if (title.includes(searchTerm) || content.includes(searchTerm) || category.includes(searchTerm)) {
            article.style.display = 'block';
        } else {
            article.style.display = 'none';
        }
    });
});
</script>

<?php include 'includes/footer.php'; ?>