<?php
// 功能：文章页默认模板
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。


// 检查会话是否已启动，未启动则启动会话
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

// 用户状态检查
$is_logged_in = isLoggedIn();
$is_user_banned = false;

// 盖章插件检查
$qk_stamp_plugin_exists = file_exists(dirname(__DIR__) . '/admin/Plugin/40_stamp.php');
$qk_stamp_enabled = false;
if ($qk_stamp_plugin_exists) {
  $plugin_content = @file_get_contents(dirname(__DIR__) . '/admin/Plugin/40_stamp.php');
  if ($plugin_content && preg_match('/盖章总开关\s*=\s*(true|false)/i', $plugin_content, $matches)) {
    $qk_stamp_enabled = strtolower($matches[1]) === 'true';
  }
}

if ($is_logged_in && isset($_SESSION['user_status'])) {
  $user_status = $_SESSION['user_status'];
  $is_user_banned = ($user_status === 0 || $user_status === '0' || $user_status === '被封禁');
}

if (!function_exists('hasPurchasedPost')) {
/**
 * 检查用户是否已购买文章
 */
function hasPurchasedPost($userId, $postId)
{
  if ($userId <= 0 || $postId <= 0) return false;

  try {
    $user = get_single_row($GLOBALS['conn'], "SELECT bought FROM users WHERE id = ?", array($userId));
    if (!$user || empty($user['bought'])) return false;

    $purchasedPosts = explode(',', $user['bought']);
    return in_array(strval($postId), $purchasedPosts);
  } catch (Exception $e) {
    return false;
  }
}
}

/**
 * 处理文章购买
 */
function purchasePost($userId, $postId)
{
  if ($userId <= 0 || $postId <= 0) return array('success' => false, 'message' => '无效的参数');

  try {
    // 检查文章是否存在
    $post = get_single_row($GLOBALS['conn'], "SELECT id, content FROM posts WHERE id = ?", array($postId));
    if (!$post) {
      return array('success' => false, 'message' => '文章不存在');
    }

    // 从付费内容中提取积分
    $pointsRequired = 0;
    if (preg_match('/\[qkcms:buy——(\d+)个积分\]/', $post['content'], $matches)) {
      $pointsRequired = intval($matches[1]);
    }

    // 检查用户是否已购买
    if (hasPurchasedPost($userId, $postId)) {
      return array('success' => false, 'message' => '您已购买过此文章');
    }

    // 获取用户信息
    $user = get_single_row($GLOBALS['conn'], "SELECT bought, points FROM users WHERE id = ?", array($userId));
    if (!$user) {
      return array('success' => false, 'message' => '用户信息不存在');
    }

    // 获取用户积分
    $userPoints = intval($user['points']);

    // 检查用户积分是否足够（仅当积分要求>0时）
    if ($pointsRequired > 0) {
      if ($userPoints < $pointsRequired) {
        return array('success' => false, 'message' => '积分不足，需要 ' . $pointsRequired . ' 积分');
      }
    }

    // 获取用户当前购买的文章
    $purchasedPosts = array();
    if (!empty($user['bought'])) {
      $purchasedPosts = explode(',', $user['bought']);
    }

    // 添加新购买的文章ID
    $purchasedPosts[] = $postId;
    $purchasedPostsStr = implode(',', $purchasedPosts);

    // 开始事务
    mysqli_autocommit($GLOBALS['conn'], false);

    // 更新用户购买记录
    $result1 = execute_non_query($GLOBALS['conn'], "UPDATE users SET bought = ? WHERE id = ?", array($purchasedPostsStr, $userId));

    // 扣除用户积分（仅当积分要求>0时）
    $result2 = true;
    if ($pointsRequired > 0) {
      $newPoints = $userPoints - $pointsRequired;
      $result2 = execute_non_query($GLOBALS['conn'], "UPDATE users SET points = ? WHERE id = ?", array($newPoints, $userId));
      // 检查积分扣除是否成功
      if (!$result2 || !isset($result2['affected_rows']) || $result2['affected_rows'] <= 0) {
        mysqli_rollback($GLOBALS['conn']);
        mysqli_autocommit($GLOBALS['conn'], true);
        return array('success' => false, 'message' => '积分扣除失败，请稍后重试');
      }
    } else {
      $newPoints = $userPoints;
    }

    if ($result1 && $result1['affected_rows'] > 0 && $result2) {
      mysqli_commit($GLOBALS['conn']);
      // 更新session中的积分值
      if (isset($_SESSION)) {
        $_SESSION['user_points'] = $newPoints;
      }
      $message = $pointsRequired > 0 ? '购买成功！已扣除 ' . $pointsRequired . ' 积分' : '购买成功！';
      return array('success' => true, 'message' => $message, 'new_points' => $newPoints);
    } else {
      mysqli_rollback($GLOBALS['conn']);
      return array('success' => false, 'message' => '购买失败，请稍后重试');
    }
  } catch (Exception $e) {
    if (isset($GLOBALS['conn'])) {
      mysqli_rollback($GLOBALS['conn']);
      mysqli_autocommit($GLOBALS['conn'], true);
    }
    return array('success' => false, 'message' => '服务器错误，请稍后重试');
  }
}

