<?php
if (!defined('__TYPECHO_ROOT_DIR__'))
    exit;

// ==================== 通用功能模块 ====================
// 包含：主题初始化、配置管理、CDN、配色、版本检查

// 主题初始化钩子
function themeInit($archive)
{
    Helper::options()->commentsAntiSpam = false;

    // 修复加密文章 PJAX 兼容性
    if ($archive->is('single') && $archive->hidden && $archive->request->isAjax()) {
        $archive->response->setStatus(200);
    }

    // AJAX 接口：获取 Token URL
    if ($archive->is('post') && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['type']) && $_POST['type'] === 'getTokenUrl') {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['tokenUrl' => Typecho_Widget::widget('Widget_Security')->getTokenUrl($archive->permalink)]);
        exit;
    }

    // AJAX 接口：检查文章是否仍为加密状态
    if ($archive->is('post') && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['type']) && $_POST['type'] === 'checkPassword') {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['hidden' => $archive->hidden]);
        exit;
    }
}

// 获取配色方案
function getColorScheme()
{
    $colorScheme = Typecho_Widget::widget('Widget_Options')->colorScheme;
    return $colorScheme;
}

// 静态资源 URL 管理
function resolveStaticURL($path)
{
    $options = Typecho_Widget::widget('Widget_Options');
    $staticCdn = $options->staticCdn;

    $staticMap = [
        'local' => [
            'medium-zoom.min.js' => $options->themeUrl . '/js/lib/medium-zoom.min.js',
            'Swup.umd.min.js' => $options->themeUrl . '/js/lib/Swup/Swup.umd.min.js',
        ],
        'bootcdn' => [
            'medium-zoom.min.js' => "https://cdn.bootcdn.net/ajax/libs/medium-zoom/1.1.0/medium-zoom.min.js",
            'Swup.umd.min.js' => "https://cdn.bootcdn.net/ajax/libs/swup/4.8.2/Swup.umd.min.js",
        ],
        "cdnjs" => [
            'medium-zoom.min.js' => "https://cdnjs.cloudflare.com/ajax/libs/medium-zoom/1.1.0/medium-zoom.min.js",
            'Swup.umd.min.js' => "https://cdnjs.cloudflare.com/ajax/libs/swup/4.8.2/Swup.umd.min.js",
        ]
    ];

    if ($staticCdn === 'local') {
        return $staticMap['local'][$path];
    }

    if (isset($staticMap[$staticCdn][$path])) {
        return $staticMap[$staticCdn][$path];
    }

    return $staticMap['local'][$path];
}

function getStaticURL($path)
{
    echo resolveStaticURL($path);
}

