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


if (!defined('ADMIN_LOADED')) {
  header('HTTP/1.1 403 Forbidden');
  exit('Access Denied');
}

$comment_helper_plugin_file = __DIR__ . '/Plugin/39_CommentMgr.php';
$has_comment_helper_plugin = is_file($comment_helper_plugin_file) && is_readable($comment_helper_plugin_file);

// 处理单个评论状态更新的请求
global $conn;
if (isset($_POST['update_comment_status']) && isset($_POST['comment_id']) && isset($_POST['status'])) {
  $comment_id = intval($_POST['comment_id']);
  $status = intval($_POST['status']);
  $sql = "UPDATE comments SET status = ? WHERE id = ?";
  $result = execute_non_query($conn, $sql, array($status, $comment_id));
  if ($result !== false) {
    echo '<script>showBlackOverlayMessage(\'评论状态已更新！\'); setTimeout(function() { window.location.href = \'?tab=comments\'; }, 2000);</script>';
  } else {
    echo '<script>showBlackOverlayMessage(\'评论状态更新失败！\'); setTimeout(function() { window.location.href = \'?tab=comments\'; }, 2000);</script>';
  }
  exit;
}

// 处理单个评论删除（支持 ajax=1）
if (isset($_GET['delete_comment'])) {
  $comment_id = intval($_GET['delete_comment']);
  $ok = false;
  if ($comment_id > 0) {
    extractAndDeleteCommentImages($comment_id, $conn);
    execute_non_query($conn, "DELETE FROM reports WHERE content_type = 'comment' AND content_id = ?", array($comment_id));
    $res = execute_non_query($conn, "DELETE FROM comments WHERE id = ?", array($comment_id));
    $ok = ($res !== false) && (!isset($res['affected_rows']) || $res['affected_rows'] > 0);
  }

  if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    echo $ok ? 'success' : 'error';
    exit;
  }

  if ($ok) {
    echo '<script>showToast(\'评论已成功删除！\', \'success\', 2000);setTimeout(function(){window.location.href=\'?tab=comments\';}, 1000);</script>';
  } else {
    echo '<script>showToast(\'删除评论失败，请重试！\', \'error\', 2000);</script>';
  }
  exit;
}

if (isset($_POST['perform_batch_action']) && (string)$_POST['perform_batch_action'] === '1') {
  header('Content-Type: application/json; charset=utf-8');
  $op = isset($_POST['batch_action']) ? (string)$_POST['batch_action'] : '';
  $raw_ids = isset($_POST['comment_ids']) ? (string)$_POST['comment_ids'] : '';
  $ids = array_filter(array_map('intval', preg_split('/\s*,\s*/', $raw_ids, -1, PREG_SPLIT_NO_EMPTY)), function ($v) {
    return $v > 0;
  });
  $ids = array_values(array_unique($ids));
  if (empty($ids)) {
    echo json_encode(array('success' => false, 'message' => '请先选择要操作的评论'), JSON_UNESCAPED_UNICODE);
    exit;
  }

  if ($op !== 'approve' && $op !== 'pending' && $op !== 'delete') {
    echo json_encode(array('success' => false, 'message' => '无效操作'), JSON_UNESCAPED_UNICODE);
    exit;
  }

  $placeholders = implode(',', array_fill(0, count($ids), '?'));
  if ($op === 'approve' || $op === 'pending') {
    $status = ($op === 'approve') ? 1 : 0;
    $sql = "UPDATE comments SET status = ? WHERE id IN ($placeholders)";
    $params = array_merge(array($status), $ids);
    $res = execute_non_query($conn, $sql, $params);
    if ($res !== false) {
      echo json_encode(array('success' => true, 'message' => '批量操作成功'), JSON_UNESCAPED_UNICODE);
    } else {
      echo json_encode(array('success' => false, 'message' => '批量操作失败'), JSON_UNESCAPED_UNICODE);
    }
    exit;
  }

  foreach ($ids as $cid) {
    extractAndDeleteCommentImages($cid, $conn);
  }
  execute_non_query($conn, "DELETE FROM reports WHERE content_type = 'comment' AND content_id IN ($placeholders)", $ids);
  $res = execute_non_query($conn, "DELETE FROM comments WHERE id IN ($placeholders)", $ids);
  if ($res !== false) {
    echo json_encode(array('success' => true, 'message' => '批量删除成功'), JSON_UNESCAPED_UNICODE);
  } else {
    echo json_encode(array('success' => false, 'message' => '批量删除失败'), JSON_UNESCAPED_UNICODE);
  }
  exit;
}

