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

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

// 处理POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  global $conn;

  // 批量保存TAG
  if (isset($_POST['batch_save_tags'])) {
    $ids = isset($_POST['ids']) ? $_POST['ids'] : array();
    $values = isset($_POST['values']) ? $_POST['values'] : array();

    if (!empty($ids) && !empty($values) && count($ids) === count($values)) {
      foreach ($ids as $index => $id) {
        $post_id = intval($id);
        $keywords = $values[$index];
        $sql = "UPDATE posts SET keywords = ? WHERE id = ?";
        execute_non_query($conn, $sql, array($keywords, $post_id));
      }
      echo '<script>showToast(\'TAG已成功批量保存！\', \'success\');</script>';
    }
  }

  // 批量保存搜索词
  if (isset($_POST['batch_save_searches'])) {
    $ids = isset($_POST['ids']) ? $_POST['ids'] : array();
    $values = isset($_POST['values']) ? $_POST['values'] : array();

    if (!empty($ids) && !empty($values) && count($ids) === count($values)) {
      foreach ($ids as $index => $id) {
        $search_id = intval($id);
        $search_term = $values[$index];
        $sql = "UPDATE search SET search_term = ? WHERE id = ?";
        execute_non_query($conn, $sql, array($search_term, $search_id));
      }
      echo '<script>showToast(\'搜索词已成功批量保存！\', \'success\');</script>';
    }
  }

  // 批量删除TAG
  if (isset($_POST['batch_delete_tags'])) {
    $tag_ids = isset($_POST['tag_ids']) ? explode(',', $_POST['tag_ids']) : array();
    if (!empty($tag_ids)) {
      $placeholders = implode(',', array_fill(0, count($tag_ids), '?'));
      $sql = "UPDATE posts SET keywords = '' WHERE id IN ($placeholders)";
      execute_non_query($conn, $sql, $tag_ids);
      echo '<script>showToast(\'TAG已成功批量删除！\', \'success\');</script>';
    }
  }

  // 批量删除搜索词
  if (isset($_POST['batch_delete_searches'])) {
    $search_ids = isset($_POST['search_ids']) ? explode(',', $_POST['search_ids']) : array();
    if (!empty($search_ids)) {
      $placeholders = implode(',', array_fill(0, count($search_ids), '?'));
      $sql = "DELETE FROM search WHERE id IN ($placeholders)";
      execute_non_query($conn, $sql, $search_ids);
      echo '<script>showToast(\'搜索词已成功批量删除！\', \'success\');</script>';
    }
  }

  // 更新单个TAG
  if (isset($_POST['update_tag'])) {
    $post_id = intval($_POST['post_id']);
    $keywords = $_POST['keywords'];
    $sql = "UPDATE posts SET keywords = ? WHERE id = ?";
    execute_non_query($conn, $sql, array($keywords, $post_id));
    echo '<script>showToast(\'TAG已成功更新！\', \'success\');</script>';
  }

  // 更新单个搜索词
  if (isset($_POST['update_search'])) {
    $search_id = intval($_POST['search_id']);
    $search_term = $_POST['search_term'];
    $sql = "UPDATE search SET search_term = ? WHERE id = ?";
    execute_non_query($conn, $sql, array($search_term, $search_id));
    echo '<script>showToast(\'搜索词已成功更新！\', \'success\');</script>';
  }

  // 删除单个TAG
  if (isset($_POST['delete_tag'])) {
    $post_id = intval($_POST['post_id']);
    $sql = "UPDATE posts SET keywords = '' WHERE id = ?";
    execute_non_query($conn, $sql, array($post_id));
    echo '<script>showToast(\'TAG已成功删除！\', \'success\');</script>';
  }

  // 删除单个搜索词
  if (isset($_POST['delete_search'])) {
    $search_id = intval($_POST['search_id']);
    $sql = "DELETE FROM search WHERE id = ?";
    execute_non_query($conn, $sql, array($search_id));
    echo '<script>showToast(\'搜索词已成功删除！\', \'success\');</script>';
  }
}

// 分页/搜索参数由 admin.php 统一解析（pX_sY / search）
if (!isset($current_page)) $current_page = 1;
if (!isset($posts_per_page)) $posts_per_page = 30;
if (!isset($search)) $search = isset($_GET['search']) ? trim($_GET['search']) : '';
$current_page = max(1, intval($current_page));
$posts_per_page = max(1, min(1000, intval($posts_per_page)));
$offset = max(0, ($current_page - 1) * $posts_per_page);

