<?php
// 启用错误报告（仅用于调试，生产环境请注释掉这两行）
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 添加自动创建必要目录的功能
$dirs_to_check = array(
    'data', 
    'data/icons', 
    'uploads', 
    'uploads/backgrounds'
);

foreach ($dirs_to_check as $dir) {
    if (!file_exists($dir) && !is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

require_once 'config/config.php';
require_once 'includes/functions.php';

try {
    // 获取网站设置
    $settings = get_site_settings();
    
    // 确保设置数组中包含所有必要的键
    $required_keys = array('site_title', 'site_description', 'announcement', 'footer_text');
    foreach ($required_keys as $key) {
        if (!isset($settings[$key])) {
            $settings[$key] = '';
        }
    }
    
    // 获取所有分类和链接
    $categories = get_all_categories();
    
    // 记录访问
    log_visit('index');
} catch (Exception $e) {
    // 记录错误
    error_log("Error in index.php: " . $e->getMessage());
    
    // 使用默认设置
    $settings = array(
        'site_title' => '导航网站',
        'site_description' => '一个简洁优雅的个人导航网站',
        'announcement' => '欢迎使用导航网站',
        'footer_text' => '© ' . date('Y') . ' 导航网站 All Rights Reserved'
    );
    $categories = array();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($settings['site_title']); ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($settings['site_description']); ?>">
    <!-- CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/all.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <style>
        body {
            <?php if (!empty($settings['background_image'])): ?>
            background-image: url('<?php echo htmlspecialchars($settings['background_image']); ?>');
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            min-height: 100vh;
            <?php endif; ?>
        }
        .site-card {
            text-decoration: none;
            display: block;
            height: 100%;
        }
        .site-card:hover {
            text-decoration: none;
        }
        .card {
            height: 100%;
            transition: all 0.3s;
            border: 1px solid rgba(0,0,0,.125);
        }
        .card:hover {
            transform: translateY(-6px);
            box-shadow: 0 2px 10px rgba(0,0,0,0.15);
        }
        .card-body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 1rem;
            text-align: center;
        }
        .icon-wrapper {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 4px;  
        }
        .site-icon {
            width: 32px;
            height: 32px;
            margin-bottom: 8px;
            border-radius: 4px;
            object-fit: contain;
        }
        .site-title {
            font-size: 14px;
            color: #333;
            margin: 0;
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .category-title {
            margin: 20px 0;
            font-size: 16px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .row {
            display: flex;
            flex-wrap: wrap;
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .alert {
            padding: 8px;
            margin-top: 70px;
            margin-bottom: 30px;
            height: 36px;
            line-height: 20px;
            display: flex;
            align-items: center;
            font-size: 14px;
        }
        .alert i {
            margin-right: 8px;
        }

        /* 搜索框样式 */
        .search-container {
            margin: 20px auto;
            max-width: 600px;
            padding: 15px;
        }
        .search-box {
            display: flex;
            gap: 10px;
            background: #fff;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .search-input {
            flex: 1;
            border: none;
            outline: none;
            font-size: 16px;
            padding: 8px;
            background: transparent;
        }
        .search-btn {
            background: #4285f4;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .search-btn:hover {
            background: #3367d6;
        }

        /* 百度服务快捷方式样式 */
        .baidu-services {
            padding: 15px 0;
            max-width: 800px;
            margin: 0 auto;
        }
        .baidu-services .card {
            height: 50px;
            border: 1px solid #e6e6e6;
            background: #fff;
            transition: all 0.3s ease;
        }
        .baidu-services .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #4285f4;
        }
        .baidu-services .card-body {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 8px;
        }
        .baidu-services .fas {
            color: #4285f4;
            font-size: 20px;
            margin: 0;
        }
        .baidu-services span {
            font-size: 13px;
            color: #333;
            margin: 0;
        }

        /* 页脚样式 */
        .footer {
            padding: 20px 0;
            text-align: center;
            background: transparent;
            color: rgba(0, 0, 0, 0.7);
        }
        .theme-dark .footer {
            color: rgba(255, 255, 255, 0.7);
        }
        .container-fluid {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            background: transparent;
        }
        .main-content {
            flex: 1;
            padding-bottom: 20px;
        }
        .navbar {
            width: 100%;
            padding: 30px 0;
            height: auto;
        }
        .navbar .container {
            position: relative;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }
        .navbar-brand {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            margin: 0;
            z-index: 1;
            font-size: 20px;
            padding: 10px 15px;
            margin: 0;
            height: auto;
            line-height: 1.5;
            white-space: normal;
        }
        .navbar-toggler {
            z-index: 2;
        }
    </style>
</head>
<body class="theme-light">
    <div class="container-fluid p-0">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top">
            <div class="container text-center">
                <a class="navbar-brand w-100" href="#"><?php echo htmlspecialchars($settings['site_title']); ?></a>
            </div>
        </nav>

        <?php if (!empty($settings['announcement'])): ?>
        <div class="container">
            <div class="alert alert-info">
                <i class="fas fa-bullhorn"></i>
                <?php echo htmlspecialchars($settings['announcement']); ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- 搜索框 -->
        <div class="container">
            <div class="search-container">
                <form class="search-box" action="https://www.baidu.com/s" method="get" target="_blank">
                    <input type="text" name="wd" class="search-input" placeholder="输入关键词搜索..." autocomplete="off">
                    <button type="submit" class="search-btn">
                        <i class="fas fa-search me-1"></i>搜索
                    </button>
                </form>
            </div>

            <!-- 百度服务快捷方式 -->
            <div class="baidu-services">
                <div class="row row-cols-2 row-cols-md-4 row-cols-lg-6 g-3">
                    <!-- 百度地图 -->
                    <div class="col">
                        <a href="https://map.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-map-marked-alt"></i>
                                <span>地图</span>
                            </div>
                        </a>
                    </div>
                    
                    <!-- 百度贴吧 -->
                    <div class="col">
                        <a href="https://tieba.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-comments"></i>
                                <span>贴吧</span>
                            </div>
                        </a>
                    </div>
                    
                    <!-- 百度图片 -->
                    <div class="col">
                        <a href="https://image.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-images"></i>
                                <span>图片</span>
                            </div>
                        </a>
                    </div>
                    
                    <!-- 百度视频 -->
                    <div class="col">
                        <a href="https://v.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-video"></i>
                                <span>视频</span>
                            </div>
                        </a>
                    </div>
                    
                    <!-- 百度网盘 -->
                    <div class="col">
                        <a href="https://pan.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-cloud"></i>
                                <span>网盘</span>
                            </div>
                        </a>
                    </div>
                    
                    <!-- 百度文库 -->
                    <div class="col">
                        <a href="https://wenku.baidu.com" target="_blank" class="card h-100 text-decoration-none">
                            <div class="card-body">
                                <i class="fas fa-book"></i>
                                <span>文库</span>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要内容区 -->
        <div class="container main-content">
            <?php 
            $conn = db_connect();
            $categories = $conn->query("SELECT * FROM categories ORDER BY sort_order ASC, id ASC");

            $order_file = 'data/link_order.json';
            $order_data = [];
            if (file_exists($order_file)) {
                $order_data = json_decode(file_get_contents($order_file), true) ?? [];
            }

            $links_query = "SELECT l.*, c.name as category_name FROM links l LEFT JOIN categories c ON l.category_id = c.id";
            $links_result = $conn->query($links_query);

            $links_by_category = [];
            while ($link = $links_result->fetch_assoc()) {
                $category_id = $link['category_id'];
                if (!isset($links_by_category[$category_id])) {
                    $links_by_category[$category_id] = [];
                }
                $links_by_category[$category_id][$link['id']] = $link;
            }

            foreach ($links_by_category as $category_id => &$category_links) {
                $current_order = $order_data[$category_id] ?? [];
                
                $sorted_links = [];
                foreach ($current_order as $id) {
                    if (isset($category_links[$id])) {
                        $sorted_links[] = $category_links[$id];
                        unset($category_links[$id]);
                    }
                }
                
                $category_links = array_merge($sorted_links, array_values($category_links));
            }
            unset($category_links);

            foreach ($categories as $category): ?>
            <div class="category-section mb-4">
                <h2 class="category-title">
                    <?php echo htmlspecialchars($category['name']); ?>
                </h2>
                <div class="row row-cols-2 row-cols-md-4 row-cols-lg-6 g-3">
                    <?php 
                    $category_id = $category['id'];
                    if (isset($links_by_category[$category_id])) {
                        foreach ($links_by_category[$category_id] as $link): 
                    ?>
                    <div class="col">
                        <a href="<?php echo htmlspecialchars($link['url']); ?>" target="_blank" class="site-card">
                            <div class="card">
                                <div class="card-body">
                                    <?php
                                    $domain = parse_url($link['url'], PHP_URL_HOST);
                                    $icon_urls = [
                                        "https://api.iowen.cn/favicon/{$domain}.png",
                                        "https://favicon.cccyun.cc/{$domain}",
                                        "https://{$domain}/favicon.ico",
                                        "https://{$domain}/favicon.png"
                                    ];
                                    ?>
                                    <img src="<?php echo $icon_urls[0]; ?>" 
                                         class="site-icon" 
                                         alt="<?php echo htmlspecialchars($link['title']); ?>"
                                         onerror="if (this.src !== '<?php echo $icon_urls[1]; ?>') this.src = '<?php echo $icon_urls[1]; ?>'; 
                                                 else if (this.src !== '<?php echo $icon_urls[2]; ?>') this.src = '<?php echo $icon_urls[2]; ?>'; 
                                                 else if (this.src !== '<?php echo $icon_urls[3]; ?>') this.src = '<?php echo $icon_urls[3]; ?>'; 
                                                 else this.src='assets/images/default-icon.png';">
                                    <span class="site-title"><?php echo htmlspecialchars($link['title']); ?></span>
                                </div>
                            </div>
                        </a>
                    </div>
                    <?php 
                        endforeach;
                    }
                    ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- 页脚 -->
        <footer class="footer mt-auto">
            <div class="container">
                <p class="mb-0"><?php echo htmlspecialchars($settings['footer_text']); ?></p>
            </div>
        </footer>
    </div>

    <!-- JavaScript -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php $conn->close(); ?>
