<?php
// ==================== 调试模式 ====================
// 在解决问题时，取消下面两行的注释，它会强制显示所有PHP错误。
// 在生产环境中，请务必将它们注释掉。
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
// ================================================

// 使用 $_SERVER['DOCUMENT_ROOT'] 确保从网站根目录开始查找，从而正确引入 header.php
require_once $_SERVER['DOCUMENT_ROOT'] . '/header.php';

// 站点根目录（物理路径），后面做递归扫描和 URL 生成时都会用到
$DOC_ROOT = isset($_SERVER['DOCUMENT_ROOT']) && $_SERVER['DOCUMENT_ROOT'] !== ''
    ? rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/')
    : rtrim(str_replace('\\', '/', __DIR__), '/');

// --- DOCX 解析功能 ---
// 使用 __DIR__ 来确保总是在当前文件所在的目录中查找 vendor/autoload.php。
$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;

/**
 * 从 PHPWord 元素中提取纯文本内容。
 * @param array $elements PHPWord 元素数组。
 * @param int $paragraphLimit 限制提取的段落数量。
 * @return string 提取并拼接好的 HTML 摘要。
 */
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;
}

/**
 * 加载 DOCX 文件并提取指定数量段落的摘要。
 * 用于“搜索匹配”，但页面不再显示摘要内容。
 * @param string $filePath 文件路径。
 * @param int $paragraphsToExtract 要提取的段落数量。
 * @return string HTML格式的摘要。
 */
function getDocxSummary(string $filePath, int $paragraphsToExtract = 2): 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);
}

/**
 * 从给定根目录递归扫描所有 .docx 文件（全站扫描）
 * @param string $baseDir 站点根目录（物理路径）
 * @param array $excludeDirs 需要排除的目录名（例如 vendor / node_modules 等）
 * @return array 绝对路径数组
 */
function findAllDocxFiles(string $baseDir, array $excludeDirs = []): array
{
    $files = [];

    $baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR);
    if (!is_dir($baseDir) || !is_readable($baseDir)) {
        return $files;
    }

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(
            $baseDir,
            FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS
        )
    );

    foreach ($iterator as $fileInfo) {
        /** @var SplFileInfo $fileInfo */
        if (!$fileInfo->isFile()) {
            continue;
        }

        $pathName = $fileInfo->getPathname();
        $dirName  = $fileInfo->getPath();
        $ext      = strtolower($fileInfo->getExtension());

        // 按目录名排除（vendor / node_modules / .git / storage / cache 等）
        if (!empty($excludeDirs)) {
            $relative = trim(str_replace($baseDir, '', $dirName), DIRECTORY_SEPARATOR);
            if ($relative !== '') {
                $parts = explode(DIRECTORY_SEPARATOR, $relative);
                $skip = false;
                foreach ($parts as $p) {
                    if ($p !== '' && in_array($p, $excludeDirs, true)) {
                        $skip = true;
                        break;
                    }
                }
                if ($skip) {
                    continue;
                }
            }
        }

        if ($ext === 'docx') {
            $files[] = $pathName;
        }
    }

    return $files;
}

/**
 * 根据物理路径构造相对于站点根的目录路径（用于显示“所在目录”）
 * 例如：/var/www/html/Tech/IaC/doc.docx -> /Tech/IaC
 *       /var/www/html/doc.docx           -> /
 */
function getRelativeDirPath(string $filePath, string $docRoot): string
{
    $docRoot   = rtrim(str_replace('\\', '/', $docRoot), '/');
    $fullDir   = str_replace('\\', '/', dirname($filePath));

    if (strpos($fullDir, $docRoot) === 0) {
        $relative = substr($fullDir, strlen($docRoot));
    } else {
        $relative = '';
    }

    $relative = '/' . ltrim((string)$relative, '/');
    return $relative === '/' ? '/' : $relative;
}

/**
 * 构造 DocxBridge 打开链接：
 *   {docx 所在目录}/DocxBridge?file=文件名.docx
 * 例如：/Tech/IaC/DocxBridge?file=MyDoc.docx
 */