function getPostPasswordSessionKey($postId)
{
  return 'qk_post_password_access_' . intval($postId);
}

function hasPostPasswordAccess($postId)
{
  $sessionKey = getPostPasswordSessionKey($postId);
  return !empty($_SESSION[$sessionKey]);
}

function isPostPasswordAjaxRequest()
{
  if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['post_password_submit'])) {
    return false;
  }
  if (isset($_POST['post_password_ajax']) && $_POST['post_password_ajax'] === '1') {
    return true;
  }
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

// 获取文章ID和详情
$post_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (function_exists('qk_get_current_post_id')) {
  $post_id = qk_get_current_post_id();
}
$settings = getSettings($GLOBALS['conn']);

/**
 * 获取文章详情并更新浏览量
 */
function getPostDetails($postId)
{
  if ($postId <= 0) return false;

  try {
    if (!get_single_row($GLOBALS['conn'], "SELECT 1 FROM posts WHERE id = ?", array($postId))) {
      return false;
    }

    $should_count = true;
    if (function_exists('qk_should_count_post_view')) {
      $should_count = qk_should_count_post_view($postId, 86400);
    }
    if ($should_count) {
      execute_query($GLOBALS['conn'], "UPDATE posts SET views = views + 1 WHERE id = ?", array($postId));
    }

    $post = get_single_row($GLOBALS['conn'], "SELECT id, title, points, likes, access_password FROM posts WHERE id = ?", array($postId));
    if (!$post) return false;

    $post['is_liked'] = false;
    if (isset($_SESSION['user_id'])) {
      $check_like_sql = "SELECT id FROM likes WHERE content_type = 'post' AND content_id = ? AND user_id = ?";
      $post['is_liked'] = (bool)get_single_row($GLOBALS['conn'], $check_like_sql, array($postId, $_SESSION['user_id']));
    }

    // 获取分享数
    $share_count_result = get_single_row($GLOBALS['conn'], "SELECT COUNT(*) as share_count FROM shares WHERE content_type = 'post' AND content_id = ?", array($postId));
    $post['share_count'] = $share_count_result ? intval($share_count_result['share_count']) : 0;

    return $post;
  } catch (Exception $e) {
    return false;
  }
}

$post = getPostDetails($post_id);

// 文章不存在处理
if (!$post && $post_id > 0) {
  if (defined('COMMON_LOADED')) {
    safeInclude('templates/404.php');
    exit;
  }
  header('Location: /404');
  exit;
}

$post_password_required = '';
$post_password_error = '';
$post_password_access_granted = true;

if ($post && isset($post['access_password'])) {
  $post_password_required = trim((string)$post['access_password']);
  if ($post_password_required !== '') {
    $post_password_access_granted = hasPostPasswordAccess($post_id);
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post_password_submit']) && isset($_POST['post_password_post_id']) && intval($_POST['post_password_post_id']) === $post_id) {
      $submittedPassword = isset($_POST['post_password']) ? trim((string)$_POST['post_password']) : '';
      if ($submittedPassword !== '' && hash_equals($post_password_required, $submittedPassword)) {
        $_SESSION[getPostPasswordSessionKey($post_id)] = 1;
        $post_password_access_granted = true;
      } else {
        $post_password_access_granted = false;
        $post_password_error = '密码不正确，请重新输入';
      }
    }
  }
}

if ($post && isPostPasswordAjaxRequest() && isset($_POST['post_password_post_id']) && intval($_POST['post_password_post_id']) === $post_id) {
  ob_clean();
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(array(
    'success' => $post_password_access_granted,
    'message' => $post_password_access_granted ? '密码验证成功' : ($post_password_error !== '' ? $post_password_error : '密码验证失败'),
    'reload' => $post_password_access_granted
  ), JSON_UNESCAPED_UNICODE);
  exit;
}

/**
 * 点赞/取消点赞
 */
function toggleLike($contentType, $contentId, $userId)
{
  try {
    $action = 'like';

    $check_sql = "SELECT id FROM likes WHERE content_type = ? AND content_id = ? AND user_id = ?";
    $existing = get_single_row($GLOBALS['conn'], $check_sql, array($contentType, $contentId, $userId));

    if ($existing) {
      execute_non_query($GLOBALS['conn'], "DELETE FROM likes WHERE id = ?", array($existing['id']));
      $action = 'unlike';
    } else {
      execute_non_query($GLOBALS['conn'], "INSERT IGNORE INTO likes (content_type, content_id, user_id, created_at) VALUES (?, ?, ?, NOW())", array($contentType, $contentId, $userId));
    }

    // 先获取当前的点赞数
    if ($contentType === 'post') {
      $current_likes = get_single_row($GLOBALS['conn'], "SELECT likes FROM posts WHERE id = ?", array($contentId));
      $current_likes = $current_likes ? intval($current_likes['likes']) : 0;
    } else {
      $current_likes = 0;
    }

    // 计算新的点赞数
    if ($action === 'like') {
      $likes_count = $current_likes + 1;
    } else {
      $likes_count = max(0, $current_likes - 1);
    }

    // 更新点赞数
    if ($contentType === 'post') {
      execute_non_query($GLOBALS['conn'], "UPDATE posts SET likes = ? WHERE id = ?", array($likes_count, $contentId));
    }

    return array('success' => true, 'action' => $action, 'likes_count' => $likes_count);
  } catch (Exception $e) {
    // 异常处理：尝试获取当前点赞数
    if ($contentType === 'post') {
      $current_likes = get_single_row($GLOBALS['conn'], "SELECT likes FROM posts WHERE id = ?", array($contentId));
      $likes_count = $current_likes ? intval($current_likes['likes']) : 0;
    } else {
      $likes_count = 0;
    }

    return array('success' => false, 'action' => 'error', 'likes_count' => $likes_count);
  }
}

