<?php








require_once __DIR__ . '/../common.php';






function load_common_sidebar_data(PDO $pdo): array
{
    ensure_new_sites_style_key_column($pdo);

    
    
    $cacheTtlSeconds = 30;
    $cacheDir = BASE_PATH . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'sidebar';
    $cacheKey = 'sidebar_data_v3';
    $cacheFile = $cacheDir . DIRECTORY_SEPARATOR . sha1($cacheKey) . '.json';

    if ($cacheTtlSeconds > 0 && is_file($cacheFile)) {
        $mtime = @filemtime($cacheFile);
        if (is_int($mtime) && $mtime > 0 && (time() - $mtime) < $cacheTtlSeconds) {
            $raw = @file_get_contents($cacheFile);
            if (is_string($raw) && $raw !== '') {
                $cached = json_decode($raw, true);
                if (is_array($cached)) {
                    return $cached;
                }
            }
        }
    }

    $categories = [];
    $newSites = [];
    $importantFriendLinks = [];
    $mostLikedArticles = [];
    $recentComments = [];
    $hotArticles = [];
    $tags = [];
    $statsToday = ['pv' => 0, 'uv' => 0];
    $statsTotal = ['pv' => 0, 'articles' => 0, 'comments' => 0, 'runtime_days' => 1];

    
    
    $contactEmail         = trim(get_setting('contact.email', ''));
    $contactQq            = trim(get_setting('contact.qq', ''));
    $contactWechat        = trim(get_setting('contact.wechat', ''));
    $contactTelegram      = trim(get_setting('contact.telegram', ''));
    $contactTelegramGroup = trim(get_setting('contact.telegram_group', ''));
    $contactQqGroup       = trim(get_setting('contact.qq_group', ''));
    $contactWhatsapp      = trim(get_setting('contact.whatsapp', ''));
    
    $contactIm            = trim(get_setting('contact.im', ''));

    $contactItems = [];
    $pushContact = function (string $icon, string $label, string $value) use (&$contactItems): void {
        $value = trim($value);
        if ($value === '') {
            return;
        }
        $contactItems[] = [
            'icon' => $icon,
            'label' => $label,
            'value' => $value,
        ];
    };

    $pushContact('@', '邮箱', $contactEmail);
    $pushContact('Q', 'QQ', $contactQq);
    $pushContact('W', '微信', $contactWechat);
    $pushContact('T', 'Telegram', $contactTelegram);
    $pushContact('TG', 'Telegram群', $contactTelegramGroup);
    $pushContact('QG', 'QQ群', $contactQqGroup);
    $pushContact('WA', 'WhatsApp', $contactWhatsapp);
    if (!$contactItems) {
        $pushContact('IM', '即时通讯', $contactIm);
    }

    $showContactCard         = get_setting('sidebar.show_contact', '1') === '1';
    $showImportantLinksCard  = get_setting('sidebar.show_important_links', '1') === '1';
    $showNewSitesCard        = get_setting('sidebar.show_new_sites', '1') === '1';
    $titleContactCard        = get_setting('sidebar.title_contact', '联系方式');
    $titleImportantLinksCard = get_setting('sidebar.title_important_links', '重要友链');
    $titleNewSitesCard       = get_setting('sidebar.title_new_sites', '最新网址');
    $sidebarOrderContact        = (int)get_setting('sidebar.order_contact', '10');
    $sidebarOrderImportantLinks = (int)get_setting('sidebar.order_important_links', '20');
    $sidebarOrderNewSites       = (int)get_setting('sidebar.order_new_sites', '30');
    $sidebarOrderTags           = (int)get_setting('sidebar.order_tags', '40');

    try {
        $sql = <<<SQL
SELECT c.id,
       c.name,
       c.slug,
       c.sort_order,
       c.icon_path,
       COALESCE(a.cnt, 0) AS article_count
FROM categories c
LEFT JOIN (
    SELECT category_id, COUNT(*) AS cnt
    FROM articles
    WHERE status = 'published'
    GROUP BY category_id
) a ON a.category_id = c.id
ORDER BY c.sort_order DESC, c.id ASC
SQL;
        $categories = $pdo->query($sql)->fetchAll() ?: [];
    } catch (Throwable $e) {
        $categories = [];
    }

    try {
        $stmt = $pdo->query("SELECT name, url, style_key FROM new_sites WHERE is_active = 1 ORDER BY sort_order DESC, id DESC");
        $newSites = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $newSites = [];
    }

    try {
        $stmt = $pdo->query("
            SELECT name, url
            FROM friend_links
            WHERE status = 'approved'
            ORDER BY sort_order DESC, id DESC
            LIMIT 5
        ");
        $importantFriendLinks = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $importantFriendLinks = [];
    }

    try {
        $stmt = $pdo->query("
            SELECT id, title, like_count
            FROM articles
            WHERE status = 'published'
            ORDER BY like_count DESC, published_at DESC, id DESC
            LIMIT 5
        ");
        $mostLikedArticles = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $mostLikedArticles = [];
    }

    try {
        $stmt = $pdo->query("
            SELECT id, title, view_count, like_count
            FROM articles
            WHERE status = 'published'
            ORDER BY view_count DESC, like_count DESC, published_at DESC, id DESC
            LIMIT 5
        ");
        $hotArticles = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $hotArticles = [];
    }

    try {
        $stmt = $pdo->query("
            SELECT c.content, c.is_guest, c.guest_name, u.nickname, a.title AS article_title
            FROM comments c
            LEFT JOIN users u ON u.id = c.user_id
            LEFT JOIN articles a ON a.id = c.article_id
            WHERE c.status = 'approved'
            ORDER BY c.created_at DESC
            LIMIT 5
        ");
        $recentComments = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $recentComments = [];
    }

    try {
        $stmt = $pdo->query("SELECT id, name FROM tags ORDER BY id DESC LIMIT 20");
        $tags = $stmt ? ($stmt->fetchAll() ?: []) : [];
    } catch (Throwable $e) {
        $tags = [];
    }

    try {
        $today = date('Y-m-d');
        $stmt  = $pdo->prepare("SELECT pv, uv FROM visit_daily WHERE date = :d");
        $stmt->execute([':d' => $today]);
        if ($row = $stmt->fetch()) {
            $statsToday['pv'] = (int)($row['pv'] ?? 0);
            $statsToday['uv'] = (int)($row['uv'] ?? 0);
        }
    } catch (Throwable $e) {
        $statsToday = ['pv' => 0, 'uv' => 0];
    }

    try {
        $stmt = $pdo->query("SELECT SUM(pv) AS pv_total FROM visit_daily");
        if ($stmt && ($row = $stmt->fetch())) {
            $statsTotal['pv'] = (int)($row['pv_total'] ?? 0);
        }
    } catch (Throwable $e) {
        $statsTotal = ['pv' => 0, 'articles' => 0, 'comments' => 0, 'runtime_days' => 1];
    }

    try {
        $stmt = $pdo->query("SELECT COUNT(*) AS c FROM articles WHERE status = 'published'");
        if ($stmt) {
            $statsTotal['articles'] = (int)($stmt->fetchColumn() ?: 0);
        }
    } catch (Throwable $e) {
        $statsTotal['articles'] = $statsTotal['articles'] ?? 0;
    }

    try {
        $stmt = $pdo->query("SELECT COUNT(*) AS c FROM comments WHERE status = 'approved'");
        if ($stmt) {
            $statsTotal['comments'] = (int)($stmt->fetchColumn() ?: 0);
        }
    } catch (Throwable $e) {
        $statsTotal['comments'] = $statsTotal['comments'] ?? 0;
    }

    
    $launchSetting = trim((string)get_setting('site.launch_date', ''));
    $launchTs = 0;
    if ($launchSetting !== '') {
        if (ctype_digit($launchSetting)) {
            $launchTs = (int)$launchSetting;
        } else {
            $ts = strtotime($launchSetting);
            if ($ts !== false) {
                $launchTs = $ts;
            }
        }
    }
    if ($launchTs <= 0) {
        $dbPath = BASE_PATH . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'blog.sqlite';
        $launchTs = is_file($dbPath) ? (int)@filemtime($dbPath) : 0;
    }
    if ($launchTs <= 0) {
        $launchTs = time();
    }
    $statsTotal['runtime_days'] = max(1, (int)floor((time() - $launchTs) / 86400) + 1);

    $result = [
        'categories' => $categories,
        'newSites' => $newSites,
        'importantFriendLinks' => $importantFriendLinks,
        'mostLikedArticles' => $mostLikedArticles,
        'recentComments' => $recentComments,
        'hotArticles' => $hotArticles,
        'tags' => $tags,
        'statsToday' => $statsToday,
        'statsTotal' => $statsTotal,
        'contactEmail' => $contactEmail,
        'contactIm' => $contactIm,
        'contactItems' => $contactItems,
        'showContactCard' => $showContactCard,
        'showImportantLinksCard' => $showImportantLinksCard,
        'showNewSitesCard' => $showNewSitesCard,
        'titleContactCard' => $titleContactCard,
        'titleImportantLinksCard' => $titleImportantLinksCard,
        'titleNewSitesCard' => $titleNewSitesCard,
        'sidebarOrderContact' => $sidebarOrderContact,
        'sidebarOrderImportantLinks' => $sidebarOrderImportantLinks,
        'sidebarOrderNewSites' => $sidebarOrderNewSites,
        'sidebarOrderTags' => $sidebarOrderTags,
    ];

    if ($cacheTtlSeconds > 0) {
        if (!is_dir($cacheDir)) {
            @mkdir($cacheDir, 0777, true);
        }
        try {
            @file_put_contents($cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE), LOCK_EX);
        } catch (Throwable $e) {
            
        }
    }

    return $result;
}