function buildDocxBridgeUrl(string $filePath, string $docRoot): string
{
    $docRoot   = rtrim(str_replace('\\', '/', $docRoot), '/');
    $fullDir   = str_replace('\\', '/', dirname($filePath));

    if (strpos($fullDir, $docRoot) === 0) {
        $relative = substr($fullDir, strlen($docRoot));
    } else {
        $relative = '';
    }

    $relative = '/' . ltrim((string)$relative, '/'); // 至少有一个前导 /
    // 根目录下的文件，链接形如 /DocxBridge?file=xxx.docx
    if ($relative === '/') {
        $baseUrl = '';
    } else {
        $baseUrl = $relative;
    }

    return $baseUrl . '/DocxBridge?file=' . rawurlencode(basename($filePath));
}

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

?>

<!-- 添加页面特定样式，用于美化“列表”布局 -->
<style>
  /* 整体顶部间距略小，显得更紧凑一些 */
  main#page-content > section:first-of-type {
    padding-top: 24px;
  }

  /* 标题布局：第一行 文档中心 + 搜索；第二行副标题 */
  .section-title-docs {
      display: flex;
      flex-direction: column;
      gap: 8px;
      margin-bottom: 18px;
  }
  .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;
      }
  }

  /* 搜索条样式（暗黑、企业风） */
  .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-list-wrapper {
      width: 100%;
      background: transparent;
  }

  .doc-list-header {
      display: grid;
      grid-template-columns: 3fr 2fr 2fr;
      gap: 16px;
      padding: 10px 18px;
      font-size: 13px;
      text-transform: uppercase;
      letter-spacing: 0.08em;
      color: var(--text-muted);
      border-bottom: 1px solid var(--line);
  }

  .doc-list-body {
      border-radius: var(--radius);
      overflow: hidden;
      background: var(--surface);
      border: 1px solid var(--line);
  }

  .doc-list-row {
      display: grid;
      grid-template-columns: 3fr 2fr 2fr;
      gap: 16px;
      padding: 12px 18px;
      align-items: center;
      text-decoration: none;
      color: var(--text);
      border-bottom: 1px solid rgba(255,255,255,0.03);
      transition: background 0.15s ease-out, transform 0.06s ease-out, box-shadow 0.15s ease-out;
  }

  .doc-list-row:last-child {
      border-bottom: none;
  }

  /* 这里不定义辉光细节，让你全局的 .solar-card 样式接管 */
  .doc-list-row:hover {
      background: rgba(255,255,255,0.03);
      transform: translateY(-1px);
      box-shadow: 0 10px 24px rgba(0, 0, 0, 0.35);
  }

  .doc-list-row:active {
      transform: translateY(0);
      box-shadow: none;
  }

  .doc-list-title {
      font-size: 15px;
      font-weight: 500;
      word-break: break-all;
  }

  .doc-list-path {
      font-size: 13px;
      color: var(--text-muted);
      word-break: break-all;
  }

  .doc-list-time {
      font-size: 13px;
      color: var(--text-muted);
      white-space: nowrap;
  }

  @media (max-width: 900px) {
      .doc-list-header {
          display: none;
      }
      .doc-list-body {
          border-radius: var(--radius);
      }
      .doc-list-row {
          grid-template-columns: 1fr;
          gap: 6px;
          padding: 12px 14px;
          align-items: flex-start;
      }
      .doc-list-path,
      .doc-list-time {
          font-size: 12px;
      }
  }

  .error-text { color: #f07178; font-size: 13px; }
  .summary-muted { color: var(--text-muted); font-style: italic; font-size: 13px; }

  .no-docs-message {
      background: var(--surface);
      padding: 30px;
      border-radius: var(--radius);
      text-align: center;
      color: var(--text-muted);
      border: 1px dashed var(--line);
      margin-top: 24px;
  }

  /* 关键词高亮：亮绿色 */
  .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">
      
      <!-- 标题区域：文档中心 + 搜索 + 副标题 -->
      <div class="section-title reveal section-title-docs">
        <div class="section-title-main-row">
          <h2>文档中心</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">
          全站 DOCX 文档索引 · 按更新时间降序排列
          <?php if ($searchKeyword !== ''): ?>
            · 当前筛选：<span class="doc-highlight"><?= htmlspecialchars($searchKeyword, ENT_QUOTES, 'UTF-8') ?></span>
          <?php endif; ?>
        </p>
      </div>
      
      <?php
        // ====== 核心：全站扫描 DOCX 文件 ======
        $docxFiles = findAllDocxFiles($DOC_ROOT, [
            'vendor', 'node_modules', '.git', 'storage', 'cache'
        ]);

        if (empty($docxFiles)) {
            echo '<div class="no-docs-message"><p>全站未找到任何 DOCX 文档。</p></div>';
        } else {
            // 按文件修改时间降序排序
            usort($docxFiles, function($a, $b) {
                return filemtime($b) <=> filemtime($a);
            });

            $matchedItems = [];

            foreach ($docxFiles as $file) {
                $fileName      = pathinfo($file, PATHINFO_FILENAME);
                $fileTimestamp = date('Y-m-d H:i:s', filemtime($file));
                $relativeDir   = getRelativeDirPath($file, $DOC_ROOT); // /Doc /Tech/IaC / 等
                $fileUrl       = buildDocxBridgeUrl($file, $DOC_ROOT);

                // =========== 搜索逻辑 ===========
                if (!empty($searchKeywords)) {
                    // 仅在有搜索关键词时，才解析 docx 正文
                    $fileSummary = getDocxSummary($file, 2); // 用于匹配，但不显示
                    if (!docMatchesKeywords($fileName, $fileSummary, $searchKeywords)) {
                        continue;
                    }
                }

                // =========== 展示内容 ===========
                $titleHtml = htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8');

                if (!empty($searchKeywords)) {
                    $titleHtml            = highlightKeywords($titleHtml, $searchKeywords);
                    $relativeDirDisplay   = highlightKeywords(htmlspecialchars($relativeDir, ENT_QUOTES, 'UTF-8'), $searchKeywords);
                } else {
                    $relativeDirDisplay   = htmlspecialchars($relativeDir, ENT_QUOTES, 'UTF-8');
                }

                $matchedItems[] = [
                    'url'       => $fileUrl,
                    'title'     => $titleHtml,
                    'dir'       => $relativeDirDisplay,
                    'timestamp' => $fileTimestamp,
                ];
            }

            if ($searchKeyword !== '' && empty($matchedItems)) {
                echo '<div class="no-docs-message"><p>未找到匹配 “' . htmlspecialchars($searchKeyword, ENT_QUOTES, 'UTF-8') . '” 的 DOCX 文档。</p></div>';
            } elseif (!empty($matchedItems)) {
      ?>
              <div class="doc-list-wrapper reveal">
                  <div class="doc-list-header">
                      <div>文档标题</div>
                      <div>所在目录</div>
                      <div>更新时间</div>
                  </div>
                  <div class="doc-list-body">
                      <?php foreach ($matchedItems as $item): ?>
                          <!-- 保留辉光特效：solar-card；同时保留 reveal 动画 -->
                          <a href="<?= $item['url'] ?>" class="doc-list-row solar-card reveal">
                              <div class="doc-list-title"><?= $item['title'] ?></div>
                              <div class="doc-list-path"><?= $item['dir'] ?></div>
                              <div class="doc-list-time"><?= htmlspecialchars($item['timestamp'], ENT_QUOTES, 'UTF-8') ?></div>
                          </a>
                      <?php endforeach; ?>
                  </div>
              </div>
      <?php
            } else {
                echo '<div class="no-docs-message"><p>暂无可显示的文档。</p></div>';
            }
        }
      ?>

    </div>
  </section>
</main>
<!-- ============== 子页面主体内容结束 ============== -->

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