// 生成动态 CSS
function generateDynamicCSS()
{
    $colorScheme = getColorScheme();

    $colorMap = [
        'pink' => ['theme' => '#ea868f', 'hover' => '#d1606e'],
        'green' => ['theme' => '#5fae8a', 'hover' => '#3f8f6a'],
        'blue' => ['theme' => '#6482db', 'hover' => '#4f6fdc'],
        'yellow' => ['theme' => '#e5b96e', 'hover' => '#cfa24d'],
        'red' => ['theme' => '#cd575f', 'hover' => '#b84a4a'],
        'purple' => ['theme' => '#8f7acb', 'hover' => '#6d5fb3'],
        'cyan' => ['theme' => '#5fb3b8', 'hover' => '#3f8f93'],
        'orange' => ['theme' => '#e39a5c', 'hover' => '#c97a3f'],
    ];

    $defaultColor = ['theme' => '#ea868f', 'hover' => '#d1606e'];
    $colors = isset($colorMap[$colorScheme]) ? $colorMap[$colorScheme] : $defaultColor;
    $themeColor = $colors['theme'];
    $themeHoverColor = $colors['hover'];

    $darkColorMap = [
        'pink' => ['theme' => '#bf677a', 'hover' => '#d6728a'],
        'green' => ['theme' => '#3f8a6c', 'hover' => '#2f6f56'],
        'blue' => ['theme' => '#44579a', 'hover' => '#5b6fc4'],
        'yellow' => ['theme' => '#ab8748', 'hover' => '#cfa24d'],
        'red' => ['theme' => '#9a444b', 'hover' => '#b84a4a'],
        'purple' => ['theme' => '#5f548a', 'hover' => '#7668a8'],
        'cyan' => ['theme' => '#3f7a7f', 'hover' => '#5f9ea3'],
        'orange' => ['theme' => '#9f5a2f', 'hover' => '#b86a3a'],
    ];

    $darkColors = isset($darkColorMap[$colorScheme]) ? $darkColorMap[$colorScheme] : $defaultColor;
    $darkThemeColor = $darkColors['theme'];
    $darkThemeHoverColor = $darkColors['hover'];

    echo '<style>
        :root {
            --themecolor: ' . htmlspecialchars($themeColor, ENT_QUOTES, 'UTF-8') . ';
            --themehovercolor: ' . htmlspecialchars($themeHoverColor, ENT_QUOTES, 'UTF-8') . ';
        }

        [data-theme="dark"] {
            --themecolor: ' . htmlspecialchars($darkThemeColor, ENT_QUOTES, 'UTF-8') . ';
            --themehovercolor: ' . htmlspecialchars($darkThemeHoverColor, ENT_QUOTES, 'UTF-8') . ';
        }
    </style>';
}

// 读取主题布尔配置项（兼容旧值）
function psOptionEnabled($value, $default = true)
{
    if ($value === null) {
        return (bool)$default;
    }

    if (is_bool($value)) {
        return $value;
    }

    $normalized = strtolower(trim((string)$value));
    if ($normalized === '1' || $normalized === 'true' || $normalized === 'on' || $normalized === 'yes') {
        return true;
    }

    if ($normalized === '0' || $normalized === 'false' || $normalized === 'off' || $normalized === 'no') {
        return false;
    }

    return (bool)$default;
}

function getPSRuntimeConfig($archive = null)
{
    $options = Typecho_Widget::widget('Widget_Options');

    $features = [
        'showTOC' => psOptionEnabled($options->showTOC ?? '1', true)
    ];

    $pageType = 'list';
    if ($archive && method_exists($archive, 'is')) {
        if ($archive->is('post')) {
            $pageType = 'post';
        } elseif ($archive->is('page')) {
            $pageType = 'page';
        }
    }

    return [
        'themeVersion' => defined('PS_THEME_VERSION') ? PS_THEME_VERSION : '0',
        'themeUrl' => $options->themeUrl,
        'siteUrl' => $options->siteUrl,
        'pageType' => $pageType,
        'features' => $features,
        'assets' => [
            'mediumZoom' => resolveStaticURL('medium-zoom.min.js'),
            'owo' => $options->themeUrl . '/js/OwO.min.js'
        ]
    ];
}

function outputPSRuntimeConfigScript($archive = null)
{
    $config = getPSRuntimeConfig($archive);
    $json = json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($json === false) {
        $json = '{}';
    }

    echo '<script>window.PS_CONFIG = ' . $json . ';</script>';
}

// 获取 GitHub 最新版本号
function getLatestGitHubRelease($owner, $repo)
{
    $owner = trim((string)$owner);
    $repo = trim((string)$repo);
    if ($owner === '' || $repo === '') {
        return false;
    }

    $cacheKey = 'release:v1:' . strtolower($owner) . '/' . strtolower($repo);
    $ttl = 6 * 3600;
    $cache = getGithubCache($cacheKey, $ttl);
    if ($cache && !empty($cache['fresh'])) {
        return $cache['data'];
    }

    $url = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: PureSuck-Theme\r\n"
        ]
    ]);

    $response = @file_get_contents($url, false, $context);

    if ($response === false) {
        if ($cache && isset($cache['data'])) {
            return $cache['data'];
        }
        return false;
    }

    $data = json_decode($response, true);

    if ($data && isset($data['tag_name'])) {
        $version = ltrim($data['tag_name'], 'v');
        setGithubCache($cacheKey, $version);
        return $version;
    }

    if ($cache && isset($cache['data'])) {
        return $cache['data'];
    }

    return false;
}

