<?php
/**
 * 栏目页
 * rh888av.com
 * SEO 优化：TDK 动态生成、面包屑导航、分页
 */

define('IN_APP', true);

require_once 'config_real.php';
require_once 'includes/common.php';

// 获取参数
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'latest';

if (!$id) {
    redirect('/');
}

// 获取分类信息
$category = getCategoryInfo($id);
if (!$category || $category['status'] != 1) {
    header('HTTP/1.1 404 Not Found');
    exit('分类不存在');
}

// 获取子分类
$children = getCategories($id);

// 获取分类路径（面包屑）
function getCategoryPath($id) {
    $path = [];
    while ($id > 0) {
        $cat = getCategoryInfo($id);
        if ($cat) {
            array_unshift($path, $cat);
            $id = $cat['pid'];
        } else {
            break;
        }
    }
    return $path;
}

$breadcrumb = getCategoryPath($id);

// 筛选条件
$where = "AND category_id IN (";
if ($children) {
    $cat_ids = [$id];
    foreach ($children as $child) {
        $cat_ids[] = $child['id'];
    }
    $where .= implode(',', $cat_ids);
} else {
    $where .= $id;
}
$where .= ")";

// 排序
switch ($sort) {
    case 'hits':
        $order = 'hits DESC';
        break;
    case 'score':
        $order = 'douban_score DESC';
        break;
    case 'year':
        $order = 'year DESC, created_at DESC';
        break;
    default:
        $order = 'created_at DESC';
}

// 分页
$per_page = getConfig('video_per_page', 24);
$total = getVideoCount($where);
$videos = getVideoList($where, $order, $per_page, $page);

// SEO 设置
$seo_title = $category['title'] ?: ($category['name'] . ' - ' . getConfig('site_name', 'RH888 影视'));
$seo_keywords = $category['keywords'] ?: ($category['name'] . ',在线' . $category['name'] . ',高清' . $category['name']);
$seo_description = $category['description'] ?: ('在线观看最新' . $category['name'] . '，' . getConfig('site_name') . '提供高清' . $category['name'] . '资源');

// 获取广告
$category_banner_ads = getAds('category_nav_bottom');
$category_card_ads = getAds('category_card');

