<?php
$pageTitle = "Our Achievements";
require_once 'includes/header.php';

// Get publication statistics
$total_publications = 0;
$publication_stats = [];

// Check if publications table exists
$pub_table_exists = false;
try {
    $result = $db->query("SHOW TABLES LIKE 'publications'");
    if ($result && $result->num_rows > 0) {
        $pub_table_exists = true;
    }
} catch (Exception $e) {
    $pub_table_exists = false;
}

if ($pub_table_exists) {
    // Get total publications
    $total_publications = $db->fetchRow("SELECT COUNT(*) as count FROM publications")['count'] ?? 0;
    
    // Get publication stats by type
    $type_column = 'type';
    try {
        $result = $db->query("SHOW COLUMNS FROM publications LIKE 'type'");
        if (!$result || $result->num_rows == 0) {
            $result = $db->query("SHOW COLUMNS FROM publications LIKE 'publication_type'");
            if ($result && $result->num_rows > 0) {
                $type_column = 'publication_type';
            }
        }
    } catch (Exception $e) {
        // Use default
    }
    
    $query = "SELECT {$type_column} as type, COUNT(*) as count FROM publications GROUP BY {$type_column} ORDER BY count DESC";
    $publication_stats = $db->fetchAll($query);
}

// Get faculty count
$total_faculty = $db->fetchRow("SELECT COUNT(*) as count FROM faculty")['count'] ?? 0;

// Get total events
$total_events = $db->fetchRow("SELECT COUNT(*) as count FROM events")['count'] ?? 0;

// Get total books in library
$total_books = 0;
try {
    $result = $db->query("SHOW TABLES LIKE 'library'");
    if ($result && $result->num_rows > 0) {
        $total_books = $db->fetchRow("SELECT COUNT(*) as count FROM library")['count'] ?? 0;
    }
} catch (Exception $e) {
    $total_books = 0;
}