// 获取当前选中的标签页（根据用户要求，使用&tag或&Search参数）
$active_tab = 'tags'; // 默认显示TAG列表
if (isset($_GET['Search'])) {
  $active_tab = 'searches';
} elseif (isset($_GET['tag']) || !isset($_GET['Search'])) {
  $active_tab = 'tags';
}



// 首屏数据：仅用于避免首屏闪烁；后续翻页/搜索完全由 seapage HeaderPagination 驱动
$tags_data = array('data' => array(), 'total' => 0);
$searches_data = array('data' => array(), 'total' => 0);
$total_pages = 1;

if ($active_tab === 'tags') {
  $tags_data = getTagsList($offset, $posts_per_page, $search);
  $total_pages = ($tags_data['total'] ?? 0) > 0 ? ceil($tags_data['total'] / $posts_per_page) : 1;
} else {
  $searches_data = getSearchesList($offset, $posts_per_page, $search);
  $total_pages = ($searches_data['total'] ?? 0) > 0 ? ceil($searches_data['total'] / $posts_per_page) : 1;
}

if ($current_page > $total_pages) $current_page = $total_pages;
?>

<div class="section-header" style="display: flex; justify-content: space-between; align-items: center;">
  <div style="display: flex; align-items: center;">
    <h2>
      <a href="?tab=tagSearch&tag&p1_s<?php echo $posts_per_page; ?>" style="text-decoration: none; color: <?php echo $active_tab === 'tags' ? 'var(--primary-color)' : 'inherit'; ?>">TAG管理</a>
    </h2>
    <h2 style="margin-left: 20px;border-left: 0px solid var(--primary-color);" class="tagsesch1">
      <a href="?tab=tagSearch&Search&p1_s<?php echo $posts_per_page; ?>" style="text-decoration: none; color: <?php echo $active_tab === 'searches' ? 'var(--primary-color)' : 'inherit'; ?>">搜索词管理</a>
    </h2>
  </div>

  <!-- 批量操作按钮 -->
  <form method="post" class="inline-form" id="batch-operation-form" style="display: flex; align-items: center; gap: 10px;">
    <input type="hidden" name="tag_ids" id="batch-tag-ids" value="">
    <input type="hidden" name="search_ids" id="batch-search-ids" value="">
    <input type="hidden" name="page" value="<?php echo $current_page; ?>">
    <input type="hidden" name="search" value="<?php echo !empty($search) ? urlencode($search) : ''; ?>">
    <button type="button" class="btn btn-danger action-button section-header-mobile-btn" id="batch-delete-btn" onclick="batchDelete()" 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;">
        <circle cx="12" cy="12" r="10"></circle>
        <line x1="15" y1="9" x2="9" y2="15"></line>
        <line x1="9" y1="9" x2="15" y2="15"></line>
      </svg>
      <span class="section-header-btn-text"><?php echo $active_tab === 'tags' ? '删除TAG词' : '删除搜索词'; ?></span>
    </button>
    <button type="button" class="btn btn-primary action-button section-header-mobile-btn" onclick="batchSave()" style="margin-right: 0; 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" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;">
        <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path>
        <polyline points="17 21 17 13 7 13 7 21"></polyline>
        <polyline points="7 3 7 8 15 8"></polyline>
      </svg>
      <span class="section-header-btn-text">提交保存</span>
    </button>
  </form>
</div>