// 分页 URL
$base_url = '/category.php?id=' . $id . '&sort=' . $sort . '&page={page}';
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    
    <!-- SEO -->
    <title><?php echo htmlSafe($seo_title); ?></title>
    <meta name="keywords" content="<?php echo htmlSafe($seo_keywords); ?>">
    <meta name="description" content="<?php echo htmlSafe($seo_description); ?>">
    
    <!-- 移动端优化 -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="applicable-device" content="pc,mobile">
    
    <!-- Canonical URL - 动态获取当前域名 -->
    <link rel="canonical" href="<?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . seoUrl('category', $id, $category['slug']); ?>">
    
    <!-- Favicon -->
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    
    <!-- 结构化数据 -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "CollectionPage",
        "name": "<?php echo htmlSafe($category['name']); ?>",
        "description": "<?php echo htmlSafe($seo_description); ?>"
    }
    </script>
    
    <!-- 样式 -->
    <link rel="stylesheet" href="/assets/css/style.css">
    
    <!-- 主题切换样式 -->
    <style>
        :root {
            --bg-body: #f5f5f5;
            --bg-card: #ffffff;
            --bg-header: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --text-primary: #333333;
            --text-secondary: #666666;
            --text-muted: #999999;
            --border-color: #e0e0e0;
            --shadow-card: 0 2px 10px rgba(0,0,0,0.08);
        }
        
        [data-theme="dark"] {
            --bg-body: #0f0f1a;
            --bg-card: #1a1a2e;
            --bg-header: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            --text-primary: #eaeaea;
            --text-secondary: #b0b0b0;
            --text-muted: #666666;
            --border-color: #2d2d44;
            --shadow-card: 0 2px 10px rgba(0,0,0,0.3);
        }
        
        body, .header, .section, .video-card, .footer {
            transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
        }
        
        .theme-toggle {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            transition: all 0.3s ease;
        }
        
        .theme-toggle:hover {
            transform: scale(1.1) rotate(15deg);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
        }
        
        .theme-toggle:active {
            transform: scale(0.95);
        }
        
        /* 栏目页标题居中 */
        .category-header {
            text-align: center;
            padding: 30px 0;
        }
        
        .category-header h1 {
            font-size: 36px;
            margin-bottom: 15px;
            color: var(--text-primary);
        }
        
        .category-header .category-desc {
            font-size: 16px;
            color: var(--text-secondary);
            margin-bottom: 20px;
        }
        
        /* 子分类居中，增加间距 */
        .sub-category {
            text-align: center;
            padding: 20px 0;
            background: var(--bg-card);
        }
        
        .sub-category-list {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .sub-cat-item {
            display: inline-block;
            padding: 10px 20px;
            background: var(--bg-body);
            color: var(--text-primary);
            border-radius: 8px;
            transition: all 0.3s ease;
            margin: 5px;
        }
        
        .sub-cat-item:hover,
        .sub-cat-item.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transform: translateY(-2px);
        }
        
        /* 筛选栏居中 */
        .filter-section {
            text-align: center;
            padding: 20px 0;
            background: var(--bg-body);
        }
        
        .filter-list {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .filter-label {
            font-weight: 600;
            color: var(--text-primary);
            margin-right: 10px;
        }
        
        .filter-item {
            display: inline-block;
            padding: 8px 16px;
            background: var(--bg-card);
            color: var(--text-primary);
            border-radius: 6px;
            transition: all 0.3s ease;
            margin: 3px;
        }
        
        .filter-item:hover,
        .filter-item.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 主题切换按钮 -->
    <button class="theme-toggle" id="themeToggle" title="切换主题" aria-label="切换主题">
        <span id="themeIcon">🌙</span>
    </button>
    <!-- 头部导航 -->
    <header class="header">
        <div class="container">
            <div class="header-inner">
                <div class="logo">
                    <a href="/" title="<?php echo htmlSafe(getConfig('site_name')); ?>">
                        <span class="logo-text"><?php echo htmlSafe(getConfig('site_name')); ?></span>
                    </a>
                </div>
                <nav class="nav">
                    <ul class="nav-list">
                        <li class="nav-item"><a href="/">首页</a></li>
                        <?php 
                        $all_categories = getCategories(0);
                        foreach ($all_categories as $cat): 
                        ?>
                        <li class="nav-item <?php echo $cat['id'] == $id ? 'active' : ''; ?>">
                            <a href="<?php echo seoUrl('category', $cat['id'], $cat['slug']); ?>">
                                <?php echo htmlSafe($cat['name']); ?>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </nav>
                <div class="search-box">
                    <form action="/search.php" method="get">
                        <input type="text" name="keyword" placeholder="搜索影片..." autocomplete="off">
                        <button type="submit" class="search-btn">搜索</button>
                    </form>
                </div>
                <button class="mobile-menu-btn" aria-label="菜单">
                    <span></span>
                    <span></span>
                    <span></span>
                </button>
            </div>
        </div>
    </header>

    <!-- 移动端导航 -->
    <div class="mobile-nav">
        <div class="mobile-nav-content">
            <ul>
                <li><a href="/">首页</a></li>
                <?php foreach ($all_categories as $cat): ?>
                <li><a href="<?php echo seoUrl('category', $cat['id'], $cat['slug']); ?>"><?php echo htmlSafe($cat['name']); ?></a></li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <!-- 主要内容 -->
    <main class="main">
        <!-- 栏目页横幅广告（导航栏下方） -->
     <?php if (!empty($category_banner_ads)): ?>
        <div class="nav-ad-container" style="text-align:center;padding:15px 0;background:var(--bg-card);box-shadow:var(--shadow-card);">
            <div class="container">
                <div style="margin:0 auto;max-width:960px;">
                    <?php foreach ($category_banner_ads as $ad): ?>
                        <?php echo nl2br(str_replace(['\r\n', '\r', '\n'], '', stripslashes($ad['code']))); ?>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="container">
            <!-- 面包屑导航 -->
            <nav class="breadcrumb">
                <a href="/">首页</a>
                <?php foreach ($breadcrumb as $index => $cat): ?>
                <span class="separator">/</span>
                <?php if ($index == count($breadcrumb) - 1): ?>
                <span class="current"><?php echo htmlSafe($cat['name']); ?></span>
                <?php else: ?>
                <a href="<?php echo seoUrl('category', $cat['id'], $cat['slug']); ?>">
                    <?php echo htmlSafe($cat['name']); ?>
                </a>
                <?php endif; ?>
                <?php endforeach; ?>
            </nav>
        </div>

        <!-- 分类标题 -->
        <section class="category-header">
            <div class="container">
                <h1><?php echo htmlSafe($category['name']); ?></h1>
                <?php if ($category['description']): ?>
                <p class="category-desc"><?php echo htmlSafe($category['description']); ?></p>
                <?php endif; ?>
            </div>
        </section>

        <!-- 子分类 -->
        <?php if ($children): ?>
        <section class="sub-category">
            <div class="container">
                <div class="sub-category-list">
                    <a href="<?php echo seoUrl('category', $id, $category['slug']); ?>" class="sub-cat-item <?php echo !$sort ? 'active' : ''; ?>">
                        全部
                    </a>
                    <?php foreach ($children as $child): ?>
                    <a href="<?php echo seoUrl('category', $child['id'], $child['slug']); ?>" class="sub-cat-item">
                        <?php echo htmlSafe($child['name']); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- 筛选排序 -->
        <section class="filter-section">
            <div class="container">
                <div class="filter-list">
                    <span class="filter-label">排序：</span>
                    <a href="?id=<?php echo $id; ?>&sort=latest" class="filter-item <?php echo $sort == 'latest' ? 'active' : ''; ?>">最新</a>
                    <a href="?id=<?php echo $id; ?>&sort=hits" class="filter-item <?php echo $sort == 'hits' ? 'active' : ''; ?>">最热</a>
                    <a href="?id=<?php echo $id; ?>&sort=score" class="filter-item <?php echo $sort == 'score' ? 'active' : ''; ?>">评分</a>
                    <a href="?id=<?php echo $id; ?>&sort=year" class="filter-item <?php echo $sort == 'year' ? 'active' : ''; ?>">年份</a>
                </div>
            </div>
        </section>

        <!-- 视频列表 -->
        <section class="section">
            <div class="container">
                <div class="section-header">
                    <h2 class="section-title">
                        <span class="title-icon">☀</span>
                        <?php echo htmlSafe($category['name']); ?>列表
                        <span class="total-count">共 <?php echo $total; ?> 部</span>
                    </h2>
                </div>
                
                <?php if ($videos): ?>
                <div class="video-grid">
                    <?php
                    $ad_index = 0;
                    $videos_per_ad = 4; // 每 4 个视频显示 1 个广告
                    foreach ($videos as $index => $video):
                        // 从第 1 个开始，每 4 个视频插入广告
                        if ($index % $videos_per_ad == 0 && !empty($category_card_ads)):
                            $ad = $category_card_ads[$ad_index % count($category_card_ads)];
                    ?>
                    <!-- 栏目页卡片广告 -->
                    <div class="video-card ad-card">
                        <a href="<?php echo !empty($ad['link']) ? htmlSafe($ad['link']) : '#'; ?>" class="video-cover" style="background:#f0f0f0;">
                            <?php echo str_replace(['\\r\\n', '\\r', '\\n', '\r\n', '\r', '\n', 'rn'], '', stripslashes($ad['code'])); ?>
                        </a>
                        <div class="video-info">
                            <h3 class="video-title">
                                <a href="<?php echo !empty($ad['link']) ? htmlSafe($ad['link']) : '#'; ?>">
                                    <?php echo htmlSafe(!empty($ad['title']) ? $ad['title'] : '广告推广'); ?>
                                </a>
                            </h3>
                            <p class="video-meta">
                                <span class="year">广告</span>
                                <span class="score">查看详情</span>
                            </p>
                        </div>
                    </div>
                    <?php
                            $ad_index++;
                        endif;
                    ?>
                    <div class="video-card">
                        <a href="<?php echo seoUrl('video', $video['id'], $video['slug']); ?>" class="video-cover">
                            <img src="<?php echo htmlSafe($video['cover'] ?: '/assets/images/default-cover.jpg'); ?>" 
                                 alt="<?php echo htmlSafe($video['title']); ?>"
                                 loading="lazy">
                            <div class="video-overlay">
                                <span class="play-icon">▶</span>
                            </div>
                        </a>
                        <div class="video-info">
                            <h3 class="video-title">
                                <a href="<?php echo seoUrl('video', $video['id'], $video['slug']); ?>">
                                    <?php echo htmlSafe(cutStr($video['title'], 18)); ?>
                                </a>
                            </h3>
                            <p class="video-desc"><?php echo htmlSafe(cutStr($video['description'], 40)); ?></p>
                            <p class="video-meta">
                                <span class="year"><?php echo $video['year']; ?></span>
                                <span class="score">评分：<?php echo $video['douban_score']; ?></span>
                            </p>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- 分页 -->
                <?php if ($total > $per_page): ?>
                <div class="pagination-container">
                    <?php echo createPagination($page, $total, $per_page, $base_url); ?>
                </div>
                <?php endif; ?>
                
                <?php else: ?>
                <div class="empty-state">
                    <div class="empty-icon">🎬</div>
                    <p>暂无影片</p>
                </div>
                <?php endif; ?>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <div class="footer-links">
                    <a href="/about.html">关于我们</a>
                    <a href="/contact.html">联系我们</a>
                    <a href="/copyright.html">版权声明</a>
                </div>
                <div class="footer-info">
                    <p>© <?php echo date('Y'); ?> <?php echo htmlSafe(getConfig('site_name')); ?> All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </footer>

    <!-- 返回顶部 -->
    <a href="#" class="back-to-top" aria-label="返回顶部">↑</a>

    <!-- 统计代码 -->
    <?php 
    $site_stat = getConfig('site_stat', '');
    if (!empty($site_stat)) {
        echo $site_stat;
    }
    ?>

    <!-- JavaScript -->
    <script src="/assets/js/main.js"></script>
    <!-- 主题切换脚本 -->
    <script>
    (function() {
        const themeToggle = document.getElementById('themeToggle');
        const themeIcon = document.getElementById('themeIcon');
        const THEME_KEY = 'frontend_theme';
        
        function getCurrentHour() {
            return new Date().getHours();
        }
        
        function isDaytime() {
            const hour = getCurrentHour();
            return hour >= 6 && hour < 18;
        }
        
        function setTheme(theme) {
            if (theme === 'dark') {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeIcon.textContent = '☀️';
                themeToggle.title = '切换到浅色主题';
            } else {
                document.documentElement.removeAttribute('data-theme');
                themeIcon.textContent = '🌙';
                themeToggle.title = '切换到深色主题';
            }
        }
        
        function autoTheme() {
            const theme = isDaytime() ? 'light' : 'dark';
            setTheme(theme);
        }
        
        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            setTheme(newTheme);
            localStorage.setItem(THEME_KEY, newTheme);
        }
        
        function initTheme() {
            const savedTheme = localStorage.getItem(THEME_KEY);
            if (savedTheme) {
                setTheme(savedTheme);
            } else {
                autoTheme();
            }
            setInterval(() => {
                if (!localStorage.getItem(THEME_KEY)) {
                    autoTheme();
                }
            }, 3600000);
        }
        
        if (themeToggle) {
            themeToggle.addEventListener('click', toggleTheme);
        }
        
        initTheme();
    })();
    </script>
</body>
</html>
