<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */



/**
 * 获取站点配置
 */
function getSiteConfig($key = '', $default = '')
{
    static $configs = null;
    if ($configs === null) {
        $db = \Core\Db\DB::getInstance();
        $rows = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')}");
        $configs = [];
        foreach ($rows as $row) {
            $configs[$row['config_key']] = $row['config_value'];
        }
    }
    if ($key === '') {
        return $configs;
    }
    return $configs[$key] ?? $default;
}

/**
 * 生成URL
 */
function buildUrl($path = '', $params = [])
{
    static $urlMode = null;
    static $base = null;
    
    if ($urlMode === null) {
        $db = \Core\Db\DB::getInstance();
        $row = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'url_mode'");
        $urlMode = $row ? $row['config_value'] : 'static';
        
        $siteRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'site_url'");
        $base = rtrim($siteRow['config_value'] ?? 'http://' . $_SERVER['HTTP_HOST'], '/');
    }
    
    if ($urlMode === 'dynamic') {
        $url = $base . '/public/index.php?';
        if ($path) $url .= 'm=' . $path;
        if ($params) $url .= '&' . http_build_query($params);
    } else {
        $url = $base . '/' . ltrim($path, '/');
        if ($params) $url .= '?' . http_build_query($params);
    }
    
    return $url;
}

/**
 * 生成栏目URL
 */
function channelUrl($channel, $page = 1)
{
    $base = getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']);
    if (!empty($channel['channel_dir'])) {
        $url = $base . '/' . $channel['channel_dir'] . '/';
    } else {
        $url = $base . '/channel/' . $channel['id'] . '/';
    }
    if ($page > 1) {
        $url .= '?page=' . $page;
    }
    return $url;
}

/**
 * 生成文章URL
 */
function articleUrl($article)
{
    $base = getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']);
    $url = $base . '/article/' . $article['id'] . '.html';
    return $url;
}

/**
 * 生成产品URL
 */
function productUrl($product)
{
    $base = getSiteConfig('site_url', 'http://' . $_SERVER['HTTP_HOST']);
    $url = $base . '/product/' . $product['id'] . '.html';
    return $url;
}

/**
 * 获取栏目名称
 */
function getChannelName($channelId)
{
    static $channels = null;
    if ($channels === null) {
        $db = \Core\Db\DB::getInstance();
        $rows = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')}");
        $channels = [];
        foreach ($rows as $row) {
            $channels[$row['id']] = $row['channel_name'];
        }
    }
    return $channels[$channelId] ?? '';
}

/**
 * 截取字符串
 */
function msubstr($str, $start = 0, $length = 100, $suffix = '...')
{
    if (function_exists('mb_substr')) {
        $s = mb_substr($str, $start, $length, 'utf-8');
    } else {
        $len = strlen($str);
        $s = '';
        for ($i = $start; $i < $len && $length > 0; $i++) {
            if (ord($str[$i]) > 127) {
                $s .= $str[$i] . $str[++$i] . $str[++$i];
                $length--;
            } else {
                $s .= $str[$i];
                $length--;
            }
        }
    }
    if ($start == 0 && strlen($s) < strlen($str)) {
        $s .= $suffix;
    }
    return $s;
}

/**
 * 格式化日期
 */
function formatDate($time, $format = 'Y-m-d H:i')
{
    if (empty($time)) {
        return '';
    }
    return date($format, $time);
}

/**
 * 格式化文件大小
 */
function formatSize($bytes)
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < 4) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 2) . ' ' . $units[$i];
}

/**
 * 获取文章标记样式
 */
function getFlagStyle($flag)
{
    $styles = [
        'top' => ['text' => '置顶', 'color' => '#e74c3c'],
        'recommend' => ['text' => '推荐', 'color' => '#f39c12'],
        'hot' => ['text' => '热门', 'color' => '#e67e22'],
    ];
    return $styles[$flag] ?? ['text' => '', 'color' => ''];
}

/**
 * 生成缩略图HTML
 */