// 表创建逻辑已移至common.php统一处理

/**
 * 内容举报
 */
function reportContent($contentType, $contentId, $userId, $reason)
{
  try {
    $result = execute_non_query($GLOBALS['conn'], "INSERT INTO reports (content_type, content_id, user_id, reason) VALUES (?, ?, ?, ?)", array($contentType, $contentId, $userId, $reason));

    if ($result && $result['affected_rows'] > 0) {
      $count_result = get_single_row($GLOBALS['conn'], "SELECT COUNT(*) as report_count FROM reports WHERE content_type = ? AND content_id = ?", array($contentType, $contentId));
      $report_count = $count_result ? intval($count_result['report_count']) : 0;

      return array('success' => true, 'report_count' => $report_count);
    }

    return array('success' => false);
  } catch (Exception $e) {
    return array('success' => false);
  }
}

/**
 * 内容分享
 */
function handleShare($contentType, $contentId, $userId = null)
{
  try {
    $result = execute_non_query($GLOBALS['conn'], "INSERT INTO shares (content_type, content_id, user_id, created_at) VALUES (?, ?, ?, NOW())", array($contentType, $contentId, $userId));

    if ($result && $result['affected_rows'] > 0) {
      $count_result = get_single_row($GLOBALS['conn'], "SELECT COUNT(*) as share_count FROM shares WHERE content_type = ? AND content_id = ?", array($contentType, $contentId));
      return array('success' => true, 'share_count' => $count_result ? intval($count_result['share_count']) : 0);
    }

    return array('success' => false);
  } catch (Exception $e) {
    return array('success' => false);
  }
}

// 点赞表创建逻辑已移至common.php统一处理

// AJAX请求处理
if (isset($_POST['action'])) {
  $action = $_POST['action'];
  $response = ['success' => false, 'message' => '未知操作'];

  switch ($action) {
    case 'toggle_like':
    case 'like':
      $content_type = isset($_POST['content_type']) ? $_POST['content_type'] : '';
      $content_id = isset($_POST['content_id']) ? intval($_POST['content_id']) : 0;

      if (!empty($content_type) && $content_id > 0) {
        if (!$is_logged_in) {
          $response['message'] = '请先登录后再点赞';
        } elseif ($is_user_banned) {
          $response['message'] = '您的账号已被封禁';
        } else {
          $result = toggleLike($content_type, $content_id, $_SESSION['user_id']);
          $response['success'] = $result && $result['success'] === true;
          $response['likes_count'] = $result && isset($result['likes_count']) ? $result['likes_count'] : 0;

          if ($result && isset($result['action'])) {
            $response['action'] = $result['action'];
            $response['message'] = $result['action'] === 'like' ? '点赞成功！' : '已取消点赞！';
          } else {
            $response['message'] = '操作过程中出现问题';
          }
        }
      } else {
        $response['message'] = '无效的操作参数';
      }
      break;

    case 'report':
      $content_type = isset($_POST['content_type']) ? $_POST['content_type'] : '';
      $content_id = isset($_POST['content_id']) ? intval($_POST['content_id']) : 0;
      $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';

      if (!empty($content_type) && $content_id > 0 && !empty($reason)) {
        if ($is_user_banned) {
          $response['message'] = '您的账号已被封禁';
        } elseif (!$is_logged_in) {
          $response['message'] = '请先登录后再举报';
        } else {
          $result = reportContent($content_type, $content_id, $_SESSION['user_id'], $reason);
          if ($result && $result['success']) {
            $response = ['success' => true, 'report_count' => $result['report_count'], 'message' => '举报提交成功'];
          } else {
            $response['message'] = '举报提交失败';
          }
        }
      } else {
        $response['message'] = '请填写完整的举报信息';
      }
      break;

    case 'share':
      $content_type = isset($_POST['content_type']) ? $_POST['content_type'] : '';
      $content_id = isset($_POST['content_id']) ? intval($_POST['content_id']) : 0;
      $user_id = $is_logged_in ? $_SESSION['user_id'] : null;

      if (!empty($content_type) && $content_id > 0) {
        $result = handleShare($content_type, $content_id, $user_id);
        if ($result && $result['success']) {
          $response = ['success' => true, 'message' => '分享成功！', 'share_count' => $result['share_count']];
        } else {
          $response['message'] = '分享失败，请稍后重试';
        }
      } else {
        $response['message'] = '无效的操作参数';
      }
      break;

    case 'purchase_post':
      $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

      if ($post_id > 0) {
        if ($is_user_banned) {
          $response = ['success' => false, 'message' => '您的账号已被封禁'];
        } elseif (!$is_logged_in) {
          $response = ['success' => false, 'message' => '请先登录后再购买'];
        } else {
          $result = purchasePost($_SESSION['user_id'], $post_id);
          if ($result['success']) {
            $response = ['success' => true, 'message' => $result['message']];
          } else {
            $response['message'] = $result['message'];
          }
        }
      } else {
        $response['message'] = '无效的文章ID';
      }
      break;
  }

  ob_clean();
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($response, JSON_UNESCAPED_UNICODE);
  exit;
}

