<?php
// ==================== 调试模式 ====================
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
// ================================================

require_once $_SERVER['DOCUMENT_ROOT'] . '/header.php';

// --- 步骤 1: 加载依赖和定义功能函数 ---

$autoload_path = __DIR__ . '/vendor/autoload.php';
if (!file_exists($autoload_path)) {
    die('<main id="page-content" style="padding-top: 124px;"><div class="container"><p style="color: #f07178; background: #2d1a1a; padding: 20px; border-radius: var(--radius);"><strong>配置错误：</strong> 未在当前目录找到 Composer 依赖库。请确保 <code>vendor</code> 文件夹与此 <code>index.php</code> 文件位于同一目录中。</p></div></main>');
}
require_once $autoload_path;

use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\IOFactory;

function extractTextFromElements(array $elements, int &$paragraphLimit): string
{
    $text = '';
    foreach ($elements as $element) {
        if ($paragraphLimit <= 0) break;
        if ($element instanceof TextRun) {
            $paragraphText = extractTextFromElements($element->getElements(), $paragraphLimit);
            if (!empty(trim($paragraphText))) {
                $text .= '<p>' . $paragraphText . '</p>';
                $paragraphLimit--;
            }
        } elseif ($element instanceof Text) {
            $text .= htmlspecialchars($element->getText(), ENT_QUOTES, 'UTF-8');
        }
    }
    return $text;
}

function getDocxSummary(string $filePath, int $paragraphsToExtract = 3): string
{
    if (!is_readable($filePath)) {
        return '<p class="error-text">错误：文件不存在或无法读取。</p>';
    }
    try {
        $phpWord = IOFactory::load($filePath);
        $summary = '';
        $paragraphCount = $paragraphsToExtract;
        foreach ($phpWord->getSections() as $section) {
            if ($paragraphCount <= 0) break;
            $summary .= extractTextFromElements($section->getElements(), $paragraphCount);
        }
        if (empty(trim($summary))) {
            return '<p class="summary-muted">此文档无内容摘要。</p>';
        }
        return $summary;
    } catch (Exception $e) {
        return '<p class="error-text">解析文档时出错：<br><small>' . htmlspecialchars($e->getMessage()) . '</small></p>';
    }
}

/**
 * 将搜索字符串拆分为关键词数组（支持空格、逗号、分号，中英文皆可）
 */
function parseSearchKeywords(string $input): array
{
    $parts = preg_split('/[\s,，;；]+/u', $input);
    $keywords = [];
    if (is_array($parts)) {
        foreach ($parts as $p) {
            $p = trim($p);
            if ($p !== '') {
                $keywords[] = $p;
            }
        }
    }
    return $keywords;
}

/**
 * 判断文档是否匹配所有关键词（文件名 + 摘要 文本中包含）
 * 采用 AND 语义：所有关键词都出现才算匹配
 */
function docMatchesKeywords(string $fileName, string $summaryHtml, array $keywords): bool
{
    if (empty($keywords)) {
        return true;
    }
    $plainText = strip_tags($summaryHtml);
    $haystack = mb_strtolower($fileName . ' ' . $plainText, 'UTF-8');

    foreach ($keywords as $kw) {
        $needle = mb_strtolower($kw, 'UTF-8');
        if ($needle === '') continue;
        if (mb_strpos($haystack, $needle, 0, 'UTF-8') === false) {
            return false;
        }
    }
    return true;
}

/**
 * 将关键词在 HTML 文本中用亮绿色高亮（不改变原有结构）
 */
function highlightKeywords(string $html, array $keywords): string
{
    if (empty($keywords)) {
        return $html;
    }
    $escaped = array_map(function ($kw) {
        return preg_quote($kw, '/');
    }, $keywords);

    $pattern = '/(' . implode('|', $escaped) . ')/iu';
    return preg_replace($pattern, '<span class="doc-highlight">$1</span>', $html);
}