function getLitpicHtml($litpic, $alt = '', $width = 0, $height = 0)
{
    if (empty($litpic)) {
        return '<span class="no-pic">暂无图片</span>';
    }

    $style = '';
    if ($width > 0) $style .= "width:{$width}px;";
    if ($height > 0) $style .= "height:{$height}px;";

    // data:image 开头的 base64 图片直接输出，不转义
    if (strpos($litpic, 'data:') === 0) {
        return '<img src="' . $litpic . '" alt="' . htmlspecialchars($alt) . '"' . ($style ? ' style="' . $style . '"' : '') . '>';
    }

    return '<img src="' . htmlspecialchars($litpic) . '" alt="' . htmlspecialchars($alt) . '"' . ($style ? ' style="' . $style . '"' : '') . '>';
}

/**
 * 生成SEO信息
 */
function getSeoInfo($title = '', $keywords = '', $description = '')
{
    $siteName = getSiteConfig('site_name', '企业CMS');
    $siteTitle = getSiteConfig('site_title', $siteName);
    $siteKeywords = getSiteConfig('site_keywords', '');
    $siteDescription = getSiteConfig('site_description', '');
    
    $pageTitle = $title ? $title . ' - ' . $siteTitle : $siteTitle;
    $pageKeywords = $keywords ?: $siteKeywords;
    $pageDescription = $description ?: $siteDescription;
    
    return [
        'title' => $pageTitle,
        'keywords' => $pageKeywords,
        'description' => $pageDescription,
    ];
}

/**
 * 输出分页
 */
function showPage($page, $totalPages, $url = '')
{
    if ($totalPages <= 1) {
        return '';
    }
    
    $html = '<div class="pagination">';
    
    // 上一页
    if ($page > 1) {
        $html .= '<a href="' . $url . '?page=' . ($page - 1) . '" class="prev">上一页</a>';
    }
    
    // 页码
    $start = max(1, $page - 2);
    $end = min($totalPages, $page + 2);
    
    if ($start > 1) {
        $html .= '<a href="' . $url . '?page=1">1</a>';
        if ($start > 2) {
            $html .= '<span class="ellipsis">...</span>';
        }
    }
    
    for ($i = $start; $i <= $end; $i++) {
        $active = ($i == $page) ? ' class="active"' : '';
        $html .= '<a href="' . $url . '?page=' . $i . '"' . $active . '>' . $i . '</a>';
    }
    
    if ($end < $totalPages) {
        if ($end < $totalPages - 1) {
            $html .= '<span class="ellipsis">...</span>';
        }
        $html .= '<a href="' . $url . '?page=' . $totalPages . '">' . $totalPages . '</a>';
    }
    
    // 下一页
    if ($page < $totalPages) {
        $html .= '<a href="' . $url . '?page=' . ($page + 1) . '" class="next">下一页</a>';
    }
    
    $html .= '</div>';
    
    return $html;
}

/**
 * 获取会员信息
 */
function getMemberInfo($memberId)
{
    $db = \Core\Db\DB::getInstance();
    return $db->fetch("SELECT * FROM {$db->table('member')} WHERE id = ?", [$memberId]);
}

/**
 * 检查会员登录状态
 */
function checkMemberLogin()
{
    if (!isset($_SESSION['member_id']) || empty($_SESSION['member_id'])) {
        header('Location: /member/login.php');
        exit;
    }
}

/**
 * 记录操作日志
 */
function addLog($action, $module = '', $description = '', $content = '')
{
    $db = \Core\Db\DB::getInstance();
    $adminId = $_SESSION['admin_id'] ?? 0;
    $adminName = $_SESSION['admin_name'] ?? '系统';
    $db->insert('log', [
        'user_id' => $adminId,
        'username' => $adminName,
        'action' => $action,
        'module' => $module,
        'content' => $description,
        'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'create_time' => time()
    ]);
}

/**
 * 获取后台 CSRF 令牌
 */
function getAdminCsrfToken()
{
    if (empty($_SESSION['admin_csrf_token'])) {
        $_SESSION['admin_csrf_token'] = md5(uniqid(mt_rand(), true));
    }
    return $_SESSION['admin_csrf_token'];
}

/**
 * 校验后台 CSRF 令牌
 */
