<?php
require_once 'config/database.php';
session_start();

// 获取要闻动态分类下的文章
$news_sql = "SELECT a.*, c.name as category_name 
            FROM articles a 
            LEFT JOIN categories c ON a.category_id = c.id 
            WHERE c.name = '要闻动态'
            ORDER BY a.created_at DESC 
            LIMIT 8";
$news_result = $conn->query($news_sql);

// 获取所有分类
$categories_sql = "SELECT * FROM categories ORDER BY id";
$categories_result = $conn->query($categories_sql);

// 获取每个分类下的最新文章
$category_articles = array();
if ($categories_result && $categories_result->num_rows > 0) {
    while ($category = $categories_result->fetch_assoc()) {
        $articles_sql = "SELECT a.*, c.name as category_name 
                        FROM articles a 
                        LEFT JOIN categories c ON a.category_id = c.id 
                        WHERE c.id = {$category['id']}
                        ORDER BY a.created_at DESC 
                        LIMIT 6";
        $articles_result = $conn->query($articles_sql);
        if ($articles_result) {
            $category_articles[$category['id']] = array(
                'category_name' => $category['name'],
                'articles' => $articles_result->fetch_all(MYSQLI_ASSOC)
            );
        }
    }
    // 重置分类结果集指针
    $categories_result->data_seek(0);
}

// 示例轮播图数据
$sample_slides = [
    [
        'title' => '我校信息工程系学子荣获三等奖、专科学校中第一名！',
        'image' => 'assets/images/ccb.jpg',
        'description' => '第十八届全国大学生信息安全竞赛（创新实践能力赛）暨第二届"长城杯"铁人三项赛（防护赛）半决赛'
    ],
    [
        'title' => '历史性突破、我校信息工程系学子荣获国赛一等奖！',
        'image' => 'assets/images/slide2.jpg',
        'description' => '2024一带一路暨金砖国家技能发展与技术创新大赛"企业信息系统安全"赛项'
    ],
    [
        'title' => '校园网络安全周活动圆满结束',
        'image' => 'assets/images/slide3.jpg',
        'description' => '提高全校师生网络安全意识'
    ]
];

// 获取轮播图文章（最新的3篇要闻动态文章）
$slider_sql = "SELECT a.*, c.name as category_name 
              FROM articles a 
              LEFT JOIN categories c ON a.category_id = c.id 
              WHERE c.name = '要闻动态'
              ORDER BY a.created_at DESC 
              LIMIT 3";
$slider_result = $conn->query($slider_sql);

// 准备轮播图数据
$slides = array();
if ($slider_result && $slider_result->num_rows > 0) {
    while ($slide = $slider_result->fetch_assoc()) {
        // 从文章内容中提取第一张图片
        if (preg_match('/!\[.*?\]\((.*?)\)/', $slide['content'], $matches)) {
            $slide['image'] = $matches[1];
        } else {
            // 如果文章中没有图片，使用示例图片
            $slide['image'] = $sample_slides[count($slides)]['image'];
        }
        
        // 如果文章没有描述，使用文章内容的前100个字符（去除Markdown语法）
        if (empty($slide['description'])) {
            // 去除Markdown图片语法
            $content = preg_replace('/!\[.*?\]\(.*?\)/', '', $slide['content']);
            // 去除其他Markdown语法
            $content = preg_replace('/\[(.*?)\]\(.*?\)/', '$1', $content);
            $content = preg_replace('/\*\*(.*?)\*\*/', '$1', $content);
            $content = preg_replace('/\*(.*?)\*/', '$1', $content);
            $content = preg_replace('/^#+\s*/', '', $content);
            $content = preg_replace('/^[-*]\s*/', '', $content);
            // 提取前100个字符
            $slide['description'] = mb_substr(strip_tags($content), 0, 100, 'UTF-8') . '...';
        }
        $slides[] = $slide;
    }
}

// 如果数据库中的文章少于3篇，用示例数据补充
while (count($slides) < 3) {
    $slides[] = $sample_slides[count($slides)];
}