// --- 步骤 2: 准备 Logo 图标池 ---
$logoSvgs = [
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 2 L95 25 L95 75 L50 98 L5 75 L5 25 Z" fill="var(--brand)" opacity="0.1"/><path d="M50 2 L95 25 L95 75 L50 98 L5 75 L5 25 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M25 37 L50 25 L75 37 L75 63 L50 75 L25 63 Z" stroke="var(--text)" stroke-width="3" fill="none" opacity="0.6"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 4 L92 26 V74 L50 96 L8 74 V26 Z" fill="var(--brand)" opacity="0.08"/><path d="M50 4 L92 26 V74 L50 96 L8 74 V26 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><circle cx="50" cy="50" r="22" stroke="var(--text)" stroke-width="3" fill="none" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" fill="var(--brand)" opacity="0.07"/><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M28 30 L72 70 M72 30 L28 70" stroke="var(--text)" stroke-width="3" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 5 L88 25 V75 L50 95 L12 75 V25 Z" fill="var(--brand)" opacity="0.06"/><path d="M50 5 L88 25 V75 L50 95 L12 75 V25 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M50 20 L77 34 V66 L50 80 L23 66 V34 Z" stroke="var(--text)" stroke-width="3" fill="none" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 4 L92 26 V74 L50 96 L8 74 V26 Z" fill="var(--brand)" opacity="0.08"/><path d="M50 4 L92 26 V74 L50 96 L8 74 V26 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M50 28 L70 65 H30 Z" stroke="var(--text)" stroke-width="3" fill="none" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" fill="var(--brand)" opacity="0.06"/><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M30 35 H70 M30 50 H70 M30 65 H70 M40 30 V70 M60 30 V70" stroke="var(--text)" stroke-width="2" opacity="0.6"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 8 L86 28 V72 L50 92 L14 72 V28 Z" fill="var(--brand)" opacity="0.06"/><path d="M50 8 L86 28 V72 L50 92 L14 72 V28 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M50 28 L70 39 V61 L50 72 L30 61 V39 Z M50 28 V72 M30 39 L50 50 L70 39" stroke="var(--text)" stroke-width="2.5" fill="none" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="50" cy="50" r="45" fill="var(--brand)" opacity="0.06"/><circle cx="50" cy="50" r="45" stroke="var(--brand)" stroke-width="3" fill="none"/><ellipse cx="50" cy="50" rx="30" ry="12" stroke="var(--text)" stroke-width="3" fill="none" opacity="0.7"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" fill="var(--brand)" opacity="0.06"/><path d="M50 6 L90 28 V72 L50 94 L10 72 V28 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M50 22 L56 38 L73 38 L59 48 L64 64 L50 54 L36 64 L41 48 L27 38 L44 38 Z" stroke="var(--text)" stroke-width="2.5" fill="none" opacity="0.75"/></svg>',
    '<svg class="logo-crest" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M50 5 L88 25 V75 L50 95 L12 75 V25 Z" fill="var(--brand)" opacity="0.06"/><path d="M50 5 L88 25 V75 L50 95 L12 75 V25 Z" stroke="var(--brand)" stroke-width="3" fill="none"/><path d="M50 20 V80 M25 40 H75 M25 60 H75" stroke="var(--text)" stroke-width="3" opacity="0.7"/></svg>',
];
$capIconSvgsForPool = [
    '<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path></svg>',
    '<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path></svg>',
    '<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path></svg>',
    '<svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"></path></svg>',
];
$docLogoPool = array_merge($capIconSvgsForPool, $logoSvgs);

// --- 搜索关键词 ---
$searchKeyword  = isset($_GET['q']) ? trim((string)$_GET['q']) : '';
$searchKeywords = $searchKeyword !== '' ? parseSearchKeywords($searchKeyword) : [];

?>
<!-- 添加页面特定样式 -->
<style>
  .doc-cap-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
    gap: 24px;
  }
  .doc-cap-card {
    display: flex;
    align-items: flex-start;
    gap: 24px;
    padding: 24px;
    height: 100%;
  }
  .doc-cap-card .icon {
    color: var(--brand);
    width: 40px;
    height: 40px;
    flex-shrink: 0;
  }
  .doc-cap-card h3 {
    margin: 0 0 8px;
    font-size: 20px;
    line-height: 1.4;
    color: var(--text);
  }
  .doc-cap-card .timestamp {
    font-size: 13px;
    color: var(--text-muted);
    margin: 0 0 12px;
  }
  .doc-cap-card .summary {
    font-size: 15px;
    color: var(--text-muted);
    line-height: 1.7;
  }
  .doc-cap-card h3,
  .doc-cap-card .summary {
      word-break: break-word;
  }
  .doc-cap-card .summary p { margin: 0 0 1em; }
  .doc-cap-card .summary p:last-child { margin-bottom: 0; }
  .error-text, .summary-muted { font-size: 14px; }
  .no-docs-message {
      background: var(--surface);
      padding: 30px;
      border-radius: var(--radius);
      text-align: center;
      color: var(--text-muted);
      border: 1px dashed var(--line);
      grid-column: 1 / -1;
  }
  main#page-content > section:first-of-type {
    padding-top: 24px;
  }

  /* 标题布局：第一行 论文 + 搜索；第二行副标题 */
  .section-title-docs {
      display: flex;
      flex-direction: column;
      gap: 8px;
  }
  .section-title-docs .section-title-main-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 24px;
  }
  .section-title-docs .section-subtitle {
      margin: 0;
      font-size: 14px;
      color: var(--text-muted);
  }

  @media (max-width: 768px) {
      .section-title-docs .section-title-main-row {
          flex-direction: column;
          align-items: flex-start;
          gap: 16px;
      }
      .doc-search-wrap {
          width: 100%;
      }

      /* ✅ 新增：小屏下增加标题区与卡片之间的缝隙 */
      .section-title-docs {
          margin-bottom: 24px;  /* 根据你审美可以改成 20 / 32 等 */
      }
  }

  /* 搜索条样式（暗黑、企业风） */
  .doc-search-wrap {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 0;
  }
  .doc-search-form {
      width: 100%;
      max-width: 420px;
  }
  .doc-search-inner {
      display: flex;
      align-items: stretch;
      background: var(--surface-elevated, #111);
      border-radius: 999px;
      padding: 2px;
      border: 1px solid var(--line);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.45);
  }
  .doc-search-input {
      flex: 1;
      border: none;
      background: transparent;
      color: var(--text);
      padding: 10px 14px 10px 18px;
      font-size: 14px;
      outline: none;
  }
  .doc-search-input::placeholder {
      color: var(--text-muted);
  }
  .doc-search-button {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      border: none;
      border-radius: 999px;
      padding: 8px 18px;
      background: #151821;
      color: #fff;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: background 0.18s ease-out, transform 0.1s ease-out, box-shadow 0.18s ease-out;
      white-space: nowrap;
  }
  .doc-search-button:hover {
      background: #1d2230;
      transform: translateY(-1px);
      box-shadow: 0 10px 24px rgba(0, 0, 0, 0.55);
  }
  .doc-search-button:active {
      transform: translateY(0);
      box-shadow: none;
  }
  .doc-search-button svg {
      width: 16px;
      height: 16px;
  }

  /* 关键词高亮：亮绿色 */
  .doc-highlight {
      color: #3CFF8F;
      font-weight: 500;
  }