// 处理批量评论状态更新的请求
if (isset($_POST['batch_update_comments_status']) && isset($_POST['comment_ids']) && isset($_POST['status'])) {
  $comment_ids = $_POST['comment_ids'];
  $status = intval($_POST['status']);
  if (!is_array($comment_ids)) {
    $comment_ids = explode(',', $comment_ids);
  }
  $valid_ids = array_filter($comment_ids, function ($id) {
    return is_numeric($id) && intval($id) > 0;
  });
  if (!empty($valid_ids)) {
    $placeholders = implode(',', array_fill(0, count($valid_ids), '?'));
    $sql = "UPDATE comments SET status = ? WHERE id IN ($placeholders)";
    $params = array_merge(array($status), $valid_ids);
    $result = execute_non_query($conn, $sql, $params);
    if ($result !== false) {
      echo '<script>showBlackOverlayMessage(\'已成功更新 ' . count($valid_ids) . ' 条评论的状态！\'); setTimeout(function() { window.location.href = \'?tab=comments\'; }, 2000);</script>';
    } else {
      echo '<script>showBlackOverlayMessage(\'批量更新评论状态失败！\'); setTimeout(function() { window.location.href = \'?tab=comments\'; }, 2000);</script>';
    }
  } else {
    echo '<script>showBlackOverlayMessage(\'没有找到有效的评论ID！\'); setTimeout(function() { window.location.href = \'?tab=comments\'; }, 2000);</script>';
  }
  exit;
}

// 处理编辑评论的请求
if (isset($_POST['edit_comment_submit']) && isset($_POST['comment_id']) && isset($_POST['content'])) {
  $comment_id = intval($_POST['comment_id']);
  $content = trim($_POST['content']);
  $status = intval($_POST['status']);

  if (empty($content)) {
    echo json_encode(array('success' => false, 'message' => '评论内容不能为空'));
    exit;
  }

  $sql = "UPDATE comments SET content = ?, status = ? WHERE id = ?";
  $result = execute_non_query($conn, $sql, array($content, $status, $comment_id));
  if ($result !== false) {
    echo json_encode(array('success' => true, 'message' => '评论更新成功'));
  } else {
    echo json_encode(array('success' => false, 'message' => '评论更新失败'));
  }
  exit;
}


?>
<script>
  // 评论列表渲染函数（供公用分页组件使用）
  function renderCommentsList(data) {
    const tbody = document.querySelector('.admin-table.comment-manage tbody');
    if (!tbody || !data.comments) return;

    tbody.innerHTML = '';
    if (!data.comments || data.comments.length === 0) {
      tbody.innerHTML = '<tr><td colspan="7" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
      return;
    }

    function escapeHtmlAttr(str) {
      if (typeof str !== 'string') return '';
      return str.replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
    }

    function escapeHtml(str) {
      if (typeof str !== 'string') return '';
      return str.replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
    }

    data.comments.forEach(comment => {
      const row = document.createElement('tr');
      const tmp = document.createElement('div');
      tmp.innerHTML = String(comment.content || '');
      const fullText = (tmp.textContent || tmp.innerText || '').trim();
      const hasImages = /<img/i.test(comment.content || '');
      const isOnlyImages = hasImages && fullText.length === 0;
      const contentDisplay = isOnlyImages ? '本条为纯图片评论 无内容' : (fullText.length > 50 ? fullText.substring(0, 50) + '...' : fullText);
      const tooltipText = isOnlyImages ? '本条为纯图片评论 无内容' : fullText;

      row.innerHTML = `
        <td><input type="checkbox" class="comment-checkbox" value="${comment.id}"></td>
        <td>${comment.id}</td>
        <td class="comment-content" style="${comment.status == 0 ? ' opacity: 0.6;' : ''}"><span class="comment-content-text" data-qk-tip="${escapeHtmlAttr(tooltipText)}">${escapeHtml(contentDisplay)}</span></td>
        <td>${escapeHtml(comment.username || '-')}</td>
        <td>${typeof window.formatDateYMD === 'function' ? window.formatDateYMD(comment.created_at) : '-'}</td>
        <td class="text-center">
          <form method="post" class="inline-form">
            <input type="hidden" name="comment_id" value="${comment.id}">
            <input type="hidden" name="status" value="${comment.status ? '1' : '0'}">
            <input type="hidden" name="update_comment_status" value="1">
            <label class="theme-switch">
              <input type="checkbox" class="form-checkbox" ${comment.status ? 'checked' : ''} onchange="toggleCommentStatus(this)">
              <span class="slider round"></span>
            </label>
          </form>
        </td>
        <td class="action-buttons-right">
          <a href="/post_id${comment.article_id}.php" target="_blank" class="btn btn-sm btn-secondary">预览</a>
          <button type="button" class="btn btn-sm btn-primary" data-comment-id="${comment.id}" data-comment-content="${escapeHtmlAttr(comment.content || '')}" data-comment-status="${comment.status}" onclick="openEditCommentModal(this.dataset.commentId, this.dataset.commentContent, this.dataset.commentStatus)">编辑</button>
          <form method="post" class="inline-form" style="display:inline;">
            <input type="hidden" name="delete_comment" value="${comment.id}">
            <button type="button" onclick="confirmDeleteComment(${comment.id})" class="btn btn-sm btn-danger">删除</button>
          </form>
        </td>
      `;
      tbody.appendChild(row);
    });
  }