<style>
  /* TAG搜索词管理页面独有样式 */
  .admin-table.tag-search-manage {
    width: 100% !important;
    border-collapse: collapse !important;
    position: relative;
    border-spacing: 0 !important;
  }

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

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

  #select-all-tags,
  #select-all-searches,
  .tag-checkbox,
  .search-checkbox {
    width: 18px !important;
    height: 18px !important;
    min-width: 18px !important;
    min-height: 18px !important;
    box-sizing: border-box;
    vertical-align: middle;
    margin: 0;
  }

  .admin-table.tag-search-manage th:nth-child(2),
  .admin-table.tag-search-manage td:nth-child(2) {
    width: 80px;
  }

  .admin-table.tag-search-manage th:nth-child(3),
  .admin-table.tag-search-manage td:nth-child(3) {
    width: 400px !important;
  }

  .admin-table.tag-search-manage th:nth-child(4),
  .admin-table.tag-search-manage td:nth-child(4) {
    width: 100px;
  }

  .admin-table.tag-search-manage th:nth-child(5),
  .admin-table.tag-search-manage td:nth-child(5) {
    width: 130px;
  }

  .admin-table.tag-search-manage th:last-child,
  .admin-table.tag-search-manage td:last-child {
    width: 190px;
  }

  #batch-operation-form .section-header-mobile-btn {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  @media (max-width: 768px) {
    #batch-operation-form .section-header-mobile-btn,
    .section-header #batch-operation-form .btn-danger.section-header-mobile-btn,
    .section-header #batch-operation-form .btn-primary.section-header-mobile-btn {
      width: 38px !important;
      height: 38px !important;
      min-width: 38px !important;
      padding: 0 !important;
      line-height: 38px !important;
    }
    #batch-operation-form .section-header-mobile-btn:first-of-type {
      margin-right: 6px !important;
    }
    #batch-operation-form .section-header-mobile-btn .section-header-btn-text {
      display: none !important;
    }
    #batch-operation-form .section-header-mobile-btn .section-header-btn-icon {
      margin-right: 0 !important;
    }
    .section-header #batch-operation-form .btn-danger.section-header-mobile-btn {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }

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

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

    .admin-table.tag-search-manage th:nth-child(3),
    .admin-table.tag-search-manage td:nth-child(3) {
      width: 150px !important;
      min-width: 150px !important;
      max-width: 200px !important;
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
    }

    .admin-table.tag-search-manage td:nth-child(3) input.form-control {
      width: 100% !important;
      max-width: 100% !important;
      min-width: 100% !important;
    }

    .admin-table.tag-search-manage th:last-child,
    .admin-table.tag-search-manage td:last-child {
      width: 160px !important;
      min-width: 160px !important;
      max-width: 160px !important;
      text-align: right !important;
    }
  }
</style>

<div class="admin-card">
  <div class="table-container">
    <?php if ($active_tab === 'tags'): ?>
      <!-- TAG列表 -->
      <div id="tags-list">
        <div class="admin-table-wrapper">
          <div class="admin-table-scroll">
            <table class="admin-table tag-search-manage">
              <thead>
                <tr>
                  <th style="width: 40px;">
                    <input type="checkbox" id="select-all-tags" class="form-checkbox">
                  </th>
                  <th>ID</th>
                  <th>TAG词</th>
                  <th class="fixed-action-column">操作</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($tags_data['tags'] as $tag): ?>
                  <tr>
                    <td style="width: 40px;">
                      <input type="checkbox" class="tag-checkbox form-checkbox" value="<?php echo $tag['id']; ?>">
                    </td>
                    <td><?php echo $tag['id']; ?></td>
                    <td style="width: 510px;">
                      <input type="text" class="form-control" style="width: 100%;" value="<?php echo escape($tag['keywords']); ?>"
                        data-id="<?php echo $tag['id']; ?>" data-original="<?php echo escape($tag['keywords']); ?>">
                    </td>
                    <td class="fixed-action-column">
                      <button class="btn btn-sm btn-secondary" onclick="previewTag(<?php echo $tag['id']; ?>, '<?php echo escape($tag['keywords']); ?>')">预览</button>
                      <button class="btn btn-sm btn-danger" onclick="deleteTag(<?php echo $tag['id']; ?>, '<?php echo escape($tag['keywords']); ?>')">删除</button>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>


      </div>
    <?php else: ?>
      <!-- 搜索词列表 -->
      <div id="searches-list">
        <div class="admin-table-wrapper">
          <div class="admin-table-scroll">
            <table class="admin-table tag-search-manage">
              <thead>
                <tr>
                  <th style="width: 40px;">
                    <input type="checkbox" id="select-all-searches" class="form-checkbox">
                  </th>
                  <th>ID</th>
                  <th>搜索词</th>
                  <th>搜索者</th>
                  <th>搜索时间</th>
                  <th class="fixed-action-column">操作</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($searches_data['searches'] as $search): ?>
                  <tr>
                    <td style="width: 40px;">
                      <input type="checkbox" class="search-checkbox form-checkbox" value="<?php echo $search['id']; ?>">
                    </td>
                    <td><?php echo $search['id']; ?></td>
                    <td>
                      <input type="text" class="form-control" style="width: 350px;" value="<?php echo escape($search['search_term']); ?>"
                        data-id="<?php echo $search['id']; ?>" data-original="<?php echo escape($search['search_term']); ?>">
                    </td>
                    <td><?php echo escape($search['username']); ?></td>
                    <td><?php echo date('Y-m-d', strtotime($search['search_time'])); ?></td>
                    <td class="fixed-action-column">
                      <button class="btn btn-sm btn-danger" onclick="deleteSearch(<?php echo $search['id']; ?>, '<?php echo escape($search['search_term']); ?>')">删除</button>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>


      </div>
    <?php endif; ?>


  </div>
</div>