// 主题配置表单
function themeConfig($form)
{
    # 主题信息及功能
    $str1 = explode('/themes/', Helper::options()->themeUrl);
    $str2 = explode('/', $str1[1]);
    $name = $str2[0];
    $db = Typecho_Db::get();
    $sjdq = $db->fetchRow($db->select()->from('table.options')->where('name = ?', 'theme:' . $name));
    $ysj = $sjdq['value'];

    if (isset($_POST['type'])) {
        if ($_POST["type"] == "备份模板设置数据") {
            if ($db->fetchRow($db->select()->from('table.options')->where('name = ?', 'theme:' . $name . 'bf'))) {
                $update = $db->update('table.options')->rows(array('value' => $ysj))->where('name = ?', 'theme:' . $name . 'bf');
                $db->query($update);
                echo '<div class="tongzhi home">备份已更新，请等待自动刷新！如果等不到请点击';
                ?>
                <a href="<?php Helper::options()->adminUrl('options-theme.php'); ?>">这里</a></div>
                <script language="JavaScript">
                    window.setTimeout("location=\'<?php Helper::options()->adminUrl('options-theme.php'); ?>\'", 2500);
                </script>
                <?php
            } else {
                if ($ysj) {
                    $insert = $db->insert('table.options')
                        ->rows(array('name' => 'theme:' . $name . 'bf', 'user' => '0', 'value' => $ysj));
                    $db->query($insert);
                    echo '<div class="tongzhi home">备份完成，请等待自动刷新！如果等不到请点击';
                    ?>
                    <a href="<?php Helper::options()->adminUrl('options-theme.php'); ?>">这里</a></div>
                    <script language="JavaScript">
                        window.setTimeout("location=\'<?php Helper::options()->adminUrl('options-theme.php'); ?>\'", 2500);
                    </script>
                    <?php
                }
            }
        }
        if ($_POST["type"] == "还原模板设置数据") {
            if ($db->fetchRow($db->select()->from('table.options')->where('name = ?', 'theme:' . $name . 'bf'))) {
                $sjdub = $db->fetchRow($db->select()->from('table.options')->where('name = ?', 'theme:' . $name . 'bf'));
                $bsj = $sjdub['value'];
                $update = $db->update('table.options')->rows(array('value' => $bsj))->where('name = ?', 'theme:' . $name);
                $db->query($update);
                echo '<div class="tongzhi home">检测到模板备份数据，恢复完成，请等待自动刷新！如果等不到请点击';
                ?>
                <a href="<?php Helper::options()->adminUrl('options-theme.php'); ?>">这里</a></div>
                <script language="JavaScript">
                    window.setTimeout("location=\'<?php Helper::options()->adminUrl('options-theme.php'); ?>\'", 2000);
                </script>
                <?php
            } else {
                echo '<div class="tongzhi home">没有模板备份数据，恢复不了哦！</div>';
            }
        }
        if ($_POST["type"] == "删除备份数据") {
            if ($db->fetchRow($db->select()->from('table.options')->where('name = ?', 'theme:' . $name . 'bf'))) {
                $delete = $db->delete('table.options')->where('name = ?', 'theme:' . $name . 'bf');
                $db->query($delete);
                echo '<div class="tongzhi home">删除成功，请等待自动刷新，如果等不到请点击';
                ?>
                <a href="<?php Helper::options()->adminUrl('options-theme.php'); ?>">这里</a></div>
                <script language="JavaScript">
                    window.setTimeout("location=\'<?php Helper::options()->adminUrl('options-theme.php'); ?>\'", 2500);
                </script>
                <?php
            } else {
                echo '<div class="tongzhi home">不用删了！备份不存在！！！</div>';
            }
        }
    }

    $themeOptionsUrl = '';
    ob_start();
    $themeOptionsUrlCandidate = Helper::options()->adminUrl('options-theme.php');
    $themeOptionsUrlBuffered = trim((string)ob_get_clean());
    if (is_string($themeOptionsUrlCandidate) && $themeOptionsUrlCandidate !== '') {
        $themeOptionsUrl = $themeOptionsUrlCandidate;
    } elseif ($themeOptionsUrlBuffered !== '') {
        $themeOptionsUrl = $themeOptionsUrlBuffered;
    }
    if ($themeOptionsUrl === '') {
        $themeOptionsUrl = 'options-theme.php';
    }
    $themeOptionsUrl = htmlspecialchars($themeOptionsUrl, ENT_QUOTES, 'UTF-8');

    echo '
    <style id="ps-theme-config-lite">
        .ps-theme-config-lite {
            margin: 12px 0 16px;
            padding: 12px 14px;
            border: 1px solid #efeaeb;
            border-left: 4px solid #ea868f;
            border-radius: 6px;
            background: #fff;
        }

        .ps-theme-config-lite h2 {
            margin: 0 0 6px;
            font-size: 16px;
            color: #333;
        }

        .ps-theme-config-lite p {
            margin: 0;
            color: #666;
            line-height: 1.7;
        }

        .ps-theme-config-lite .ps-theme-config-actions {
            margin-top: 10px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .ps-theme-meta-lite {
            margin: 10px 0 12px;
            line-height: 1.7;
            color: #666;
        }

        .ps-theme-meta-lite .ps-current-version {
            color: #b45864;
            font-weight: 600;
        }

        .ps-theme-meta-lite .ps-version-new {
            color: #d95f5f;
        }

        .ps-theme-meta-lite .ps-version-latest {
            color: #4ca36c;
        }

        .ps-theme-backup-lite {
            margin: 8px 0 14px;
            padding: 10px 12px;
            border: 1px solid #efefef;
            border-radius: 6px;
            background: #fff;
        }

        .ps-theme-backup-lite p {
            margin: 0 0 8px;
            color: #666;
        }
    </style>
    <div class="ps-theme-config-lite">
        <h2>PureSuck 主题配置</h2>
        <p>干净，纯洁，淡雅朴素的 Typecho 主题</p>
        <p>希望这份干净的爱恋能得到你的喜欢</p>
        <div class="ps-theme-config-actions">
            <a class="btn btn-s" href="https://www.moxiify.cn" target="_blank" rel="noopener noreferrer">作者主页</a>
            <a class="btn btn-s" href="https://github.com/MoXiaoXi233/PureSuck-theme" target="_blank" rel="noopener noreferrer">主题文档</a>
        </div>
    </div>';

    // 获取最新版本号
    $currentVersion = defined('PS_THEME_VERSION') ? PS_THEME_VERSION : '1.3.2';
    $latestVersion = getLatestGitHubRelease('MoXiaoXi233', 'PureSuck-theme');
    $versionHtml = '<div class="ps-theme-meta-lite">当前主题版本：<span class="ps-current-version">' . htmlspecialchars($currentVersion) . '</span>';

    if ($latestVersion) {
        if (version_compare($latestVersion, $currentVersion, '>')) {
            $versionHtml .= ' <span class="ps-version-new">(有新版本: ' . htmlspecialchars($latestVersion) . ')</span>';
        } else {
            $versionHtml .= ' <span class="ps-version-latest">(已是最新)</span>';
        }
    }

    $versionHtml .= '</div>';

    echo $versionHtml . '
    <div class="ps-theme-backup-lite">
    <p>主题开源页面及文档：<a href="https://github.com/MoXiaoXi233/PureSuck-theme" target="_blank" rel="noopener noreferrer">PureSuck-theme</a></p>
    <p>*备份功能只在 SQL 环境下测试正常，遇到问题请清空配置重新填写*</p>
    <form class="protected home" action="?' . $name . 'bf" method="post">
    <input type="submit" name="type" class="btn btn-s" value="备份模板设置数据" />  <input type="submit" name="type" class="btn btn-s" value="还原模板设置数据" />  <input type="submit" name="type" class="btn btn-s" value="删除备份数据" /></form>
    </div>';

    // 网页 icon URL 配置项
    $logoUrl = new \Typecho\Widget\Helper\Form\Element\Text(
        'logoUrl',
        null,
        null,
        _t('favicon.ico 地址'),
        _t('填写ico格式图片 URL 地址, 在网站标题前加上一个图标')
    );
    $form->addInput($logoUrl);

    // 网站标题配置项
    $titleIndex = new \Typecho\Widget\Helper\Form\Element\Text(
        'titleIndex',
        null,
        null,
        _t('网站标题'),
        _t('网站左侧标题文字')
    );
    $form->addInput($titleIndex);

    // 左侧 LOGO URL 配置项
    $logoIndex = new \Typecho\Widget\Helper\Form\Element\Text(
        'logoIndex',
        null,
        null,
        _t('左侧 LOGO 地址'),
        _t('填写 JPG/PNG/Webp 等图片 URL 地址, 网站左侧头像的显示 (512*512最佳) ')
    );
    $form->addInput($logoIndex);

    // 左侧 Logo 跳转链接 配置项
    $logoIndexUrl = new \Typecho\Widget\Helper\Form\Element\Text(
        'logoIndexUrl',
        null,
        null,
        _t('LOGO 跳转 地址'),
        _t('点击头像时候跳转的网址，可以设置为引导页等，为空则为博客首页')
    );
    $form->addInput($logoIndexUrl);

    //作者头像
    $authorAvatar = new \Typecho\Widget\Helper\Form\Element\Text(
        'authorAvatar',
        null,
        null,
        _t('作者头像地址'),
        _t('填写 JPG/PNG/Webp 等图片 URL 地址, 用于显示文章作者头像')
    );
    $form->addInput($authorAvatar);

    // 左侧描述
    $customDescription = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'customDescription',
        null,
        null,
        _t('左侧个人描述'),
        _t('填写自定义描述内容，最好简短，将在网站左侧站名下显示')
    );
    $form->addInput($customDescription);

    // 左侧自定义
    $leftSideCustomCode = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'leftSideCustomCode',
        null,
        null,
        _t('左侧自定义区域'),
        _t('支持自定义HTML，将在网站左侧显示')
    );
    $form->addInput($leftSideCustomCode);

    // Footer Script标签
    $footerScript = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'footerScript',
        null,
        null,
        _t('Script标签'),
        _t('位于Footer，在这里填入JavaScript代码，需要包含&lt;script&gt;标签！，不要填除了脚本外的其他内容，否则会造成样式错误！<br>如果开启了 Pjax 功能，请自行在 header.php 配置回调函数或者尝试寻求帮助')
    );
    $form->addInput($footerScript);

    $staticCdn = new Typecho_Widget_Helper_Form_Element_Radio(
        'staticCdn',
        array(
            'local' => _t('本地'),
            'bootcdn' => _t('BootCDN'),
            'cdnjs' => _t('CDNJS'),
        ),
        'local',
        _t("主题静态资源 CDN"),
        _t("静态资源 CDN 源选择，默认为本地")
    );
    $form->addInput($staticCdn);

    // 网页底部信息
    $footerInfo = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'footerInfo',
        null,
        '在 Typecho 后台主题设置填写此处字段<br>感谢使用 PureSuck 主题',
        _t('网页底部信息'),
        _t('填写网页底部的自定义信息，可以包含HTML内容，用br标签换行')
    );
    $form->addInput($footerInfo);


    // Pjax回调函数（Swup）
    $PjaxScript = new \Typecho\Widget\Helper\Form\Element\Textarea(
        'PjaxScript',
        null,
        null,
        _t('Swup 回调函数'),
        _t('在这里填入需要在每次页面切换后执行的函数，例如：loadDPlayer(); 如果不知道这是什么，请忽略。')
    );
    $form->addInput($PjaxScript);

    //主题样式细调
    // 标题粗下划线
    $postTitleAfter = new Typecho_Widget_Helper_Form_Element_Radio(
        'postTitleAfter',
        array(
            'off' => _t('关'),
            'boldLine' => _t('粗线条'),
            'wavyLine' => _t('波浪线条'),
        ),
        'off',
        _t('主标题下的装饰线条样式'),
        _t('选择主标题下的装饰线条样式，带有触摸反馈')
    );
    $form->addInput($postTitleAfter);

    // 搜索功能显示选项
    $showSearch = new Typecho_Widget_Helper_Form_Element_Radio(
        'showSearch',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否显示搜索功能'),
        _t('在页面右侧显示一个搜索框')
    );
    $form->addInput($showSearch);

    // TOC 模块显示选项
    $showTOC = new Typecho_Widget_Helper_Form_Element_Radio(
        'showTOC',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否显示 TOC 目录树'),
        _t('在页面右侧显示一个目录树，如果页面没有对应的目录结构会自动隐藏')
    );
    $form->addInput($showTOC);

    // 分类模块显示选项
    $showCategory = new Typecho_Widget_Helper_Form_Element_Radio(
        'showCategory',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否显示分类模块')
    );
    $form->addInput($showCategory);

    // 标签模块显示选项
    $showTag = new Typecho_Widget_Helper_Form_Element_Radio(
        'showTag',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否显示标签模块')
    );
    $form->addInput($showTag);

    // 文章页显示字数信息选项
    $showWordCount = new Typecho_Widget_Helper_Form_Element_Radio(
        'showWordCount',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否在文章开头显示字数和预计阅读时间')
    );
    $form->addInput($showWordCount);

    // 文章页显示版权信息选项
    $showCopyright = new Typecho_Widget_Helper_Form_Element_Radio(
        'showCopyright',
        array('1' => _t('显示'), '0' => _t('隐藏')),
        '1',
        _t('是否在文章页尾显示版权信息')
    );
    $form->addInput($showCopyright);

    $ccLicense = new Typecho_Widget_Helper_Form_Element_Radio(
        'ccLicense',
        array(
            'by-nc-sa' => _t('CC BY-NC-SA 4.0'),
            'by-nc' => _t('CC BY-NC 4.0'),
            'by' => _t('CC BY 4.0'),
            'by-sa' => _t('CC BY-SA 4.0'),
            'by-nc-nd' => _t('CC BY-NC-ND 4.0'),
            'zero' => _t('CC0 1.0'),
        ),
        'by-nc-sa',
        _t('使用的CC协议'),
        _t('选择使用的CC协议，默认为CC BY-NC-SA 4.0')
    );
    $form->addInput($ccLicense);

    // 主题配色
    $colors = array(
        'pink' => _t('素粉'),
        'green' => _t('淡绿'),
        'blue' => _t('墨蓝'),
        'yellow' => _t('落黄'),
        'red' => _t('赤红'),
        'purple' => _t('幽紫'),
        'cyan' => _t('青空'),
        'orange' => _t('橙阳'),
    );
    $defaultColor = 'pink';
    $colorSelect = new Typecho_Widget_Helper_Form_Element_Radio('colorScheme', $colors, $defaultColor, _t('配色方案'), _t('选择一个配色方案，默认为素粉'));
    $form->addInput($colorSelect);

    // 卡片竖排分类显示选项
    $showCardCategory = new Typecho_Widget_Helper_Form_Element_Radio(
        'showCardCategory',
        array(
            '1' => _t('显示'),
            '0' => _t('隐藏')
        ),
        '1',
        _t('是否在文章卡片右上角显示竖排分类'),
        _t('只在首页及搜索页等小卡片显示，不在文章内显示')

    );
    $form->addInput($showCardCategory);

}