// Get Achievements category posts
$achievements_posts = [];
$achievements_category_id = null;
try {
    // First get the Achievements category ID
    $category = $db->fetchRow("SELECT id FROM categories WHERE name = 'Achievements' OR slug = 'achievements'");
    
    if ($category) {
        $achievements_category_id = $category['id'];
        
        // Get published posts from Achievements category
        $query = "SELECT p.*, c.name as category_name, c.slug as category_slug 
                 FROM posts p 
                 LEFT JOIN categories c ON p.category_id = c.id
                 WHERE p.status = 'published' AND p.category_id = ?
                 ORDER BY p.created_at DESC
                 LIMIT 6";
        
        $stmt = $db->prepare($query);
        $stmt->bind_param("i", $achievements_category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $achievements_posts = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        // Apply multilingual fallback
        $currentLang = getCurrentLanguage();
        foreach ($achievements_posts as &$post) {
            $post['title'] = getContentWithFallback('posts', $post['id'], 'title', $currentLang) ?: $post['title'];
            $post['excerpt'] = getContentWithFallback('posts', $post['id'], 'excerpt', $currentLang) ?: $post['excerpt'];
        }
    }
} catch (Exception $e) {
    error_log("Error fetching achievements posts: " . $e->getMessage());
    $achievements_posts = [];
}
?>

<section class="hero">
    <div class="container">
        <div class="hero-content">
            <span class="hero-subtitle">Our Success</span>
            <h1 class="hero-title">Research Achievements</h1>
            <p class="page-description">Discover our outstanding research output and academic excellence in the field of cyber law.</p>
        </div>
    </div>
</section>

<!-- Publications Statistics -->
<section class="section" style="background-color: var(--white-soft);">
    <div class="container">
        <div class="text-center mb-5">
            <h2><i class="fas fa-book-open"></i> Research Output Overview</h2>
            <p class="text-secondary">Our comprehensive publication portfolio across various categories</p>
        </div>
        
        <?php if (!empty($publication_stats)): ?>
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                            <div class="card text-center" style="border: none; border-radius: 15px; overflow: hidden; transition: transform 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 4px 12px rgba(0,0,0,0.15);" onmouseover="this.style.transform='translateY(-5px)'; this.style.boxShadow='0 8px 20px rgba(0,0,0,0.2)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.15)';">
                                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 2rem 1.5rem;">
                                    <div style="background-color: rgba(255,255,255,0.2); width: 70px; height: 70px; margin: 0 auto 1.5rem; border-radius: 50%; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px);">
                                        <i class="fas fa-book-open" style="font-size: 2rem; color: white;"></i>
                                    </div>
                                    <h2 style="font-size: 2.5rem; font-weight: 700; color: white; margin-bottom: 0.5rem;"><?php echo number_format($total_publications); ?></h2>
                                    <p style="font-size: 0.95rem; color: rgba(255,255,255,0.95); margin: 0; font-weight: 500;">Total Publications</p>
                                </div>
                            </div>
                        </div>
                        <?php 
                        // Define type labels and icons
                        $typeLabels = [
                            'article_national' => ['label' => 'National Articles', 'icon' => 'fa-flag', 'color' => '#A29BFE'],
                            'article_oak' => ['label' => 'OAK Articles', 'icon' => 'fa-certificate', 'color' => '#00B894'],
                            'article_international' => ['label' => 'International Articles', 'icon' => 'fa-globe', 'color' => '#6C5CE7'],
                            'article_scopus' => ['label' => 'Scopus Articles', 'icon' => 'fa-star', 'color' => '#FFD93D'],
                            'article_wos' => ['label' => 'Web of Science Articles', 'icon' => 'fa-award', 'color' => '#FD79A8'],
                            'monograph' => ['label' => 'Monographs', 'icon' => 'fa-book', 'color' => '#FF6B6B'],
                            'textbook' => ['label' => 'Textbooks', 'icon' => 'fa-book-open', 'color' => '#45B7D1'],
                            'study_guide' => ['label' => 'Study Guides', 'icon' => 'fa-graduation-cap', 'color' => '#96CEB4'],
                            'conference_paper' => ['label' => 'Conference Papers', 'icon' => 'fa-users', 'color' => '#FD79A8'],
                            // Legacy types for backward compatibility
                            'article' => ['label' => 'Articles', 'icon' => 'fa-file-alt', 'color' => '#4ECDC4'],
                            'scopus_article' => ['label' => 'Scopus Articles', 'icon' => 'fa-star', 'color' => '#FFD93D'],
                            'international_journal' => ['label' => 'International Articles', 'icon' => 'fa-globe', 'color' => '#6C5CE7'],
                            'national_journal' => ['label' => 'National Articles', 'icon' => 'fa-flag', 'color' => '#A29BFE'],
                            'journal' => ['label' => 'Articles', 'icon' => 'fa-file-alt', 'color' => '#4ECDC4'],
                            'book' => ['label' => 'Books', 'icon' => 'fa-book', 'color' => '#FF6B6B'],
                            'conference' => ['label' => 'Conference Papers', 'icon' => 'fa-users', 'color' => '#FD79A8'],
                            'book_chapter' => ['label' => 'Book Chapters', 'icon' => 'fa-bookmark', 'color' => '#FDCB6E'],
                            'technical_report' => ['label' => 'Technical Reports', 'icon' => 'fa-file-code', 'color' => '#74B9FF'],
                            'chapter' => ['label' => 'Chapters', 'icon' => 'fa-bookmark', 'color' => '#FDCB6E'],
                            'report' => ['label' => 'Reports', 'icon' => 'fa-file-code', 'color' => '#74B9FF'],
                            'other' => ['label' => 'Other', 'icon' => 'fa-ellipsis-h', 'color' => '#DFE6E9']
                        ];
                        
                        foreach ($publication_stats as $stat): 
                            $type = $stat['type'] ?? 'other';
                            $typeInfo = $typeLabels[$type] ?? $typeLabels['other'];
                        ?>
                        <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                            <div class="card text-center" style="border: none; border-radius: 15px; overflow: hidden; transition: transform 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 2px 8px rgba(0,0,0,0.08);" onmouseover="this.style.transform='translateY(-5px)'; this.style.boxShadow='0 8px 16px rgba(0,0,0,0.15)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0,0,0,0.08)';">
                                <div style="background: linear-gradient(135deg, <?php echo $typeInfo['color']; ?>15 0%, <?php echo $typeInfo['color']; ?>25 100%); padding: 2rem 1.5rem;">
                                    <div style="background-color: white; width: 70px; height: 70px; margin: 0 auto 1.5rem; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
                                        <i class="fas <?php echo $typeInfo['icon']; ?>" style="font-size: 2rem; color: <?php echo $typeInfo['color']; ?>;"></i>
                                    </div>
                                    <h2 style="font-size: 2.5rem; font-weight: 700; color: <?php echo $typeInfo['color']; ?>; margin-bottom: 0.5rem;"><?php echo number_format($stat['count']); ?></h2>
                                    <p style="font-size: 0.95rem; color: #666; margin: 0; font-weight: 500;"><?php echo $typeInfo['label']; ?></p>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Chart Visualization -->
                    <?php if (count($publication_stats) > 0): ?>
                    <div class="mt-5">
                        <div class="row">
                            <div class="col-md-6 mb-4">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="text-center mb-4">Publications Distribution</h5>
                                        <canvas id="publicationsChartDoughnut" style="max-height: 350px;"></canvas>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6 mb-4">
                                <div class="card">
                                    <div class="card-body">
                                        <h5 class="text-center mb-4">Publications by Category</h5>
                                        <canvas id="publicationsChartBar" style="max-height: 350px;"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="fas fa-book fa-4x text-muted mb-4"></i>
                    <h4 class="text-muted">No publications available yet</h4>
                    <p class="text-secondary">Check back soon for our latest research contributions.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- Research Impact -->
<section class="section" style="background-color: var(--white-soft);">
    <div class="container">
        <div class="text-center mb-5">
            <h2>Research Impact</h2>
            <p class="text-secondary">Our commitment to excellence in cyber law research</p>
        </div>
        
        <div class="row">
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="card text-center">
                    <div class="card-body">
                        <div class="feature-icon mb-3" style="color: #FFD93D;">
                            <i class="fas fa-star"></i>
                        </div>
                        <h4>International Recognition</h4>
                        <p>Publications in Scopus and Web of Science indexed journals, recognized globally for their impact.</p>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="card text-center">
                    <div class="card-body">
                        <div class="feature-icon mb-3" style="color: #6C5CE7;">
                            <i class="fas fa-globe"></i>
                        </div>
                        <h4>Global Collaboration</h4>
                        <p>Research partnerships with leading institutions across the world in cyber law and digital rights.</p>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="card text-center">
                    <div class="card-body">
                        <div class="feature-icon mb-3" style="color: #FF6B6B;">
                            <i class="fas fa-book"></i>
                        </div>
                        <h4>Academic Resources</h4>
                        <p>Comprehensive collection of textbooks, monographs, and study materials for students and researchers.</p>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="card text-center">
                    <div class="card-body">
                        <div class="feature-icon mb-3" style="color: #00B894;">
                            <i class="fas fa-certificate"></i>
                        </div>
                        <h4>Quality Assurance</h4>
                        <p>All publications undergo rigorous peer review and meet international academic standards.</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="text-center mt-4">
            <a href="/publications" class="btn btn-primary">
                <i class="fas fa-book-reader"></i> Browse All Publications
            </a>
            <a href="/faculty" class="btn btn-outline ms-2">
                <i class="fas fa-users"></i> Meet Our Faculty
            </a>
        </div>
    </div>
</section>

<!-- Achievements Posts Section -->
<?php if (!empty($achievements_posts)): ?>
<section class="section">
    <div class="container">
        <div class="text-center mb-5">
            <h2><i class="fas fa-trophy"></i> Achievements & Milestones</h2>
            <p class="text-secondary">Celebrating our department's outstanding accomplishments and recognition</p>
        </div>
        
        <div class="posts-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 2rem;">
            <?php foreach ($achievements_posts as $post): ?>
                <div class="card" style="border: none; border-radius: 15px; overflow: hidden; transition: transform 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 2px 8px rgba(0,0,0,0.08);" onmouseover="this.style.transform='translateY(-8px)'; this.style.boxShadow='0 12px 24px rgba(0,0,0,0.15)';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0,0,0,0.08)';">
                    <?php if (!empty($post['featured_image'])): ?>
                        <div style="position: relative; overflow: hidden; height: 200px;">
                            <img src="<?php echo UPLOADS_URL; ?>/posts/<?php echo htmlspecialchars($post['featured_image']); ?>" 
                                 alt="<?php echo htmlspecialchars($post['title']); ?>" 
                                 style="width: 100%; height: 100%; object-fit: cover; transition: transform 0.3s ease;"
                                 onmouseover="this.style.transform='scale(1.1)';" 
                                 onmouseout="this.style.transform='scale(1)';">
                            <div style="position: absolute; top: 15px; left: 15px;">
                                <span style="background: linear-gradient(135deg, #FFD93D 0%, #FFA500 100%); color: white; padding: 0.4rem 1rem; border-radius: 20px; font-size: 0.85rem; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.2);">
                                    <i class="fas fa-trophy"></i> Achievement
                                </span>
                            </div>
                        </div>
                    <?php else: ?>
                        <div style="background: linear-gradient(135deg, #FFD93D 0%, #FFA500 100%); height: 200px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-trophy" style="font-size: 4rem; color: rgba(255,255,255,0.5);"></i>
                        </div>
                    <?php endif; ?>
                    
                    <div class="card-body" style="padding: 1.5rem;">
                        <h4 style="font-size: 1.2rem; font-weight: 600; margin-bottom: 0.75rem; line-height: 1.4;">
                            <a href="/post/<?php echo htmlspecialchars($post['slug']); ?>" 
                               style="color: #333; text-decoration: none; transition: color 0.3s ease;"
                               onmouseover="this.style.color='#FFD93D';" 
                               onmouseout="this.style.color='#333';">
                                <?php echo htmlspecialchars($post['title']); ?>
                            </a>
                        </h4>
                        
                        <?php if (!empty($post['excerpt'])): ?>
                            <p style="color: #666; font-size: 0.95rem; line-height: 1.6; margin-bottom: 1rem;">
                                <?php echo htmlspecialchars(substr(strip_tags($post['excerpt']), 0, 120)) . (strlen(strip_tags($post['excerpt'])) > 120 ? '...' : ''); ?>
                            </p>
                        <?php endif; ?>
                        
                        <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #eee;">
                            <span style="color: #999; font-size: 0.85rem;">
                                <i class="fas fa-calendar-alt"></i> 
                                <?php echo date('M d, Y', strtotime($post['created_at'])); ?>
                            </span>
                            <a href="/post/<?php echo htmlspecialchars($post['slug']); ?>" 
                               class="btn btn-sm btn-outline" 
                               style="padding: 0.4rem 1rem; font-size: 0.85rem; border-radius: 20px;">
                                Read More <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <?php if ($achievements_category_id): ?>
        <div class="text-center mt-5">
            <a href="/news?category=<?php echo $achievements_category_id; ?>" class="btn btn-primary">
                <i class="fas fa-list"></i> View All Achievements
            </a>
        </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if (!empty($publication_stats)): ?>
    // Check if Chart.js is loaded
    if (typeof Chart === 'undefined') {
        console.error('Chart.js library failed to load');
        const charts = document.querySelectorAll('canvas[id^="publicationsChart"]');
        charts.forEach(chart => {
            chart.style.display = 'none';
            const msg = document.createElement('p');
            msg.style.textAlign = 'center';
            msg.style.padding = '20px';
            msg.style.color = '#999';
            msg.textContent = 'Chart library failed to load';
            chart.parentNode.appendChild(msg);
        });
    } else {
        try {
            // Prepare data for charts
            const labels = [];
            const data = [];
            const colors = [];
            
            const typeColors = {
                'article_national': '#A29BFE',
                'article_oak': '#00B894',
                'article_international': '#6C5CE7',
                'article_scopus': '#FFD93D',
                'article_wos': '#FD79A8',
                'monograph': '#FF6B6B',
                'textbook': '#45B7D1',
                'study_guide': '#96CEB4',
                'conference_paper': '#FD79A8',
                // Legacy types
                'article': '#4ECDC4',
                'scopus_article': '#FFD93D',
                'international_journal': '#6C5CE7',
                'national_journal': '#A29BFE',
                'journal': '#4ECDC4',
                'book': '#FF6B6B',
                'conference': '#FD79A8',
                'book_chapter': '#FDCB6E',
                'technical_report': '#74B9FF',
                'chapter': '#FDCB6E',
                'report': '#74B9FF',
                'other': '#DFE6E9'
            };
            
            const typeLabels = {
                'article_national': 'National Articles',
                'article_oak': 'OAK Articles',
                'article_international': 'Intl. Articles',
                'article_scopus': 'Scopus Articles',
                'article_wos': 'WoS Articles',
                'monograph': 'Monographs',
                'textbook': 'Textbooks',
                'study_guide': 'Study Guides',
                'conference_paper': 'Conference Papers',
                // Legacy types
                'article': 'Articles',
                'scopus_article': 'Scopus Articles',
                'international_journal': 'Intl. Articles',
                'national_journal': 'National Articles',
                'journal': 'Articles',
                'book': 'Books',
                'conference': 'Conference Papers',
                'book_chapter': 'Book Chapters',
                'technical_report': 'Technical Reports',
                'chapter': 'Chapters',
                'report': 'Reports',
                'other': 'Other'
            };
            
            <?php foreach ($publication_stats as $stat): ?>
            {
                const type = '<?php echo addslashes($stat['type'] ?? 'other'); ?>';
                const count = <?php echo intval($stat['count']); ?>;
                labels.push(typeLabels[type] || type);
                data.push(count);
                colors.push(typeColors[type] || '#DFE6E9');
            }
            <?php endforeach; ?>
            
            // Create doughnut chart
            const ctxDoughnut = document.getElementById('publicationsChartDoughnut');
            if (ctxDoughnut) {
                new Chart(ctxDoughnut, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Publications',
                            data: data,
                            backgroundColor: colors,
                            borderWidth: 3,
                            borderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    padding: 15,
                                    font: {
                                        size: 12
                                    }
                                }
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        let label = context.label || '';
                                        if (label) {
                                            label += ': ';
                                        }
                                        label += context.parsed;
                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                        const percentage = ((context.parsed / total) * 100).toFixed(1);
                                        label += ' (' + percentage + '%)';
                                        return label;
                                    }
                                }
                            }
                        }
                    }
                });
            }
            
            // Create bar chart
            const ctxBar = document.getElementById('publicationsChartBar');
            if (ctxBar) {
                new Chart(ctxBar, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Number of Publications',
                            data: data,
                            backgroundColor: colors,
                            borderWidth: 1,
                            borderColor: colors.map(c => c)
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return 'Publications: ' + context.parsed.y;
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    stepSize: 1
                                }
                            }
                        }
                    }
                });
            }
        } catch (error) {
            console.error('Error creating charts:', error);
        }
    }
    <?php endif; ?>
});
</script>

<?php require_once 'includes/footer.php'; ?>