</style>

<!-- ============== 主体内容 ============== -->
<main id="page-content" style="padding-top: 80px; min-height: calc(100vh - 250px);">
  <section>
    <div class="container">
      
      <!-- 第一行：论文 + 搜索；第二行：Aegis Infrastructure -->
      <div class="section-title reveal section-title-docs">
        <div class="section-title-main-row">
          <h2>Key</h2>

          <div class="doc-search-wrap">
            <form class="doc-search-form" method="get">
              <div class="doc-search-inner">
                <input
                  type="text"
                  name="q"
                  class="doc-search-input"
                  placeholder="搜索文档……"
                  value="<?= htmlspecialchars($searchKeyword, ENT_QUOTES, 'UTF-8') ?>"
                >
                <button type="submit" class="doc-search-button">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="11" cy="11" r="6" stroke-width="2"></circle>
                    <line x1="16" y1="16" x2="21" y2="21" stroke-width="2" stroke-linecap="round"></line>
                  </svg>
                  <span>搜索</span>
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- <p class="section-subtitle">Aegis Infrastructure</p> -->
      </div>
      
      <div class="doc-cap-grid">
        <?php
        $docxFiles = glob(__DIR__ . '/*.docx');

        if (empty($docxFiles)) {
            echo '<div class="no-docs-message"><p>此目录下暂无 DOCX 文档。</p></div>';
        } else {
            usort($docxFiles, function($a, $b) {
                return filemtime($b) <=> filemtime($a);
            });

            $matchedCount = 0;

            foreach ($docxFiles as $file) {
                $fileName     = pathinfo($file, PATHINFO_FILENAME);
                $fileTimestamp = date('Y-m-d H:i:s', filemtime($file));
                $fileSummary  = getDocxSummary($file, 3); // HTML
                $fileUrl      = 'DocxBridge?file=' . rawurlencode(basename($file));

                // 关键词过滤（文件名 + 摘要）
                if (!empty($searchKeywords) && !docMatchesKeywords($fileName, $fileSummary, $searchKeywords)) {
                    continue;
                }

                $matchedCount++;

                // 高亮标题和摘要中的关键词
                $titleHtml = htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8');
                $summaryHtml = $fileSummary;

                if (!empty($searchKeywords)) {
                    $titleHtml   = highlightKeywords($titleHtml, $searchKeywords);
                    $summaryHtml = highlightKeywords($summaryHtml, $searchKeywords);
                }

                // 从图标池中随机选择一个
                $iconSvg = $docLogoPool[array_rand($docLogoPool)];
                if (strpos($iconSvg, 'class="logo-crest"') !== false) {
                    $iconSvg = str_replace('class="logo-crest"', 'class="icon"', $iconSvg);
                }
        ?>
                <a href="<?= $fileUrl ?>" class="solar-card doc-cap-card reveal">
                    <?= $iconSvg ?>
                    <div>
                        <h3><?= $titleHtml ?></h3>
                        <div class="timestamp"><?= $fileTimestamp ?></div>
                        <div class="summary">
                            <?= $summaryHtml ?>
                        </div>
                    </div>
                </a>
        <?php
            }

            if ($searchKeyword !== '' && $matchedCount === 0) {
                echo '<div class="no-docs-message"><p>未找到匹配 “' . htmlspecialchars($searchKeyword, ENT_QUOTES, 'UTF-8') . '” 的 DOCX 文档。</p></div>';
            }
        }
        ?>
      </div>

    </div>
  </section>
</main>
<!-- ============== 内容结束 ============== -->

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/footer.php';
?>