function verifyAdminCsrfToken($token = null)
{
    if ($token === null) {
        $token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
        if ($token === '' && isset($_SERVER['HTTP_X_CSRF_TOKEN'])) {
            $token = $_SERVER['HTTP_X_CSRF_TOKEN'];
        }
    }
    return !empty($token) && isset($_SESSION['admin_csrf_token']) && hash_equals($_SESSION['admin_csrf_token'], $token);
}

/**
 * 后台 CSRF 校验失败时统一输出
 */
function requireAdminCsrfToken($json = false)
{
    if (verifyAdminCsrfToken()) {
        return true;
    }
    if ($json) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 403, 'msg' => '非法请求，CSRF校验失败']);
    } else {
        echo '<script>alert("非法请求，CSRF校验失败");history.back();</script>';
    }
    exit;
}

/**
 * 获取会员端 CSRF 令牌
 */
function getMemberCsrfToken()
{
    if (empty($_SESSION['member_csrf_token'])) {
        $_SESSION['member_csrf_token'] = md5(uniqid(mt_rand(), true));
    }
    return $_SESSION['member_csrf_token'];
}

/**
 * 校验会员端 CSRF 令牌
 */
function verifyMemberCsrfToken($token = null)
{
    if ($token === null) {
        $token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
        if ($token === '' && isset($_SERVER['HTTP_X_CSRF_TOKEN'])) {
            $token = $_SERVER['HTTP_X_CSRF_TOKEN'];
        }
    }
    return !empty($token) && isset($_SESSION['member_csrf_token']) && hash_equals($_SESSION['member_csrf_token'], $token);
}

/**
 * 会员端 CSRF 校验失败时统一输出
 */
function requireMemberCsrfToken($json = false)
{
    if (verifyMemberCsrfToken()) {
        return true;
    }
    if ($json) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 403, 'msg' => '非法请求，CSRF校验失败']);
    } else {
        echo '<script>alert("非法请求，CSRF校验失败");history.back();</script>';
    }
    exit;
}

/**
 * 发送站内消息通知管理员
 * @param string $title   消息标题
 * @param string $content 消息内容
 * @param string $fromName 发送者名称
 */
function sendAdminMessage($title, $content, $fromName = '系统通知')
{
    $db = \Core\Db\DB::getInstance();
    $db->insert('message', [
        'from_id'   => 0,
        'from_name' => $fromName,
        'to_id'     => 0,
        'to_name'   => '管理员',
        'title'     => $title,
        'content'   => $content,
        'is_read'   => 0,
        'create_time' => time()
    ]);
}

/**
 * 记录页面浏览（每次访问自动累加）
 */
function trackPageView()
{
    $db = \Core\Db\DB::getInstance();
    
    // 获取今日开始时间戳
    $todayStart = strtotime(date('Y-m-d'));
    
    // 今日浏览量+1
    $db->query("UPDATE {$db->table('config')} SET config_value = config_value + 1 WHERE config_key = 'today_views'");
    
    // 如果今日浏览量记录的时间不是今天，重置为1
    $lastDate = getSiteConfig('views_date', '');
    $today = date('Y-m-d');
    if ($lastDate != $today) {
        $db->query("UPDATE {$db->table('config')} SET config_value = 1 WHERE config_key = 'today_views'");
        $db->query("UPDATE {$db->table('config')} SET config_value = ? WHERE config_key = 'views_date'", [$today]);
    }
    
    // 总浏览量+1
    $db->query("UPDATE {$db->table('config')} SET config_value = config_value + 1 WHERE config_key = 'total_views'");
}

/**
 * 获取站点浏览量
 */
function getSiteViews()
{
    $today = date('Y-m-d');
    $lastDate = getSiteConfig('views_date', '');
    
    // 如果记录日期不是今天，今日浏览量需要重置
    if ($lastDate != $today) {
        return [
            'today_views' => 0,
            'total_views' => intval(getSiteConfig('total_views', 0))
        ];
    }
    
    return [
        'today_views' => intval(getSiteConfig('today_views', 0)),
        'total_views' => intval(getSiteConfig('total_views', 0))
    ];
}