if ($slider_result === false || $news_result === false) {
    die("查询失败: " . $conn->error);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>辽宁省交通高等专科学校网络安全工作室</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        body {
            background: #f5f5f5;
        }

        /* 主要内容区布局 */
        .main-content {
            max-width: 1200px;
            margin: 20px auto;
        }

        .content-wrapper {
            padding: 0 20px;
        }

        .top-content {
            display: grid;
            grid-template-columns: 800px 380px;
            gap: 20px;
            margin-bottom: 20px;
        }

        .bottom-content {
            display: grid;
            grid-template-columns: 800px 380px;
            gap: 20px;
        }

        .left-columns {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .category-column {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            height: 360px;
        }

        /* 轮播图样式调整 */
        .slider-container {
            margin: 0;
            height: 360px;
            background: #fff;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: relative;
            width: 100%;
        }
        .slider {
            height: 100%;
            display: flex;
            transition: transform 0.5s ease;
            position: relative;
            width: 300%; /* 根据图片数量设置宽度 */
        }
        .slide {
            width: 33.333%; /* 每张图片占总宽度的三分之一 */
            height: 100%;
            position: relative;
        }
        .slide img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .slide-caption {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0,0,0,0.8));
            color: white;
            padding: 20px;
        }
        .slide-title {
            font-size: 20px;
            margin: 0 0 8px 0;
            font-weight: bold;
        }
        .slide-description {
            font-size: 14px;
            opacity: 0.9;
            margin: 0;
            line-height: 1.4;
        }
        
        /* 要闻动态区域样式 */
        .news-container {
            margin: 0;
            height: 360px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }
        .news-header {
            padding: 15px 20px;
            border-bottom: 2px solid #0066cc;
            margin: 0;
        }
        .news-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .news-more {
            float: right;
            color: #666;
            text-decoration: none;
            font-size: 14px;
        }
        .news-more:hover {
            color: #0066cc;
        }
        .news-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px 20px;
            margin: 0;
            list-style: none;
        }
        .news-list::-webkit-scrollbar {
            width: 4px;
        }
        .news-list::-webkit-scrollbar-thumb {
            background-color: #ddd;
            border-radius: 2px;
        }
        .news-list::-webkit-scrollbar-track {
            background-color: #f5f5f5;
        }
        .news-item {
            padding: 12px 0;
            border-bottom: 1px dashed #eee;
            display: flex;
            align-items: center;
        }
        .news-item:last-child {
            border-bottom: none;
        }
        .news-item a {
            color: #333;
            text-decoration: none;
            flex: 1;
            font-size: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
        }
        .news-item a:hover {
            color: #0066cc;
        }
        .news-date {
            color: #999;
            font-size: 13px;
            margin-left: 15px;
        }

        /* 分类文章区域样式 */
        .categories-container {
            max-width: 1200px;
            margin: 0 auto 20px;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }
        .category-section {
            background: white;
            padding: 0;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .category-header {
            padding: 15px 20px;
            border-bottom: 2px solid #0066cc;
            margin: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 52px;
            box-sizing: border-box;
        }
        .category-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin: 0;
        }
        .category-more {
            color: #666;
            text-decoration: none;
            font-size: 14px;
        }
        .category-more:hover {
            color: #0066cc;
        }
        .category-list {
            list-style: none;
            padding: 10px 20px;
            margin: 0;
        }
        .category-item {
            padding: 10px 0;
            border-bottom: 1px dashed #eee;
            display: flex;
            align-items: center;
        }
        .category-item:last-child {
            border-bottom: none;
        }
        .category-item a {
            color: #333;
            text-decoration: none;
            flex: 1;
            font-size: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
        }
        .category-item a:hover {
            color: #0066cc;
        }
        .category-date {
            color: #999;
            font-size: 13px;
            margin-left: 15px;
        }

        /* 轮播图控制样式 */
        .slider-controls {
            position: absolute;
            bottom: 15px;
            right: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 2;
        }
        .slider-dots {
            display: flex;
            gap: 8px;
        }
        .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255,255,255,0.5);
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .dot.active {
            background: white;
            transform: scale(1.2);
        }
        .slider-buttons {
            display: flex;
            gap: 5px;
        }
        .arrow {
            width: 24px;
            height: 24px;
            background: rgba(0,0,0,0.3);
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            text-decoration: none;
        }
        .arrow:hover {
            background: rgba(0,0,0,0.6);
        }

        .more-link {
            color: #666;
            text-decoration: none;
            font-size: 14px;
        }

        .more-link:hover {
            color: #0066cc;
        }

        .article-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px 20px;
            margin: 0;
            list-style: none;
            height: calc(100% - 52px);
        }

        .article-list::-webkit-scrollbar {
            width: 4px;
        }

        .article-list::-webkit-scrollbar-thumb {
            background-color: #ddd;
            border-radius: 2px;
        }

        .article-list::-webkit-scrollbar-track {
            background-color: #f5f5f5;
        }

        .article-list li {
            padding: 12px 0;
            border-bottom: 1px dashed #eee;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            width: 100%;
        }

        .article-list li:last-child {
            border-bottom: none;
        }

        .article-list a {
            color: #333;
            text-decoration: none;
            font-size: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
            margin-right: 15px;
            width: calc(100% - 60px); /* 减去日期的宽度和margin */
            display: block;
        }

        .article-list a:hover {
            color: #0066cc;
        }

        .article-date {
            color: #999;
            font-size: 13px;
            width: 45px;
            text-align: right;
            flex-shrink: 0;
        }

        .category-header {
            padding: 15px 20px;
            border-bottom: 2px solid #0066cc;
            margin: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 52px;
            box-sizing: border-box;
        }

        .category-header h3 {
            margin: 0;
            color: #333;
            font-size: 18px;
            font-weight: bold;
        }

        .no-data {
            text-align: center;
            color: #999;
            padding: 20px 0;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php'; ?>

    <!-- 主要内容区 -->
    <div class="main-content">
        <!-- 上方内容：轮播图和要闻动态 -->
        <div class="top-content">
            <!-- 轮播图 -->
            <div class="slider-container">
                <div class="slider">
                    <?php foreach($slides as $index => $slide): ?>
                        <div class="slide">
                            <img src="<?php echo htmlspecialchars($slide['image']); ?>" alt="<?php echo htmlspecialchars($slide['title']); ?>">
                            <div class="slide-caption">
                                <h3 class="slide-title"><?php echo htmlspecialchars($slide['title']); ?></h3>
                                <p class="slide-description">
                                    <?php echo htmlspecialchars($slide['description']); ?>
                                </p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="slider-controls">
                    <div class="slider-dots">
                        <?php for($i = 0; $i < count($slides); $i++): ?>
                            <span class="dot <?php echo $i === 0 ? 'active' : ''; ?>"></span>
                        <?php endfor; ?>
                    </div>
                    <div class="slider-buttons">
                        <a href="javascript:;" class="arrow prev">←</a>
                        <a href="javascript:;" class="arrow next">→</a>
                    </div>
                </div>
            </div>

            <!-- 要闻动态 -->
            <div class="news-container">
                <div class="news-header">
                    <span class="news-title">要闻动态</span>
                    <a href="category.php?name=要闻动态" class="news-more">更多 ></a>
                </div>
                <ul class="news-list">
                    <?php if ($news_result && $news_result->num_rows > 0): ?>
                        <?php while($article = $news_result->fetch_assoc()): ?>
                            <li class="news-item">
                                <a href="article.php?id=<?php echo $article['id']; ?>">
                                    <?php echo htmlspecialchars($article['title']); ?>
                                </a>
                                <span class="news-date">
                                    <?php echo date('m-d', strtotime($article['created_at'])); ?>
                                </span>
                            </li>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <li class="news-item">暂无通知</li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>

        <!-- 下方内容：三列布局 -->
        <div class="bottom-content">
            <!-- 左侧两列 -->
            <div class="left-columns">
                <!-- 通知公告 -->
                <div class="category-column">
                    <div class="category-header">
                        <h3>通知公告</h3>
                        <a href="/category.php?id=2" class="more-link">更多 &gt;</a>
                    </div>
                    <ul class="article-list">
                        <?php
                        $notice_sql = "SELECT id, title, created_at FROM articles WHERE category_id = 2 ORDER BY created_at DESC LIMIT 8";
                        $notice_result = $conn->query($notice_sql);
                        if ($notice_result && $notice_result->num_rows > 0) {
                            while ($article = $notice_result->fetch_assoc()) {
                                echo '<li>';
                                echo '<a href="/article.php?id=' . $article['id'] . '">' . htmlspecialchars($article['title']) . '</a>';
                                echo '<span class="article-date">' . date('m-d', strtotime($article['created_at'])) . '</span>';
                                echo '</li>';
                            }
                        } else {
                            echo '<li class="no-data">暂无文章</li>';
                        }
                        ?>
                    </ul>
                </div>

                <!-- 政策文件 -->
                <div class="category-column">
                    <div class="category-header">
                        <h3>政策文件</h3>
                        <a href="/category.php?id=4" class="more-link">更多 &gt;</a>
                    </div>
                    <ul class="article-list">
                        <?php
                        $policy_sql = "SELECT id, title, created_at FROM articles WHERE category_id = 4 ORDER BY created_at DESC LIMIT 8";
                        $policy_result = $conn->query($policy_sql);
                        if ($policy_result && $policy_result->num_rows > 0) {
                            while ($article = $policy_result->fetch_assoc()) {
                                echo '<li>';
                                echo '<a href="/article.php?id=' . $article['id'] . '">' . htmlspecialchars($article['title']) . '</a>';
                                echo '<span class="article-date">' . date('m-d', strtotime($article['created_at'])) . '</span>';
                                echo '</li>';
                            }
                        } else {
                            echo '<li class="no-data">暂无文章</li>';
                        }
                        ?>
                    </ul>
                </div>
            </div>

            <!-- 右侧：漏洞预警 -->
            <div class="category-column">
                <div class="category-header">
                    <h3>漏洞预警</h3>
                    <a href="/category.php?id=3" class="more-link">更多 &gt;</a>
                </div>
                <ul class="article-list">
                    <?php
                    $vulnerability_sql = "SELECT id, title, created_at FROM articles WHERE category_id = 3 ORDER BY created_at DESC LIMIT 8";
                    $vulnerability_result = $conn->query($vulnerability_sql);
                    if ($vulnerability_result && $vulnerability_result->num_rows > 0) {
                        while ($article = $vulnerability_result->fetch_assoc()) {
                            echo '<li>';
                            echo '<a href="/article.php?id=' . $article['id'] . '">' . htmlspecialchars($article['title']) . '</a>';
                            echo '<span class="article-date">' . date('m-d', strtotime($article['created_at'])) . '</span>';
                            echo '</li>';
                        }
                    } else {
                        echo '<li class="no-data">暂无文章</li>';
                    }
                    ?>
                </ul>
            </div>
        </div>
    </div>

    <!-- 分类文章展示 -->
    <div class="categories-container">
        <?php 
        if ($categories_result && $categories_result->num_rows > 0):
            while($category = $categories_result->fetch_assoc()):
                if ($category['name'] !== '要闻动态'):
                    $articles = $category_articles[$category['id']] ?? null;
        ?>
            <div class="category-section">
                <div class="category-header">
                    <span class="category-title"><?php echo htmlspecialchars($category['name']); ?></span>
                    <a href="category.php?id=<?php echo $category['id']; ?>" class="category-more">更多 ></a>
                </div>
                <ul class="category-list">
                    <?php if ($articles && !empty($articles['articles'])): ?>
                        <?php foreach($articles['articles'] as $article): ?>
                            <li class="category-item">
                                <a href="article.php?id=<?php echo $article['id']; ?>">
                                    <?php echo htmlspecialchars($article['title']); ?>
                                </a>
                                <span class="category-date">
                                    <?php echo date('m-d', strtotime($article['created_at'])); ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="category-item">暂无文章</li>
                    <?php endif; ?>
                </ul>
            </div>
        <?php 
                endif;
            endwhile;
        endif; 
        ?>
    </div>

    <script>
        // 轮播图功能
        document.addEventListener('DOMContentLoaded', function() {
            const slider = document.querySelector('.slider');
            const slides = document.querySelectorAll('.slide');
            const dots = document.querySelectorAll('.dot');
            const prevBtn = document.querySelector('.arrow.prev');
            const nextBtn = document.querySelector('.arrow.next');
            let currentSlide = 0;
            const slideCount = dots.length;
            const SLIDE_INTERVAL = 3000; // 3秒切换一次
            let slideInterval;

            // 根据实际幻灯片数量设置slider宽度
            slider.style.width = `${slideCount * 100}%`;
            slides.forEach(slide => {
                slide.style.width = `${100 / slideCount}%`;
            });

            function showSlide(index) {
                if (index < 0) index = slideCount - 1;
                if (index >= slideCount) index = 0;
                currentSlide = index;
                
                const offset = index * (100 / slideCount);
                slider.style.transform = `translateX(-${offset}%)`;
                dots.forEach(dot => dot.classList.remove('active'));
                dots[index].classList.add('active');
            }

            function startAutoSlide() {
                if (slideInterval) {
                    clearInterval(slideInterval);
                }
                slideInterval = setInterval(() => {
                    showSlide(currentSlide + 1);
                }, SLIDE_INTERVAL);
            }

            function stopAutoSlide() {
                if (slideInterval) {
                    clearInterval(slideInterval);
                    slideInterval = null;
                }
            }

            // 点击圆点切换
            dots.forEach((dot, index) => {
                dot.addEventListener('click', () => {
                    showSlide(index);
                    stopAutoSlide();
                    startAutoSlide();
                });
            });

            // 点击箭头切换
            prevBtn.addEventListener('click', () => {
                showSlide(currentSlide - 1);
                stopAutoSlide();
                startAutoSlide();
            });
            
            nextBtn.addEventListener('click', () => {
                showSlide(currentSlide + 1);
                stopAutoSlide();
                startAutoSlide();
            });

            // 鼠标悬停时暂停自动轮播
            slider.parentElement.addEventListener('mouseenter', stopAutoSlide);

            // 鼠标离开时恢复自动轮播
            slider.parentElement.addEventListener('mouseleave', startAutoSlide);

            // 初始化第一张幻灯片
            showSlide(0);

            // 初始化自动轮播
            if (slideCount > 1) {
                startAutoSlide();
            }
        });
    </script>

    <?php
    define('IN_SITE', true);
    include 'includes/footer.php';
    ?>
</body>
</html>
<?php $conn->close(); ?> 