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

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

// --- DOCX 解析功能 ---
$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 = 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>';
    }
}

// **关键新增**: 动态获取当前目录名
$currentDirName = basename(__DIR__);
?>

<!-- 添加页面特定样式，用于美化卡片布局 -->
<style>
  .doc-card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 24px;
  }
  .doc-card {
    padding: 24px; display: flex; flex-direction: column; height: 100%;
  }
  .doc-card .timestamp {
    display: inline-block; background: var(--bg); border: 1px solid var(--line);
    border-radius: 999px; padding: 6px 16px; font-size: 13px; font-weight: 600;
    color: var(--text-muted); margin-bottom: 16px; align-self: flex-start;
  }
  .doc-card h4 {
    margin: 0 0 12px; font-size: 20px; line-height: 1.4; color: var(--text);
  }
  .doc-card .summary {
    font-size: 15px; color: var(--text-muted); line-height: 1.7; flex-grow: 1;
  }
  .doc-card .summary p { margin: 0 0 1em; }
  .doc-card .summary p:last-child { margin-bottom: 0; }
  .error-text { color: #f07178; font-size: 14px; }
  .summary-muted { color: var(--text-muted); font-style: italic; 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);
  }
  main#page-content > section:first-of-type {
    padding-top: 24px;
  }
</style>

<!-- ============== 子页面主体内容 ============== -->
<main id="page-content" style="padding-top: 80px; min-height: calc(100vh - 250px);">
  <section>
    <div class="container">
      
      <div class="section-title reveal">
        <!-- **关键修改**: 使用动态目录名作为标题 -->
        <h2><?= htmlspecialchars($currentDirName) ?></h2>
        <p>Aegis Infrastructure</p>
      </div>
      
      <div class="doc-card-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);
            });

            foreach ($docxFiles as $file) {
                $fileName = pathinfo($file, PATHINFO_FILENAME);
                $fileTimestamp = date('Y-m-d H:i:s', filemtime($file));
                $fileSummary = getDocxSummary($file, 2);
                $fileUrl = 'DocxBridge?file=' . rawurlencode(basename($file));
        ?>
                <a href="<?= $fileUrl ?>" class="solar-card doc-card reveal">
                    <div class="timestamp"><?= $fileTimestamp ?></div>
                    <h4><?= htmlspecialchars($fileName) ?></h4>
                    <div class="summary">
                        <?= $fileSummary ?>
                    </div>
                </a>
        <?php
            }
        }
        ?>
      </div>

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

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