// 检查文章是否存在
if (!$post) {
  header('HTTP/1.0 404 Not Found');
  echo '404 - 文章不存在或已被删除';
  exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{qkcms:posts_title}-{qkcms:site_name}</title>
  <meta name="keywords" content="{qkcms:posts_keywords}">
  <meta name="description" content="{qkcms:posts_description}">
  <script>
    (function () {
      try {
        if (localStorage.getItem('post_sidebar_collapsed') === 'true') {
          document.documentElement.classList.add('qk-post-sidebar-collapsed');
        }
      } catch (e) {}
    })();
  </script>
  <style>
    body.qk-post0 .topics-section.content,
    body.qk-post0 .buy-content-block {
      overflow: hidden;
    }

    body.qk-post0 .topics-section.content .ql-align-center,
    body.qk-post0 .buy-content-block .ql-align-center {
      text-align: center;
    }

    body.qk-post0 .topics-section.content .ql-align-right,
    body.qk-post0 .buy-content-block .ql-align-right {
      text-align: right;
    }

    body.qk-post0 .topics-section.content .ql-align-justify,
    body.qk-post0 .buy-content-block .ql-align-justify {
      text-align: justify;
    }

    body.qk-post0 .topics-section.content img,
    body.qk-post0 .buy-content-block img {
      max-width: 100% !important;
      height: auto !important;
      display: block;
      box-sizing: border-box;
    }

    body.qk-post0 .topics-section.content .ql-align-center img,
    body.qk-post0 .buy-content-block .ql-align-center img,
    body.qk-post0 .topics-section.content .ql-align-center video,
    body.qk-post0 .buy-content-block .ql-align-center video,
    body.qk-post0 .topics-section.content .ql-align-center iframe,
    body.qk-post0 .buy-content-block .ql-align-center iframe {
      margin-left: auto;
      margin-right: auto;
    }

    body.qk-post0 .topics-section.content .ql-align-right img,
    body.qk-post0 .buy-content-block .ql-align-right img,
    body.qk-post0 .topics-section.content .ql-align-right video,
    body.qk-post0 .buy-content-block .ql-align-right video,
    body.qk-post0 .topics-section.content .ql-align-right iframe,
    body.qk-post0 .buy-content-block .ql-align-right iframe {
      margin-left: auto;
      margin-right: 0;
    }
  </style>
  <link href="/assets/quill/quill.snow.css" rel="stylesheet">
  <link rel="stylesheet" href="/assets/css/ts_comment.css" />
  <link rel="stylesheet" href="/assets/css/ts_post.css" />
</head>
<body class="qk-post0">

{qkcms:head.html}
  <main class="main-content">
    <div class="container">
      <div class="content-layout" id="contentLayout">
        <div class="main-column" id="mainColumn">
          <section class="category-header-section" style="height:188px;">
            
            <div class="sidebar-toggle-btn" id="sidebarToggleBtn" title="收起侧边栏">
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="9 18 15 12 9 6"></polyline>
              </svg>
            </div>
            <div class="category-header-content">
              <div class="category-info">
                <div class="category-title-container">
                  <h1 class="category-title">
                    <span class="category-title-text">{qkcms:posts_title}</span>
                      <?php if ($qk_stamp_plugin_exists && $qk_stamp_enabled): ?>
                        <button type="button" class="post-stamp-btn" id="postStampBtn" data-post-id="<?php echo $post_id; ?>" data-post-title="<?php echo isset($post['title']) ? htmlspecialchars($post['title'], ENT_QUOTES) : ''; ?>" data-post-property="{qkcms:posts_property}" data-post-property-id="<?php $pp = get_single_row($GLOBALS['conn'], 'SELECT property FROM posts WHERE id = ?', array($post_id)); echo isset($pp['property']) ? intval($pp['property']) : 0; ?>" data-require-login="1" data-login-action="stamp" style="display:none">盖章</button>
                      <?php endif; ?>
                  </h1>
                  <div class="post-admin-tools">
                    <div class="category-meta"> <a class="post2" href="{qkcms:posts_category_url}">{qkcms:posts_category}</a> </div>
                  </div>
                </div>
              
                <div class="category-details">
                  <div class="category-thumbnail"> <img src="{qkcms:posts_thumbnail}" alt="{qkcms:cat_name}" /> </div>
                  <div class="category-description">
                    <p>{qkcms:posts_description}</p>
                    <div class="category-keywords tags-wrapper" style="margin-top: 15px;">{qkcms:posts_keywords_links}</div>
                  </div>
                </div>
              </div>
            </div>

            
          </section>
          <div class="topics-section content<?php echo (!$post_password_access_granted && $post_password_required !== '') ? ' post-password-content is-locked' : ''; ?>" style="padding-bottom: 25px;">
            <div class="post-content-head">
              <h3 class="trending-header">文章详情</h3>
              <div class="post-content-position">{qkcms:current_position}</div>
            </div>
            <?php
            /**
             * 处理代码块功能
             * @param string $content 原始内容
             * @return string 处理后的内容
             */
            function processCodeBlocks($content)
            {
              // 检查是否已经处理过代码块（避免递归处理）
              if (strpos($content, 'code-block-container') !== false) {
                return $content;
              }

              // 1. 处理带标记的代码块 [qkcms:code]...[/qkcms:code]
              $content = preg_replace_callback('/\[qkcms:code\]([\s\S]*?)\[\/qkcms:code\]/i', function ($matches) {
                $code = $matches[1];
                // 清理代码内容
                $code = trim($code);
                // 确保代码不为空
                if (empty($code)) {
                  $code = '// 空代码块';
                }
                return formatCodeBlock($code);
              }, $content);

              return $content;
            }

            /**
             * 格式化代码块
             * @param string $code 代码内容
             * @return string 格式化后的代码块HTML
             */
            function formatCodeBlock($code)
            {
              // 确保代码内容不为空
              if (empty($code)) {
                $code = '// 空代码块';
              }

              // 检查代码是否包含HTML转义字符，如果是则解码
              if (strpos($code, '&lt;') !== false || strpos($code, '&gt;') !== false || strpos($code, '&amp;') !== false) {
                $code = htmlspecialchars_decode($code, ENT_QUOTES);
              }

              // 处理HTML换行标签，转换为换行符
              $code = str_replace('<br>', "\n", $code);
              $code = str_replace('<br/>', "\n", $code);
              $code = str_replace('<br />', "\n", $code);
              $code = str_replace('</p>', "\n", $code);
              $code = str_replace('</div>', "\n", $code);
              $code = str_replace('</li>', "\n", $code);

              // 移除HTML开始标签（保留内容）
              $code = preg_replace('/<p[^>]*>/', '', $code);
              $code = preg_replace('/<div[^>]*>/', '', $code);
              $code = preg_replace('/<li[^>]*>/', '', $code);

              // 保留换行符，不要在HTML转义中丢失
              $code = str_replace("\r\n", "\n", $code);
              $code = str_replace("\r", "\n", $code);

              // 生成唯一ID用于复制按钮
              $codeId = 'code-' . uniqid();

              // 将代码按行分割，为每行生成对应的行号
              $lines = explode("\n", $code);
              $lineCount = count($lines);

              // 生成带行号的代码HTML - 不转义HTML特殊字符，保持富文本格式
              $codeWithLineNumbers = '';
              for ($i = 0; $i < $lineCount; $i++) {
                $lineNumber = $i + 1;
                // 不转义HTML特殊字符，直接显示原始内容
                $lineContent = $lines[$i];
                // 跳过空行（可选）
                if (trim($lineContent) === '' && $i < $lineCount - 1) {
                  // 保留空行但显示为空
                  $lineContent = '';
                }
                $codeWithLineNumbers .= '<div class="code-line">';
                $codeWithLineNumbers .= '<span class="line-number">' . $lineNumber . '</span>';
                $codeWithLineNumbers .= '<span class="line-content">' . $lineContent . '</span>';
                $codeWithLineNumbers .= '</div>';
              }

              // 将原始代码存储在data属性中，用于复制时使用
              $encodedCode = base64_encode($code);

              // 返回格式化后的代码块
              return '<div class="code-block-container">'
                . '<div class="code-block-header">'
                . '<button class="copy-code-btn" data-code-id="' . $codeId . '" data-original-code="' . $encodedCode . '">复制</button>'
                . '</div>'
                . '<div class="code-block-content" id="' . $codeId . '">'
                . $codeWithLineNumbers
                . '</div>'
                . '</div>';
            }

            if ($post_password_access_granted || $post_password_required === '') {
              $points_required = 0;
              $has_purchased = false;
              $has_purchase_identifier = false;
              $content_without_purchase = '';

              if (isset($_SESSION['user_id'])) {
                $user = get_single_row($GLOBALS['conn'], "SELECT points FROM users WHERE id = ?", array($_SESSION['user_id']));
                if ($user && isset($user['points'])) {
                  $_SESSION['user_points'] = intval($user['points']);
                }
              }

              if ($post && isset($post['points'])) {
                $points_required = intval($post['points']);
              }

              if (isset($_SESSION['user_id'])) {
                $has_purchased = hasPurchasedPost($_SESSION['user_id'], $post_id);
              }

              $content_result = get_single_row($GLOBALS['conn'], "SELECT content FROM posts WHERE id = ?", array($post_id));
              if ($content_result && isset($content_result['content'])) {
                $content = $content_result['content'];
                $has_purchase_identifier = strpos($content, '[qkcms:buy') !== false && strpos($content, '[/qkcms:buy]') !== false;
              }

              if (!$has_purchased && $has_purchase_identifier) {
                $paid_content = '';
                if (preg_match('/\[qkcms:buy——(\d+)个积分\]([\s\S]*?)\[\/qkcms:buy\]/', $content, $matches)) {
                  $points = isset($matches[1]) ? $matches[1] : $points_required;
                  $paid_content = isset($matches[2]) ? $matches[2] : '';
                }

                if (strpos($paid_content, '[qkcms:code]') !== false) {
                  $paid_content = processCodeBlocks($paid_content);
                }

                echo '<script>';
                echo 'window.paidContent = ' . json_encode($paid_content) . ';';
                echo '</script>';

                $content_processed = $content;

                if (strpos($content_processed, '[qkcms:code]') !== false) {
                  $content_processed = processCodeBlocks($content_processed);
                }

                $content_processed = preg_replace_callback('/\[qkcms:buy——(\d+)个积分\]([\s\S]*?)\[\/qkcms:buy\]/', function ($matches) use ($post_id) {
                  $points = isset($matches[1]) ? $matches[1] : 0;
                  return '<div class="buy-content-block"><div><div class="buy-content-info"><div class="buy-content-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg></div><div class="buy-content-text"><span>此内容需付费后浏览</span><span>需购买后查看</span></div><span class="points-badge">' . $points . '积分</span></div><div class="buy-content-actions"><button class="buy-post-btn" data-require-login="1" data-login-action="buy" data-post-id="' . $post_id . '">立即解锁</button><button class="ignore-post-btn">忽略</button></div></div></div>';
                }, $content_processed);

                echo $content_processed;
              } else {
                $content_clean = preg_replace('/\[qkcms:buy——(\d+)个积分\]([\s\S]*?)\[\/qkcms:buy\]/', '$2', $content);

                if (strpos($content_clean, '[qkcms:code]') !== false) {
                  $content_clean = processCodeBlocks($content_clean);
                }

                echo $content_clean;
              }
            } else {
              echo '<div class="post-password-placeholder" aria-hidden="true"></div>';
            }
            ?>

            <?php if (!$post_password_access_granted && $post_password_required !== ''): ?>
              <div class="post-password-overlay">
                <div class="post-password-panel">
                  <div class="post-password-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                      <rect x="3" y="11" width="18" height="10" rx="2"></rect>
                      <path d="M7 11V8a5 5 0 0 1 10 0v3"></path>
                    </svg>
                  </div>
                  <div class="post-password-title">本文需要密码才可访问</div>
                  <form method="post" class="post-password-form js-post-password-form">
                    <input type="hidden" name="post_password_submit" value="1">
                    <input type="hidden" name="post_password_post_id" value="<?php echo intval($post_id); ?>">
                    <input type="password" name="post_password" class="post-password-input" placeholder="请输入访问密码" autocomplete="off">
                    <button type="submit" class="post-password-button">确认访问</button>
                  </form>
                </div>
              </div>
            <?php endif; ?>

            <script>
              <?php if ($post_password_error !== ''): ?>
              if (typeof showToast === 'function') {
                showToast('<?php echo addslashes($post_password_error); ?>', 'error');
              } else {
                alert('<?php echo addslashes($post_password_error); ?>');
              }
              <?php endif; ?>
              function bindPostPasswordForms() {
                const passwordForms = document.querySelectorAll('.js-post-password-form');
                passwordForms.forEach(form => {
                  form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    if (form.dataset.submitting === '1') return;
                    const submitButton = form.querySelector('.post-password-button');
                    const passwordInput = form.querySelector('.post-password-input');
                    if (!submitButton || !passwordInput) return;
                    const formData = new FormData(form);
                    formData.append('post_password_ajax', '1');
                    form.dataset.submitting = '1';
                    submitButton.disabled = true;
                    fetch(window.location.href, {
                      method: 'POST',
                      body: formData,
                      headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                      },
                      credentials: 'same-origin'
                    }).then(response => response.json()).then(result => {
                      if (typeof showToast === 'function') {
                        showToast(result.message || (result.success ? '密码验证成功' : '密码验证失败'), result.success ? 'success' : 'error');
                      } else if (!result.success) {
                        alert(result.message || '密码验证失败');
                      }
                      if (result.success) {
                        setTimeout(function() {
                          window.location.reload();
                        }, 240);
                        return;
                      }
                      passwordInput.focus();
                      passwordInput.select();
                    }).catch(() => {
                      if (typeof showToast === 'function') {
                        showToast('请求失败，请稍后重试', 'error');
                      } else {
                        alert('请求失败，请稍后重试');
                      }
                    }).finally(() => {
                      delete form.dataset.submitting;
                      submitButton.disabled = false;
                    });
                  });
                });
              }
              // 复制代码功能
              function bindCopyButtons() {
                const copyButtons = document.querySelectorAll('.copy-code-btn');

                copyButtons.forEach(button => {
                  button.addEventListener('click', function() {
                    // 获取代码块容器
                    const codeContainer = this.closest('.code-block-container');
                    if (!codeContainer) return;

                    // 获取代码内容区域
                    const codeContent = codeContainer.querySelector('.code-block-content');
                    if (!codeContent) return;

                    // 提取纯文本代码（移除HTML标签，保留纯文本和换行）
                    let codeText = '';
                    const lines = codeContent.querySelectorAll('.code-line');
                    lines.forEach((line, index) => {
                      const lineContent = line.querySelector('.line-content');
                      if (lineContent) {
                        // 获取纯文本内容，保留原始格式
                        let text = lineContent.innerText || lineContent.textContent;
                        // 添加换行符（除了最后一行）
                        if (index < lines.length - 1) {
                          text += '\n';
                        }
                        codeText += text;
                      }
                    });

                    // 移除开头和结尾的空行
                    codeText = codeText.replace(/^\n+/, '').replace(/\n+$/, '');

                    // 移除多余的空行（连续的多个换行符替换为一个）
                    codeText = codeText.replace(/\n\s*\n/g, '\n');

                    navigator.clipboard.writeText(codeText).then(() => {
                      // 显示复制成功状态
                      const originalText = this.textContent;
                      this.textContent = '已复制';
                      this.classList.add('copied');

                      // 2秒后恢复原状
                      setTimeout(() => {
                        this.textContent = originalText;
                        this.classList.remove('copied');
                      }, 2000);
                    });
                  });
                });
              }

              document.addEventListener('DOMContentLoaded', function() {
                bindPostPasswordForms();
                bindCopyButtons();
              });
            </script>
          </div>

          <section class="category-header-section" >
          
            <h3 class="trending-header" style="border-bottom: 1px solid var(--border);  padding-bottom: 20px;">{qkcms:posts_title}评论区</h3>
          
          {qkcms:comment.php} 

          </section>
        </div>


        <aside class="sidebar" id="sidebar">
          <div class="trending-topics text-center" style="height:194px;">  <img src="{qkcms:posts_author_avatar}" class="post1">
            <h4 class="author-title">作者：{qkcms:posts_author} </h4>
            <a href="/Member_id{qkcms:posts_author_id}.html" class="btn sidebar-post-btn author-home-btn"> 进入作者主页 </a>
          </div>
          <div class="trending-topics fade-in">
            <h3 class="trending-header">热门文章</h3>
            <div class="trending-list"> {qkcms:articles row=8 order=hot titlelen=40 } <a href="{url}" class="trending-item spaced-item">
                <div class="trending-rank  warm">{title_id}</div>
                <div class="trending-content">
                  <div class="trending-title">{title}</div>
                  <div class="trending-meta"> {views} 浏览 · {comments} 评论</div>
                </div>
              </a> {/qkcms:articles} </div>
          </div>
          <div class="events-section fade-in">
            <h3 class="events-header">全站公告</h3>
            {qkcms:articles row=3 property=4 category_id=-1 titlelen=40} <a href="{url}" class="event-item">
              <div class="event-date">
                <div class="event-month">{date_mo}月</div>
                <div class="event-day">{date_dy}</div>
              </div>
              <div class="event-info">
                <div class="event-title">{title}</div>
                <div class="event-location">{keywords}</div>
              </div>
            </a> {/qkcms:articles}
          </div>
        </aside>
      </div>
    </div>

    
    <div class="vertical-actions">
      <button class="vertical-action-btn like-button" data-require-login="1" data-login-action="like" data-type="post" data-id="<?php echo $post_id; ?>" title="点赞"> <span class="icon icon-like <?php echo $post['is_liked'] ? 'liked' : ''; ?>"></span>
        <div class="count-badge">{qkcms:posts_like_count}</div>
        <div class="action-tooltip">点赞</div>
      </button>
      <button class="vertical-action-btn share-button" data-require-login="1" data-login-action="share" data-id="<?php echo $post_id; ?>" title="分享"> <span class="icon icon-share"></span>
        <div class="count-badge">{qkcms:posts_share_count}</div>
        <div class="action-tooltip">分享</div>
      </button>
      <button class="vertical-action-btn report-button" data-require-login="1" data-login-action="report" data-type="post" data-id="<?php echo $post_id; ?>" title="举报"> <span class="icon icon-report"></span>
        <div class="count-badge">{qkcms:posts_report_count}</div>
        <div class="action-tooltip">举报</div>
      </button>
      <button class="vertical-action-btn view-button" title="浏览量"> <span class="icon icon-view"></span>
        <div class="count-badge">{qkcms:posts_views}</div>
        <div class="action-tooltip">浏览量</div>
      </button>
    </div>

    
    <div id="report-modal" class="modal">
      <div class="modal-backdrop"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">举报</h3>
          <button type="button" id="close-report-modal" class="modal-close" onclick="closeReportModal()">×</button>
        </div>
        <div class="modal-body">
          <form id="report-form">
            <input type="hidden" id="report-type" name="report-type">
            <input type="hidden" id="report-id" name="report-id">
            <div class="form-group">
              <label for="report-reason">举报原因</label>
              <textarea id="report-reason" name="content" class="form-control" rows="5" required></textarea>
            </div>
          </form>
        </div>
        <div class="modal-actions">
          <button type="submit" id="submitReport" class="submit-button" data-require-login="1" data-login-action="report" onclick="submitReportForm()">提交</button>
        </div>
      </div>
    </div>
  </main>
  <script>
    // 全局变量
    window.isUserBanned = <?php echo $is_user_banned ? 'true' : 'false'; ?>;
    window.isLoggedIn = <?php echo $is_logged_in ? 'true' : 'false'; ?>;
    window.postId = <?php echo $post_id; ?>;
    window.posts_points = <?php echo isset($post['points']) ? intval($post['points']) : 0; ?>;
    window.userHasPurchased = <?php echo (isset($_SESSION['user_id']) && hasPurchasedPost($_SESSION['user_id'], $post_id)) ? 'true' : 'false'; ?>;
    window.userPoints = <?php echo isset($_SESSION['user_points']) ? $_SESSION['user_points'] : 0; ?>;
    // 从PHP常量获取默认头像和缩略图路径
    window.DEFAULT_AVATAR_PATH = '<?php echo DEFAULT_AVATAR_PATH; ?>';
    window.DEFAULT_THUMBNAIL_PATH = '<?php echo DEFAULT_THUMBNAIL_PATH; ?>';
    try{ if(typeof DEFAULT_AVATAR_PATH === 'undefined'){ DEFAULT_AVATAR_PATH = window.DEFAULT_AVATAR_PATH; } }catch(e){}
    try{ if(typeof DEFAULT_THUMBNAIL_PATH === 'undefined'){ DEFAULT_THUMBNAIL_PATH = window.DEFAULT_THUMBNAIL_PATH; } }catch(e){}
  </script>
  <script src="/assets/js/post.js"></script>
  <script>
    // 处理购买文章
    document.addEventListener('DOMContentLoaded', function() {
      // 为所有购买按钮添加点击事件
      document.querySelectorAll('.buy-post-btn').forEach(function(button) {

        // 添加点击事件
        button.addEventListener('click', function() {
          const postId = this.getAttribute('data-post-id');
          const buyBlock = this.closest('.buy-content-block');

          // 检查用户是否被封禁
          if (window.isUserBanned) {
            showToast('您的账号已被封禁', 'error');
            return;
          }

          // 发送购买请求
          fetch(window.location.href, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
              },
              credentials: 'include',
              body: 'action=purchase_post&post_id=' + postId
            })
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                showToast(data.message, 'success');
                // 购买成功后，用付费内容替换整个付费块
                if (buyBlock && window.paidContent) {
                  // 用付费内容替换整个buyBlock
                  buyBlock.outerHTML = window.paidContent;
                  // 重新绑定复制按钮的事件监听器
                  bindCopyButtons();
                }
                // 更新页面积分显示
                if (data.new_points !== undefined) {
                  // 更新session中的积分值
                  window.userPoints = data.new_points;
                  // 更新导航右上角的账号积分
                  const userMenuItems = document.querySelectorAll('.user-menu-item');
                  userMenuItems.forEach(item => {
                    const label = item.querySelector('.menu-label');
                    if (label) {
                      if (label.textContent.includes('用户积分')) {
                        const value = item.querySelector('.menu-value');
                        if (value) {
                          value.textContent = data.new_points;
                        }
                      }
                    }
                  });
                }
              } else {
                if (data.message.includes('积分不足')) {
                  // 使用全局确认框提示
                  confirmDialog('很抱歉，你的积分不足 是否立即去充值？', function() {
                    // 新窗口打开充值页面
                    window.open('/recharge.php', '_blank');
                  });
                } else {
                  showToast(data.message, 'error');
                }
              }
            })
            .catch(error => {
              showToast('购买失败，请稍后重试', 'error');
            });
        });
      });

      // 为所有忽略按钮添加点击事件
      document.querySelectorAll('.ignore-post-btn').forEach(function(button) {
        button.addEventListener('click', function() {
          const buyBlock = this.closest('.buy-content-block');
          if (buyBlock) {
            buyBlock.style.display = 'none';
          }
        });
      });
    });
  </script>

  
  <script>
    (function() {
      const toggleBtn = document.getElementById('sidebarToggleBtn');
      const contentLayout = document.getElementById('contentLayout');
      const mainColumn = document.getElementById('mainColumn');
      const sidebar = document.getElementById('sidebar');

      // 从localStorage读取状态
      const isCollapsed = localStorage.getItem('post_sidebar_collapsed') === 'true';

      // 初始化状态
      if (isCollapsed) {
        document.body.classList.add('sidebar-collapsed');
        document.documentElement.classList.add('qk-post-sidebar-collapsed');
        toggleBtn.title = '展开侧边栏';
        toggleBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>`;
      } else {
        document.documentElement.classList.remove('qk-post-sidebar-collapsed');
      }

      // 点击切换
      toggleBtn.addEventListener('click', function() {
        const isNowCollapsed = document.body.classList.toggle('sidebar-collapsed');
        localStorage.setItem('post_sidebar_collapsed', isNowCollapsed);
        if (isNowCollapsed) {
          document.documentElement.classList.add('qk-post-sidebar-collapsed');
        } else {
          document.documentElement.classList.remove('qk-post-sidebar-collapsed');
        }

        if (isNowCollapsed) {
          this.title = '展开侧边栏';
          // 收起状态：左箭头
          this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>`;
        } else {
          this.title = '收起侧边栏';
          // 展开状态：右箭头
          this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>`;
        }
      });
    })();
  </script>
  <?php if (!empty($qk_stamp_plugin_exists) && $qk_stamp_enabled): ?>
    {qk_Plugin:ID40}
<?php endif; ?>
{qkcms:footer.html}
</body>
</html>
</html>