</script>
<style>
  #status-select,
  #comment-batch-operation {
    height: 46px !important;
    line-height: 46px !important;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }

  @media (max-width: 768px) {
    #status-form {
      display: none !important;
    }

    #comment-batch-operation {
      height: 38px !important;
      line-height: 38px !important;
    }
  }
</style>
<style>
  /* 列表右上角按钮样式 */
  .section-header-mobile-btn {
    width: 128px;
  }

  /* 列表右上角按钮手机端样式 - 使用更高优先级覆盖admin.css */
  @media (max-width: 768px) {

    .section-header .section-header-mobile-btn,
    .section-header .btn-danger.section-header-mobile-btn,
    .section-header .btn-primary.section-header-mobile-btn {
      width: 38px !important;
      height: 38px !important;
      min-width: 38px !important;
      padding: 0 !important;
      margin-left: 6px !important;
      line-height: 38px !important;
    }

    .section-header-mobile-btn .section-header-btn-text {
      display: none !important;
    }

    .section-header-mobile-btn .section-header-btn-icon {
      margin-right: 0 !important;
    }
  }
</style>
<div class="section-header">
  <h2>评论管理</h2>
  <div class="action-buttons">
    <form method="get" class="inline-form" id="status-form">
      <input type="hidden" name="tab" value="comments">
      <?php if (isset($_GET['search'])): ?>
        <input type="hidden" name="search" value="<?php echo escape($_GET['search']); ?>">
      <?php endif; ?>
      <select id="status-select" name="status" class="form-control comment-status-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
        <option value="all" <?php echo !isset($_GET['status']) || $_GET['status'] == 'all' ? 'selected' : ''; ?>>全部评论</option>
        <option value="approved" <?php echo isset($_GET['status']) && $_GET['status'] == 'approved' ? 'selected' : ''; ?>>已审核</option>
        <option value="pending" <?php echo isset($_GET['status']) && $_GET['status'] == 'pending' ? 'selected' : ''; ?>>待审核</option>
      </select>
    </form>
    <script>
      var changeStatus = function(status) {
        if (typeof HeaderPagination !== 'undefined') {
          const urlParams = new URLSearchParams(window.location.search);
          if (status === 'all') {
            urlParams.delete('status');
          } else {
            urlParams.set('status', status);
          }
          urlParams.set('page', '1');

          const newUrl = window.location.pathname + '?' + urlParams.toString();
          window.history.pushState({}, document.title, newUrl);

          HeaderPagination.state.page = 1;
          HeaderPagination.load();
        }
      };

      document.addEventListener('DOMContentLoaded', function() {
        var statusSelect = document.getElementById('status-select');
        if (statusSelect && !statusSelect.getAttribute('data-bound')) {
          statusSelect.setAttribute('data-bound', 'true');
          statusSelect.addEventListener('change', function(e) {
            e.preventDefault();
            e.stopPropagation();
            changeStatus(this.value);
          }, false);
        }
      });
    </script>


    <form method="post" class="inline-form ml-2" id="comment-batch-operation-form" onsubmit="return false;">
      <input type="hidden" name="comment_ids" id="comment-batch-comment-ids" value="">
      <?php if (isset($_GET['status'])): ?>
        <input type="hidden" name="status" value="<?php echo $_GET['status']; ?>">
      <?php endif; ?>
      <?php if (isset($_GET['search'])): ?>
        <input type="hidden" name="search" value="<?php echo escape($_GET['search']); ?>">
      <?php endif; ?>
      <select id="comment-batch-operation" class="form-control batch-action-select" style="margin-right: 15px; margin-left: -15px; width: auto;">
        <option value="">批量操作</option>
        <option value="approve">批量审核</option>
        <option value="pending">批量待审</option>
        <option value="delete">批量删除</option>
      </select>
    </form>
    <?php if ($has_comment_helper_plugin): ?>
      <button type="button" id="open-comment-helper-btn" class="btn btn-primary action-button section-header-mobile-btn" style="display: inline-flex; align-items: center; justify-content: center;">
        <svg class="section-header-btn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
        </svg>
        <span class="section-header-btn-text">评论助手</span>
      </button>
    <?php endif; ?>
  </div>
