<?php
/**
 * 新闻列表页 — 动态从数据库读取新闻
 */
require_once __DIR__ . '/admin/includes/db.php';
require_once __DIR__ . '/admin/includes/functions.php';

$db = getDb();

// ---- 分类筛选 ----
$category = isset($_GET['category']) ? $_GET['category'] : '';
$validCategories = getCategories();
if ($category !== '' && !in_array($category, $validCategories)) {
    $category = '';
}

// ---- 分页 ----
$perPage = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// ---- 构建查询 ----
$where = 'WHERE is_show = 1';
$params = [];

if ($category !== '') {
    $where .= ' AND category = :category';
    $params[':category'] = $category;
}

// 总数
$countSql = "SELECT COUNT(*) FROM news {$where}";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = (int) $stmt->fetchColumn();

$totalPages = ceil($total / $perPage);
if ($page > $totalPages && $totalPages > 0) $page = $totalPages;

$offset = ($page - 1) * $perPage;

// 列表查询（置顶优先，然后按创建时间降序）
$sql = "SELECT id, title, category, cover_image, summary, created_at
        FROM news {$where}
        ORDER BY is_top DESC, created_at DESC
        LIMIT {$perPage} OFFSET {$offset}";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$newsList = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="品牌动态 — 浙江夸父生物医药最新新闻与行业资讯。">
  <title>新闻动态<?php if ($category): ?> - <?php echo e($category); ?><?php endif; ?> | 浙江夸父生物医药</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body class="sub-page">

  <header class="site-header">
    <a class="logo" href="index.html" aria-label="浙江夸父生物医药首页">
      <span class="logo-mark">K</span>
      <span><b data-cms="global-nav-brand">夸父生物医药</b><small data-cms="global-nav-brand-en">KUAFU BIOMEDICINE</small></span>
    </a>
    <nav class="nav">
      <a href="about.html">公司概况</a>
      <a href="platform.html">科研平台</a>
      <a href="technology.html">核心技术</a>
      <a href="pipeline.html">产业布局</a>
      <a href="contact.html">联系我们</a>
      <a href="news.php">新闻动态</a>
    </nav>
    <a class="nav-cta" href="contact.html">合作咨询</a>
    <button class="menu" aria-label="打开菜单" aria-expanded="false"><i></i><i></i></button>
  </header>

  <main>
    <!-- Page Hero -->
    <section class="page-hero">
      <div class="page-hero-inner">
        <div class="page-hero-text">
          <p class="page-hero-kicker">Brand News</p>
          <h1>新闻动态</h1>
          <p class="page-hero-desc">了解夸父生物医药最新科研进展、行业动态与企业资讯，见证再生医学的每一步前行。</p>
        </div>
        <div class="page-hero-deco">
          <div class="deco-news">
            <svg viewBox="0 0 240 100" xmlns="http://www.w3.org/2000/svg">
              <line class="flow-line" x1="10" y1="50" x2="230" y2="50"/>
              <line class="flow-line" x1="60" y1="50" x2="60" y2="25"/>
              <line class="flow-line" x1="120" y1="50" x2="120" y2="20"/>
              <line class="flow-line" x1="180" y1="50" x2="180" y2="28"/>
              <line class="flow-line" x1="60" y1="50" x2="60" y2="75"/>
              <line class="flow-line" x1="120" y1="50" x2="120" y2="80"/>
              <circle class="flow-dot" cx="60" cy="50" r="3.5"/>
              <circle class="flow-dot" cx="120" cy="50" r="3.5"/>
              <circle class="flow-dot" cx="180" cy="50" r="3.5"/>
              <rect class="flow-node" x="30" y="10" width="60" height="14" rx="2"/>
              <rect class="flow-node" x="90" y="5" width="60" height="14" rx="2"/>
              <rect class="flow-node" x="150" y="12" width="60" height="14" rx="2"/>
              <rect class="flow-node" x="30" y="76" width="60" height="14" rx="2"/>
              <rect class="flow-node" x="90" y="80" width="60" height="14" rx="2"/>
              <polyline class="flow-arrow" points="226,46 232,50 226,54"/>
            </svg>
          </div>
        </div>
      </div>
      <div class="page-hero-footer">
        <span class="page-hero-chapter">NEWS</span>
        <span class="page-hero-scroll">SCROLL <i></i></span>
      </div>
    </section>

    <!-- News Section -->
    <section class="news-section">
      <!-- Category Filters (使用 <a> 标签，GET 参数筛选) -->
      <div class="news-filters">
        <?php
          $allActive = ($category === '') ? ' active' : '';
          echo '<a class="news-filter-btn' . $allActive . '" href="news.php">全部</a>';
          foreach ($validCategories as $cat) {
              $active = ($category === $cat) ? ' active' : '';
              echo '<a class="news-filter-btn' . $active . '" href="news.php?category=' . urlencode($cat) . '">' . e($cat) . '</a>';
          }
        ?>
      </div>

      <!-- News List -->
      <div class="news-list">
        <?php if (empty($newsList)): ?>
          <p style="text-align:center;color:var(--muted);padding:60px 0;font-size:15px;">暂无相关新闻</p>
        <?php else: ?>
          <?php
            $isFirst = true;
            foreach ($newsList as $index => $item):
              $dateStr = date('Y.m.d', strtotime($item['created_at']));
              $day = date('d', strtotime($item['created_at']));
              $yearMonth = date('Y.m', strtotime($item['created_at']));
              $summaryText = !empty($item['summary']) ? e($item['summary']) : truncate($item['content'] ?? '', 120);
              $hasCover = !empty($item['cover_image']);
          ?>
            <?php if ($isFirst && $hasCover): ?>
              <!-- Featured item (with image) -->
              <a href="news_detail.php?id=<?php echo $item['id']; ?>" class="news-item--featured">
                <div class="news-thumb">
                  <img src="<?php echo e($item['cover_image']); ?>" alt="<?php echo e($item['title']); ?>">
                  <span class="news-category-tag"><?php echo e($item['category']); ?></span>
                </div>
                <div class="news-body">
                  <div class="news-date"><?php echo $dateStr; ?></div>
                  <h3><?php echo e($item['title']); ?></h3>
                  <p><?php echo $summaryText; ?></p>
                </div>
              </a>
              <?php $isFirst = false; continue; ?>
            <?php endif; ?>
            <?php $isFirst = false; ?>
            <!-- Regular item -->
            <a href="news_detail.php?id=<?php echo $item['id']; ?>" class="news-item">
              <div class="news-date">
                <span class="news-day"><?php echo $day; ?></span>
                <?php echo $yearMonth; ?>
              </div>
              <div class="news-body">
                <h3><?php echo e($item['title']); ?></h3>
                <p><?php echo $summaryText; ?></p>
                <span class="news-category-tag"><?php echo e($item['category']); ?></span>
              </div>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <!-- Pagination -->
      <?php if ($totalPages > 1): ?>
      <div class="news-pagination">
        <?php
          // Build URL helper
          function buildPageUrl($p, $cat) {
              if ($cat !== '') {
                  return 'news.php?category=' . urlencode($cat) . '&page=' . $p;
              }
              return 'news.php?page=' . $p;
          }

          // Previous
          if ($page > 1) {
              echo '<a href="' . buildPageUrl($page - 1, $category) . '">&larr; PREV</a>';
          }

          // Page numbers
          $start = max(1, $page - 2);
          $end = min($totalPages, $page + 2);
          if ($start > 1) {
              echo '<a href="' . buildPageUrl(1, $category) . '">1</a>';
              if ($start > 2) echo '<span class="dots">...</span>';
          }
          for ($i = $start; $i <= $end; $i++) {
              $active = ($i === $page) ? ' active' : '';
              echo '<a class="' . $active . '" href="' . buildPageUrl($i, $category) . '">' . $i . '</a>';
          }
          if ($end < $totalPages) {
              if ($end < $totalPages - 1) echo '<span class="dots">...</span>';
              echo '<a href="' . buildPageUrl($totalPages, $category) . '">' . $totalPages . '</a>';
          }

          // Next
          if ($page < $totalPages) {
              echo '<a href="' . buildPageUrl($page + 1, $category) . '">NEXT &rarr;</a>';
          }
        ?>
      </div>
      <?php endif; ?>
    </section>
  </main>

  <footer>
    <div class="footer-top">
      <div class="footer-col">
        <a class="logo" href="index.html"><span class="logo-mark">K</span><span><b data-cms="global-footer-brand">夸父生物医药</b><small data-cms="global-footer-brand-en">KUAFU BIOMEDICINE</small></span></a>
        <p data-cms="global-footer-slogan">DermAI Genesis · AI × 细胞技术 × 皮肤再生科学平台</p>
      </div>
      <div class="footer-col">
        <h4>科研网络</h4>
        <a href="https://www.westlake.edu.cn/" target="_blank" rel="noopener">西湖大学</a>
        <a href="https://lifesciences.westlake.edu.cn/faculty/duanqing-pei.html" target="_blank" rel="noopener">裴端卿教授</a>
        <a href="platform.html">中科院香港创新研究院</a>
        <a href="platform.html">上海再生医学研究所</a>
        <a href="platform.html">韩国 LS 研究院</a>
      </div>
      <div class="footer-col">
        <h4>快速导航</h4>
        <a href="about.html">公司概况</a>
        <a href="technology.html">核心技术</a>
        <a href="pipeline.html">产业布局</a>
        <a href="news.php">新闻动态</a>
        <a href="contact.html">联系我们</a>
      </div>
    </div>
    <div class="footer-bottom">
      <small>© 2026 浙江夸父生物医药有限公司</small>
      <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener" style="opacity:.5;text-decoration:none;color:inherit">浙ICP备2026034549号</a>
      <small style="opacity:.5">关联公司：后羿医药 · 后羿生物 · LS Research Institute</small>
    </div>
  </footer>

  <script src="script.js"></script>
</body>
</html>