<!-- JavaScript -->
<script>
  function handleTagSearchAjaxResponse(xhr, successMessage, onSuccess) {
    if (xhr.readyState !== 4 || xhr.status !== 200) {
      return;
    }

    let response = null;
    try {
      response = JSON.parse(xhr.responseText);
    } catch (e) {}

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

    if (typeof showToast === 'function') {
      showToast(successMessage, 'success', 2000);
    }

    if (typeof onSuccess === 'function') {
      onSuccess();
    }
  }

  // 全选/取消全选TAG
  document.addEventListener('change', function(event) {
    if (event.target.id === 'select-all-tags') {
      // 全选/取消全选所有TAG复选框
      const isChecked = event.target.checked;
      const allCheckboxes = document.querySelectorAll('.tag-checkbox');
      allCheckboxes.forEach(function(checkbox) {
        checkbox.checked = isChecked;
      });
    } else if (event.target.id === 'select-all-searches') {
      // 全选/取消全选所有搜索词复选框
      const isChecked = event.target.checked;
      const allCheckboxes = document.querySelectorAll('.search-checkbox');
      allCheckboxes.forEach(function(checkbox) {
        checkbox.checked = isChecked;
      });
    }
  });

  // 批量保存
  function batchSave() {
    const activeTab = '<?php echo $active_tab; ?>';
    let updates = [];

    if (activeTab === 'tags') {
      // 收集修改过的TAG
      const allInputs = document.querySelectorAll('#tags-list input.form-control');
      allInputs.forEach(input => {
        const id = input.dataset.id;
        const original = input.dataset.original;
        const current = input.value;

        if (current !== original) {
          updates.push({
            id: id,
            value: current
          });
        }
      });
    } else {
      // 收集修改过的搜索词
      const allInputs = document.querySelectorAll('#searches-list input.form-control');
      allInputs.forEach(input => {
        const id = input.dataset.id;
        const original = input.dataset.original;
        const current = input.value;

        if (current !== original) {
          updates.push({
            id: id,
            value: current
          });
        }
      });
    }

    if (updates.length === 0) {
      // 确保showToast函数可用
      if (typeof showToast === 'function') {
        showToast('没有需要保存的修改', 'info');
      }
      return;
    }

    // 直接使用AJAX批量保存，不显示确认框
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '?tab=tagSearch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      handleTagSearchAjaxResponse(xhr, activeTab === 'tags' ? 'TAG已成功批量保存！' : '搜索词已成功批量保存！', function() {
        if (typeof HeaderPagination !== 'undefined') {
          HeaderPagination.load();
        }
      });
    };

    // 构建请求数据
    let data = activeTab === 'tags' ? 'batch_save_tags=1' : 'batch_save_searches=1';
    updates.forEach((item, index) => {
      data += '&ids[' + index + ']=' + item.id + '&values[' + index + ']=' + encodeURIComponent(item.value);
    });

    xhr.send(data);
  }

  // 批量删除
  function batchDelete() {
    const activeTab = '<?php echo $active_tab; ?>';
    let ids = [];
    let confirmMsg = '';
    let actionName = '';
    let idField = '';

    if (activeTab === 'tags') {
      const allCheckboxes = document.querySelectorAll('.tag-checkbox:checked');
      ids = Array.from(allCheckboxes).map(function(checkbox) {
        return checkbox.value;
      });
      confirmMsg = '确定要批量删除选中的 ' + ids.length + ' 个TAG吗？';
      actionName = 'batch_delete_tags';
      idField = 'tag_ids';
    } else {
      const allCheckboxes = document.querySelectorAll('.search-checkbox:checked');
      ids = Array.from(allCheckboxes).map(function(checkbox) {
        return checkbox.value;
      });
      confirmMsg = '确定要批量删除选中的 ' + ids.length + ' 个搜索词吗？';
      actionName = 'batch_delete_searches';
      idField = 'search_ids';
    }

    if (ids.length === 0) {
      // 确保showToast函数可用
      if (typeof showToast === 'function') {
        showToast('请先选择要删除的项目', 'warning');
      }
      return;
    }

    // 显示确认对话框
    const confirmAction = function() {
      // 使用AJAX批量删除
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '?tab=tagSearch', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.onreadystatechange = function() {
        handleTagSearchAjaxResponse(xhr, activeTab === 'tags' ? 'TAG已成功批量删除！' : '搜索词已成功批量删除！', function() {
          if (typeof HeaderPagination !== 'undefined') {
            HeaderPagination.load();
          }
        });
      };

      // 构建请求数据
      let data = actionName + '=1&' + idField + '=' + ids.join(',');
      xhr.send(data);
    };

    if (typeof confirmDialog === 'function') {
      confirmDialog(confirmMsg, confirmAction);
    } else {
      if (confirm(confirmMsg)) {
        confirmAction();
      }
    }
  }

  // 更新TAG
  function updateTag(id, value) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '?tab=tagSearch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      handleTagSearchAjaxResponse(xhr, 'TAG已成功更新！');
    };
    xhr.send('update_tag=1&post_id=' + id + '&keywords=' + encodeURIComponent(value));
  }

  // 更新搜索词
  function updateSearch(id, value) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '?tab=tagSearch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      handleTagSearchAjaxResponse(xhr, '搜索词已成功更新！');
    };
    xhr.send('update_search=1&search_id=' + id + '&search_term=' + encodeURIComponent(value));
  }

  // 删除TAG
  function deleteTag(id, tag) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '?tab=tagSearch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      handleTagSearchAjaxResponse(xhr, 'TAG已成功删除！', function() {
        if (typeof HeaderPagination !== 'undefined') {
          HeaderPagination.load();
        }
      });
    };
    xhr.send('delete_tag=1&post_id=' + id);
  }

  // 删除搜索词
  function deleteSearch(id, searchTerm) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '?tab=tagSearch', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
      handleTagSearchAjaxResponse(xhr, '搜索词已成功删除！', function() {
        if (typeof HeaderPagination !== 'undefined') {
          HeaderPagination.load();
        }
      });
    };
    xhr.send('delete_search=1&search_id=' + id);
  }

  // 预览TAG
  function previewTag(id, tag) {
    // 直接跳转到文章页面
    window.open('/post_id' + id + '.php', '_blank');
  }

  // 更新TAG列表
  function updateTagsList(tags) {
    const tbody = document.querySelector('.admin-table.tag-search-manage tbody');
    if (tbody) {
      tbody.innerHTML = '';
      if (tags.length === 0) {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
        return;
      }
      tags.forEach(tag => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td style="width: 40px;">
            <input type="checkbox" class="tag-checkbox form-checkbox" value="${tag.id}">
          </td>
          <td>${tag.id}</td>
          <td style="width: 510px;">
            <input type="text" class="form-control" style="width: 100%;" value="${escapeHtml(tag.keywords)}" data-id="${tag.id}" data-original="${escapeHtml(tag.keywords)}">
          </td>
          <td class="fixed-action-column">
            <button class="btn btn-sm btn-secondary" onclick="previewTag(${tag.id}, '${escapeHtml(tag.keywords)}')">预览</button>
            <button class="btn btn-sm btn-danger" onclick="deleteTag(${tag.id}, '${escapeHtml(tag.keywords)}')">删除</button>
          </td>
        `;
        tbody.appendChild(row);
      });
    }
  }

  // 更新搜索词列表
  function updateSearchesList(searches) {
    const tbody = document.querySelector('.admin-table.tag-search-manage tbody');
    if (tbody) {
      tbody.innerHTML = '';
      if (searches.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
        return;
      }
      searches.forEach(search => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td style="width: 40px;">
            <input type="checkbox" class="search-checkbox form-checkbox" value="${search.id}">
          </td>
          <td>${search.id}</td>
          <td>
            <input type="text" class="form-control" style="width: 350px;" value="${escapeHtml(search.search_term)}" data-id="${search.id}" data-original="${escapeHtml(search.search_term)}">
          </td>
          <td>${escapeHtml(search.username)}</td>
          <td>${new Date(search.search_time).toISOString().split('T')[0]}</td>
          <td class="fixed-action-column">
            <button class="btn btn-sm btn-danger" onclick="deleteSearch(${search.id}, '${escapeHtml(search.search_term)}')">删除</button>
          </td>
        `;
        tbody.appendChild(row);
      });
    }
  }

  // 顶部分页回调渲染（统一入口）
  function renderTagSearchList(pageData) {
    const activeTab = window.location.href.includes('&Search') ? 'searches' : 'tags';
    const data = pageData && (pageData.data || pageData) || {};

    if (activeTab === 'tags') {
      const tags = data.tags || [];
      updateTagsList(tags);
    } else {
      const searches = data.searches || [];
      updateSearchesList(searches);
    }
  }

  // HTML转义
  function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  document.addEventListener('DOMContentLoaded', function() {
    if (typeof HeaderPagination !== 'undefined') {
      HeaderPagination.state.page = <?php echo $current_page; ?>;
      HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
      HeaderPagination.state.total = <?php echo $active_tab === 'tags' ? ($tags_data['total'] ?? 0) : ($searches_data['total'] ?? 0); ?>;
      HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

      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>