</div>
<div class="admin-card">
  <div class="table-container">
    <table class="admin-table comment-manage">
      <thead>
        <tr>
          <th><input type="checkbox" id="select-all-comments"></th>
          <th>ID</th>
          <th>内容</th>
          <th>用户</th>
          <th>时间</th>
          <th>审核</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <?php
        if (isset($comments) && !empty($comments)) {
          foreach ($comments as $comment) {
            $plain_content = strip_tags($comment['content']);
            $has_images = preg_match('/<img/i', $comment['content']);
            $is_only_images = $has_images && trim($plain_content) === '';
            $content_display = $is_only_images ? '本条为纯图片评论 无内容' : (mb_strlen($plain_content) > 50 ? mb_substr($plain_content, 0, 50) . '...' : $plain_content);
            $content_tip_text = $is_only_images ? '本条为纯图片评论 无内容' : $plain_content;

            $status_checked = $comment['status'] ? 'checked' : '';
            $opacity = $comment['status'] == 0 ? ' opacity: 0.6;' : '';
            $created_at = $comment['created_at'] ? date('Y-m-d', strtotime($comment['created_at'])) : '-';
            $content_tip = htmlspecialchars($content_tip_text, ENT_QUOTES, 'UTF-8');

            echo "<tr>";
            echo "<td><input type='checkbox' class='comment-checkbox' value='{$comment['id']}'></td>";
            echo "<td>{$comment['id']}</td>";
            echo "<td class='comment-content' style='{$opacity}'><span class='comment-content-text' data-qk-tip='{$content_tip}'>" . escape($content_display) . "</span></td>";
            echo "<td>" . escape($comment['username'] ?: '-') . "</td>";
            echo "<td>{$created_at}</td>";
            echo "<td class='text-center'>";
            echo "  <form method='post' class='inline-form'>";
            echo "    <input type='hidden' name='comment_id' value='{$comment['id']}'>";
            echo "    <input type='hidden' name='status' value='" . ($comment['status'] ? '1' : '0') . "'>";
            echo "    <input type='hidden' name='update_comment_status' value='1'>";
            echo "    <label class='theme-switch'>";
            echo "      <input type='checkbox' class='form-checkbox' {$status_checked} onchange='toggleCommentStatus(this)'>";
            echo "      <span class='slider round'></span>";
            echo "    </label>";
            echo "  </form>";
            echo "</td>";
            echo "<td class='action-buttons-right'>";
            echo "  <a href='/post_id{$comment['article_id']}.php' target='_blank' class='btn btn-sm btn-secondary'>预览</a>";
            echo "  <button type='button' class='btn btn-sm btn-primary' data-comment-id='{$comment['id']}' data-comment-content='" . htmlspecialchars($comment['content'], ENT_QUOTES) . "' data-comment-status='{$comment['status']}' onclick=\"openEditCommentModal(this.dataset.commentId, this.dataset.commentContent, this.dataset.commentStatus)\">编辑</button>";
            echo "  <form method='post' class='inline-form' style='display:inline;'>";
            echo "    <input type='hidden' name='delete_comment' value='{$comment['id']}'>";
            echo "    <button type='button' onclick='confirmDeleteComment({$comment['id']})' class='btn btn-sm btn-danger'>删除</button>";
            echo "  </form>";
            echo "</td>";
            echo "</tr>";
          }
        } else {
          echo "<tr><td colspan='7' style='text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;'>当前列表暂无数据</td></tr>";
        }
        ?>
      </tbody>
    </table>






    <?php if ($has_comment_helper_plugin): ?>
      <div id="commentHelperModal" class="modal">
        <div class="modal-backdrop"></div>
        <div class="modal-content" style="width: 620px; max-width: 620px; height: 560px; max-height: 560px; overflow: hidden;">
          <div class="modal-header">
            <h3 class="modal-title">评论助手</h3>
            <button type="button" class="modal-close" onclick="closeCommentHelperModal()">×</button>
          </div>
          <div class="modal-body" style="padding: 0;">
            <iframe id="comment-helper-iframe" style="width:550px;height:500px;border:0;display:block;margin:0 auto;"></iframe>
          </div>
        </div>
      </div>
    <?php endif; ?>

    <script>
      window.addEventListener('message', function(event) {
        if (event.origin !== window.location.origin) return;
        const data = event.data || {};
        if (data.type === 'toast' && data.func === 'showToast') {
          if (typeof window.showToast === 'function') {
            window.showToast(data.message, (data.options && data.options.type) ? data.options.type : 'info');
          }
          return;
        }
        if (data.type === 'toast' && data.func === 'confirmDialog') {
          const result = confirm(data.message || '');
          window.postMessage({
            type: 'confirm_result',
            id: data.id,
            result
          }, window.location.origin);
        }
      });

      <?php if ($has_comment_helper_plugin): ?>
        window.openCommentHelperModal = function() {
          const modal = document.getElementById('commentHelperModal');
          const iframe = document.getElementById('comment-helper-iframe');
          if (!modal || !iframe) return;
          if (typeof window.addModalStyles === 'function') window.addModalStyles();
          modal.style.display = 'flex';
          setTimeout(() => modal.classList.add('modal-visible'), 10);
          iframe.srcdoc = '<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;padding:0;background:#fff;font-family:Microsoft YaHei,SimSun,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}#app{width:100%;height:100%;}::-webkit-scrollbar{width:10px;height:10px;}::-webkit-scrollbar-track{background:#e2e8f0;border-radius:14px;}::-webkit-scrollbar-thumb{background:#94a3b8;border-radius:14px;}::-webkit-scrollbar-thumb:hover{background:#64748b;}</style></head><body><div id="app"></div><script>(function(){var app=document.getElementById(\"app\");app.innerHTML=\"<div style=\\\"text-align:center;padding:50px 0\\\"><div style=\\\"display:inline-block;width:40px;height:40px;border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;animation:spin 1s linear infinite\\\"></div><p style=\\\"margin-top:20px;color:#666\\\">加载中...</p><style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style></div>\";fetch(\"/admin/Plugin.php\",{method:\"POST\",credentials:\"include\",headers:{\"Content-Type\":\"application/x-www-form-urlencoded\"},body:\"action=load_plugin_by_id&plugin_id=39\"}).then(function(r){return r.json()}).then(function(data){if(!data||!data.success){app.innerHTML=\"<div style=\\\"padding:24px;text-align:center;color:#666\\\">加载失败</div>\";return}app.innerHTML=data.html;Array.prototype.slice.call(app.querySelectorAll(\"script\")).forEach(function(s){var ns=document.createElement(\"script\");ns.textContent=s.textContent;document.head.appendChild(ns);s.parentNode&&s.parentNode.removeChild(s)});if(typeof window.onload===\"function\") window.onload()}).catch(function(){app.innerHTML=\"<div style=\\\"padding:24px;text-align:center;color:#666\\\">加载失败</div>\"})})();<\/script></body></html>';
        };

        window.closeCommentHelperModal = function() {
          const modal = document.getElementById('commentHelperModal');
          if (!modal) return;
          modal.classList.remove('modal-visible');
          setTimeout(() => {
            modal.style.display = 'none';
            const iframe = document.getElementById('comment-helper-iframe');
            if (iframe) iframe.srcdoc = '';
          }, 300);
        };

        document.addEventListener('DOMContentLoaded', function() {
          const btn = document.getElementById('open-comment-helper-btn');
          if (btn) btn.addEventListener('click', e => {
            e.preventDefault();
            e.stopPropagation();
            window.openCommentHelperModal();
          });
          const modal = document.getElementById('commentHelperModal');
          if (modal) modal.addEventListener('click', e => {
            if (e.target === modal || e.target.classList.contains('modal-backdrop')) window.closeCommentHelperModal();
          });
          document.addEventListener('keydown', e => {
            if (e.key === 'Escape') window.closeCommentHelperModal();
          });
        });
      <?php endif; ?>

      window.showToast =
        function(message, type = 'info', duration = 3000) {
          const existingToast = document.getElementById('toast-message');
          if (existingToast) existingToast.remove();
          const toast = document.createElement('div');
          toast.id = 'toast-message';
          toast.textContent = message;
          toast.style.position = 'fixed';
          toast.style.top = '20px';
          toast.style.right = '20px';
          toast.style.padding = '12px 20px';
          toast.style.borderRadius = '4px';
          toast.style.color = 'white';
          toast.style.fontSize = '14px';
          toast.style.zIndex = '9999';
          toast.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
          toast.style.transition = 'opacity 0.3s ease';
          toast.style.opacity = '0';
          if (type === 'error') toast.style.backgroundColor = '#dc3545';
          else if (type === 'success') toast.style.backgroundColor = '#28a745';
          else if (type === 'warning') {
            toast.style.backgroundColor = '#ffc107';
            toast.style.color = 'black';
          } else toast.style.backgroundColor = '#17a2b8';
          document.body.appendChild(toast);
          setTimeout(() => toast.style.opacity = '1', 10);
          setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
              if (document.body.contains(toast)) document.body.removeChild(toast);
            }, 300);
          }, duration);
        };

      window.updateBatchCommentIds = function() {
        const checkedBoxes = document.querySelectorAll('.comment-checkbox:checked');
        const commentIds = Array.from(checkedBoxes).map(box => box.value).join(',');
        const batchCommentIdsInput = document.getElementById('comment-batch-comment-ids');
        if (batchCommentIdsInput) batchCommentIdsInput.value = commentIds;
      };

      window.toggleSelectAllComments = function(checkbox) {
        const isChecked = checkbox.checked;
        const commentCheckboxes = document.querySelectorAll('.comment-checkbox');
        commentCheckboxes.forEach(commentCheckbox => commentCheckbox.checked = isChecked);
        if (typeof window.updateBatchCommentIds === 'function') window.updateBatchCommentIds();
      };

      window.toggleCommentStatus = function(checkbox) {
        const form = checkbox.closest('form');
        if (!form) return;
        const commentIdInput = form.querySelector('input[name="comment_id"]');
        const statusInput = form.querySelector('input[name="status"]');
        if (!commentIdInput || !statusInput) return;
        const newStatus = checkbox.checked ? '1' : '0';
        statusInput.value = newStatus;
        const xhr = new XMLHttpRequest();
        const formData = new FormData(form);
        xhr.open('POST', '?tab=comments', true);
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              window.handleCommentAjaxResponse(xhr.responseText, '状态更新成功！');
            } else {
              checkbox.checked = !checkbox.checked;
              statusInput.value = checkbox.checked ? '1' : '0';
              showToast('切换状态失败，请重试！', 'error');
            }
          }
        };
        xhr.onerror = function() {
          checkbox.checked = !checkbox.checked;
          statusInput.value = checkbox.checked ? '1' : '0';
          showToast('网络错误，请检查连接后重试！', 'error');
        };
        xhr.send(formData);
      };

      window.showBlackOverlayMessage = function(message) {
        showToast(message, 'info', 2000);
      }

      window.handleCommentAjaxResponse = function(rawText, successMessage, onSuccess) {
        let response = null;
        const text = (rawText || '').trim();

        try {
          response = JSON.parse(text);
        } catch (e) {}

        if (response && response.success === false) {
          showToast(response.message || response.error || '演示账号无权限操作', 'error');
          return;
        }

        if (response && response.success === true) {
          showToast(response.message || successMessage, 'success');
          if (typeof onSuccess === 'function') onSuccess();
          return;
        }

        if (text === 'success') {
          showToast(successMessage, 'success');
          if (typeof onSuccess === 'function') onSuccess();
          return;
        }

        showToast(text || '操作失败，请重试！', 'error');
      }

      // 处理批量操作 - 直接获取元素绑定事件，避免事件委托冲突
      document.addEventListener('DOMContentLoaded', function() {
        const batchSelect = document.getElementById('comment-batch-operation');
        if (batchSelect) {
          // 直接绑定change事件，不使用事件委托
          batchSelect.onchange = function() {
            const operation = this.value;
            if (!operation) return;

            // 获取选中的评论ID
            const checkedBoxes = document.querySelectorAll('.comment-checkbox:checked');
            const commentIds = Array.from(checkedBoxes).map(box => box.value);

            if (commentIds.length === 0) {
              showToast('请先选择要操作的评论！', 'warning');
              this.value = ''; // 重置选择
              return;
            }

            // 只有删除操作需要确认
            if (operation === 'delete') {
              // 使用自定义的confirmDialog函数替代原生confirm，避免闪退
              if (window.confirmDialog) {
                window.confirmDialog('确定要执行批量删除操作吗？',
                  // 确认回调
                  () => {
                    performBatchOperation(this, operation, commentIds);
                  },
                  // 取消回调
                  () => {
                    this.value = ''; // 重置选择
                  }
                );
              } else {
                // 如果自定义confirmDialog不可用，降级使用原生confirm
                if (confirm('确定要执行批量删除操作吗？')) {
                  performBatchOperation(this, operation, commentIds);
                } else {
                  this.value = ''; // 重置选择
                }
              }
            } else {
              performBatchOperation(this, operation, commentIds);
            }
          };
        }
      });

      // 执行批量操作的辅助函数
      function performBatchOperation(selectElement, operation, commentIds) {
        // 发起AJAX请求
        const xhr = new XMLHttpRequest();
        const formData = new FormData();
        formData.append('perform_batch_action', '1');
        formData.append('batch_action', operation);
        formData.append('comment_ids', commentIds.join(','));

        // 传递当前分页和筛选状态
        if (typeof HeaderPagination !== 'undefined') {
          formData.append('page', HeaderPagination.state.page);
          formData.append('posts_per_page', HeaderPagination.state.pageSize);
        }

        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('status')) formData.append('status', urlParams.get('status'));
        if (urlParams.has('search')) formData.append('search', urlParams.get('search'));

        xhr.open('POST', '?tab=comments', true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              // 解析响应
              try {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                  showToast(response.message, 'success');
                  // 重新加载评论列表（不刷新页面）
                  if (typeof HeaderPagination !== 'undefined') {
                    HeaderPagination.load();
                  } else {
                    window.location.reload();
                  }
                } else {
                  showToast(response.message, 'error');
                }
              } catch (e) {
                window.location.reload();
              }
            } else {
              showToast('批量操作失败，请重试！', 'error');
            }
            // 重置选择器
            selectElement.value = '';
          }
        };

        xhr.onerror = function() {
          showToast('网络错误，请检查连接后重试！', 'error');
          selectElement.value = '';
        };

        // 发送AJAX请求
        xhr.send(formData);
      }

      // 批量删除评论的脚本函数
      window.confirmDeleteComment = function(commentId) {
        // 单个删除不需要确认框，直接执行删除操作
        const xhr = new XMLHttpRequest();
        const url = '/admin/admin.php?tab=comments&delete_comment=' + encodeURIComponent(commentId) + '&ajax=1';
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              window.handleCommentAjaxResponse(xhr.responseText, '评论已成功删除！', function() {
                if (typeof HeaderPagination !== 'undefined') {
                  HeaderPagination.load();
                } else {
                  window.location.reload();
                }
              });
            } else showToast('删除评论失败，请重试！', 'error');
          }
        };
        xhr.onerror = function() {
          showToast('网络错误，请检查连接后重试！', 'error');
        };
        xhr.send();
      }



      // 使用事件委托处理全选复选框变化
      document.addEventListener('change', function(event) {
        if (event.target.id === 'select-all-comments') {
          // 全选/取消全选所有评论复选框
          const isChecked = event.target.checked;
          const commentCheckboxes = document.querySelectorAll('.comment-checkbox');
          commentCheckboxes.forEach(commentCheckbox => commentCheckbox.checked = isChecked);
          window.updateBatchCommentIds();
        } else if (event.target.classList.contains('comment-checkbox')) {
          // 单个评论复选框变化，更新全选复选框状态
          const allCheckboxes = document.querySelectorAll('.comment-checkbox');
          const checkedCheckboxes = document.querySelectorAll('.comment-checkbox:checked');
          const selectAllCheckbox = document.getElementById('select-all-comments');
          if (selectAllCheckbox) {
            selectAllCheckbox.checked = allCheckboxes.length > 0 && allCheckboxes.length === checkedCheckboxes.length;
          }
          window.updateBatchCommentIds();
        }
      });

      // 初始化评论管理页面
      document.addEventListener('DOMContentLoaded', function() {
        // 初始化分页组件
        if (typeof HeaderPagination !== 'undefined' && typeof HeaderPagination.init === 'function') {
          // 设置初始状态
          HeaderPagination.state.page = <?php echo $current_page; ?>;
          HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
          HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

          // 设置缓存，标记第一页已加载，防止 init() 触发重复请求
          HeaderPagination.cache.page = <?php echo $current_page; ?>;
          HeaderPagination.cache.pageSize = <?php echo $posts_per_page; ?>;
          HeaderPagination.cache.totalPages = <?php echo $total_pages ?? 1; ?>;

          HeaderPagination.init();
          HeaderPagination.updateUI();
        }
      });
    </script>

    <script>
      // 支持分页功能
      function isPaginationSupported() {
        return true;
      }
    </script>

    <style>
      .admin-table.comment-manage {
        width: 100% !important;
        min-width: 1030px !important;
        table-layout: fixed !important;
      }

      .admin-table.comment-manage th,
      .admin-table.comment-manage td {
        padding: 0 20px !important;
        text-align: left !important;
        border: none !important;
        border-bottom: 1px solid #e5e7eb !important;
        height: 75px !important;
        line-height: 75px !important;
        box-sizing: border-box !important;
        vertical-align: middle !important;
        margin: 0 !important;
        outline: none !important;
      }

      .admin-table.comment-manage th:first-child,
      .admin-table.comment-manage td:first-child {
        width: 70px !important;
        min-width: 70px !important;
        max-width: 70px !important;

      }

      .admin-table.comment-manage th:nth-child(2),
      .admin-table.comment-manage td:nth-child(2) {
        width: 80px !important;
        min-width: 80px !important;
        max-width: 80px !important;
      }

      .admin-table.comment-manage th:nth-child(3),
      .admin-table.comment-manage td:nth-child(3) {
        width: 300px !important;
        min-width: 300px !important;
        max-width: 300px !important;
      }

      .admin-table.comment-manage th:nth-child(4),
      .admin-table.comment-manage td:nth-child(4) {
        width: 120px !important;
        min-width: 120px !important;
        max-width: 120px !important;
      }

      .admin-table.comment-manage th:nth-child(5),
      .admin-table.comment-manage td:nth-child(5) {
        width: 160px !important;
        min-width: 160px !important;
        max-width: 160px !important;
      }

      .admin-table.comment-manage th:nth-child(6),
      .admin-table.comment-manage td:nth-child(6) {
        width: 100px !important;
        min-width: 100px !important;
        max-width: 100px !important;

      }

      .admin-table.comment-manage th:nth-child(7),
      .admin-table.comment-manage td:nth-child(7) {
        width: 200px !important;
        min-width: 200px !important;
        max-width: 200px !important;
        text-align: right !important;
      }

      .admin-table.comment-manage thead {
        height: 75px !important;
        box-sizing: border-box !important;
      }

      .admin-table.comment-manage thead tr {
        height: 75px !important;
        line-height: 75px !important;
        box-sizing: border-box !important;
        display: table-row !important;
      }

      .admin-table.comment-manage tr {
        height: 75px !important;
        line-height: 75px !important;
        box-sizing: border-box !important;
        margin: 0 !important;
        padding: 0 !important;
      }

      .admin-table.comment-manage .comment-content {
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        font-family: inherit !important;
        font-size: inherit !important;
        font-weight: inherit !important;
      }

      .admin-table.comment-manage td input[type="checkbox"],
      .admin-table.comment-manage td .switch {
        vertical-align: middle !important;
        margin: 0 5px 0 0 !important;
        display: inline-block !important;
      }

      .admin-table.comment-manage .flex-right {
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        width: 100% !important;
      }
    </style>
