<?php
include("../include/conn.php");

$keyword = isset($_GET['wd']) ? trim($_GET['wd']) : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$displaypg = 20;

$keyword_safe = '';
$total = 0;
$lastpg = 1;
$rows = array();

if (!empty($keyword)) {
    $keyword_safe = safe_real_escape_string($keyword);
    $where = "`title` LIKE '%{$keyword_safe}%'";

    $count_sql = "SELECT COUNT(*) as cnt FROM `bencao` WHERE {$where}";
    $count_result = safe_query($count_sql);
    $count_row = safe_fetch_array($count_result);
    $total = isset($count_row['cnt']) ? intval($count_row['cnt']) : 0;

    $lastpg = max(1, ceil($total / $displaypg));
    if ($page > $lastpg) $page = $lastpg;
    $firstcount = ($page - 1) * $displaypg;

    $sql = "SELECT * FROM `bencao` WHERE {$where} ORDER BY `regtime` DESC LIMIT {$firstcount}, {$displaypg}";
    $query = safe_query($sql);
    while ($r = safe_fetch_array($query)) {
        $rows[] = $r;
    }
}

$kw_html = htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8');
$kw_encoded = urlencode($keyword);
$page_title_seo = !empty($keyword) ? $kw_html . ' - 本草搜索' : '本草搜索';
$desc_seo = !empty($keyword)
    ? '为您找到' . $total . '条关于"' . $kw_html . '"的本草资料，包含中药材功效、用法等信息。'
    : '猎取网本草搜索，按药名快速查找中草药资料与功效。';
$canonical_seo = 'https://bencao.liequ.net/search.php' . (!empty($keyword) ? '?wd=' . $kw_encoded : '');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title_seo; ?> - 中草药大全 - 猎取网</title>
    <meta name="description" content="<?php echo $desc_seo; ?>">
    <meta name="keywords" content="<?php echo !empty($keyword) ? $kw_html . ',' : ''; ?>本草搜索,本草纲目,中草药,中药材,猎取网">
    <link rel="canonical" href="<?php echo $canonical_seo; ?>">
    <meta property="og:title" content="<?php echo $page_title_seo; ?> - 猎取网">
    <meta property="og:description" content="<?php echo $desc_seo; ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo $canonical_seo; ?>">
    <meta property="og:site_name" content="猎取网">
    <meta property="og:locale" content="zh_CN">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="<?php echo $page_title_seo; ?> - 猎取网">
    <meta name="twitter:description" content="<?php echo $desc_seo; ?>">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="/css/liequnet.css" rel="stylesheet" type="text/css">
    <style>
    /* ===== 页面标题区 ===== */
    .page-header-bar {
        text-align: center;
        padding: 40px 20px 20px;
    }
    .page-header-bar .page-icon {
        width: 72px; height: 72px; font-size: 32px;
        background: linear-gradient(135deg, var(--gold-primary), var(--gold-light));
        border-radius: 50%;
        display: inline-flex; align-items: center; justify-content: center;
        color: var(--bg-dark); margin-bottom: 12px;
        box-shadow: var(--shadow-xl);
    }
    .page-header-bar h1 {
        font-size: 32px; font-weight: 700;
        background: linear-gradient(135deg, var(--gold-primary), var(--gold-light));
        -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
        margin-bottom: 6px;
    }
    .page-header-bar .page-sub {
        font-size: 14px; color: var(--text-tertiary);
    }
    .bencao-result-count { color:#888; font-size:14px; margin-bottom:16px; }
    .bencao-result-count strong { color:#d4a853; }
    .bencao-highlight { color:#e74c3c; font-weight:700; }
    </style>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "WebApplication",
      "name": "本草搜索 - 猎取网",
      "url": "https://bencao.liequ.net/search.php",
      "description": "猎取网本草搜索，按药名快速查找中草药资料与功效。",
      "applicationCategory": "SearchApplication",
      "operatingSystem": "Web",
      "publisher": {
        "@type": "Organization",
        "name": "猎取网",
        "url": "https://www.liequ.net/"
      }
    }
    </script>
    <script>
(function(){
    var u=navigator.userAgent.toLowerCase();
    if(/android|iphone|ipad|ipod|windows phone|blackberry|opera mini|iemobile/i.test(u))
        location.href='/m/bencao/search.php<?php echo !empty($keyword) ? "?keyword=" . $kw_encoded : ""; ?>';
    if(self!==top) top.location=self.location;
})()
    </script>
</head>
<body>

<header class="top-bar">
    <div class="container">
        <div class="top-bar-content">
            <div class="user-info" id="ad_adyour">
                <span class="loading"><span class="loading-spinner"></span>会员数据加载中...</span>
            </div>
            <div class="current-date" id="currentDate" onclick="window.open('https://www.liequ.net/wannianli/','_blank')" title="点击查看万年历"></div>
        </div>
    </div>
</header>

<!-- ===== 页面标题 ===== -->
<div class="page-header-bar">
    <div class="page-icon"><i class="fas fa-book-medical"></i></div>
    <h1>本草纲目</h1>
    <div class="page-sub">中草药资料大全，传承中医智慧</div>
</div>

<div class="article-wrapper">
    <div class="pleft">
        <div class="place">
            <strong>当前位置:</strong> <a href="https://www.liequ.net/">主页</a> &gt; <a href="https://bencao.liequ.net/">本草纲目</a> &gt; 本草搜索
        </div>

        <div style="margin-bottom:16px;display:flex;gap:8px;">
            <form action="/bencao/search.php" method="get" style="display:flex;gap:8px;flex:1;" onsubmit="var q=this.querySelector('input[name=wd]');if(!q.value.trim()){q.focus();return false;}">
                <input type="text" name="wd" placeholder="搜索本草，如：人参、黄芪、当归..." value="<?php echo $kw_html; ?>" style="flex:1;padding:10px 14px;border:1.5px solid var(--gold-border-20,#e0d5b8);border-radius:8px;font-size:14px;color:var(--text-primary,#333);background:var(--bg-input,#fff);outline:none;transition:border-color .3s;" onfocus="this.style.borderColor='var(--gold-primary,#d4a853)'" onblur="this.style.borderColor=''">
                <button type="submit" style="padding:10px 20px;background:linear-gradient(135deg,var(--gold-primary,#d4a853),var(--gold-light,#f0c674));border:none;border-radius:8px;color:#fff;font-size:14px;font-weight:600;cursor:pointer;white-space:nowrap;"><i class="fas fa-search"></i> 搜索本草</button>
            </form>
        </div>

<?php if (!empty($keyword)): ?>
        <div class="bencao-result-count">
            搜索"<strong><?php echo $kw_html; ?></strong>"共找到 <strong><?php echo $total; ?></strong> 条本草资料
        </div>

    <?php if ($total > 0): ?>
        <div class="article-list">
        <?php
        $now = date("ymd");
        foreach ($rows as $row) {
            $id       = intval($row['id']);
            $title    = htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8');
            $tupian   = isset($row['tupian']) ? $row['tupian'] : '';
            $regtime  = isset($row['regtime']) ? $row['regtime'] : '';
            $username = isset($row['username']) ? $row['username'] : '';
            $newdate  = $regtime ? date('ymd', strtotime($regtime)) : '';
            $mobile3  = preg_replace('/(\d{5})\d{4}(\d{2})/', '$1****$2', $username);

            // 从 content 提取摘要
            $raw_content = isset($row['content']) ? $row['content'] : '';
            preg_match_all('/[\x{4e00}-\x{9fff}]+/u', strip_tags($raw_content), $desc_matches);
            $desc = implode('', $desc_matches[0]);

            // 关键词高亮
            $title_hl = $title;
            $desc_hl = mb_substr($desc, 0, 120, 'UTF-8');
            if (!empty($keyword)) {
                $q = preg_quote($keyword, '/');
                $title_hl = preg_replace("/($q)/i", '<span class="bencao-highlight">\\1</span>', $title);
                $desc_hl = preg_replace("/($q)/i", '<span class="bencao-highlight">\\1</span>', $desc_hl);
            }
        ?>
            <div class="article-card">
                <a class="card-thumb" href="https://bencao.liequ.net/article/<?php echo $id; ?>.html" target="_blank">
                    <?php if ($tupian): ?>
                        <img src="https://www.liequ.net/<?php echo htmlspecialchars($tupian, ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo $title; ?>" loading="lazy">
                    <?php else: ?>
                        <i class="fas fa-leaf no-pic"></i>
                    <?php endif; ?>
                </a>
                <div class="card-body">
                    <a class="card-title" href="https://bencao.liequ.net/article/<?php echo $id; ?>.html" target="_blank">
                        <?php echo $title_hl; ?>
                        <?php if ($newdate && $newdate + 3 > $now): ?><img src="/images/news.gif" style="vertical-align:middle;margin-left:6px" alt="新"><?php endif; ?>
                    </a>
                    <div class="card-meta">
                        <span class="card-cat">本草纲目</span>
                        <span><i class="fas fa-user" style="margin-right:3px;opacity:0.5"></i><?php echo $mobile3; ?></span>
                        <span><i class="fas fa-clock" style="margin-right:3px;opacity:0.5"></i><?php echo htmlspecialchars($regtime, ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <p class="card-desc"><?php echo $desc_hl; ?></p>
                </div>
            </div>
        <?php } ?>
        </div>

        <?php
        // 分页导航
        if ($lastpg > 1) {
            $prepg = $page - 1;
            $nextpg = ($page < $lastpg) ? $page + 1 : 0;
            $base = 'https://bencao.liequ.net/search.php?wd=' . $kw_encoded . '&page=';
        ?>
        <div class="pagination-wrapper">
            <div class="page-info">共 <strong><?php echo $total; ?></strong> 条记录</div>
            <div class="page-btns">
                <a href="<?php echo $base; ?>1" class="page-btn<?php echo $page==1?' disabled':''; ?>">首页</a>
                <?php if ($prepg): ?>
                <a href="<?php echo $base . $prepg; ?>" class="page-btn">上一页</a>
                <?php else: ?>
                <span class="page-btn disabled">上一页</span>
                <?php endif; ?>
                <?php
                $start = max(1, $page - 2);
                $end = min($lastpg, $page + 2);
                if ($start > 1) {
                    echo '<a href="' . $base . '1" class="page-num">1</a>';
                    if ($start > 2) echo '<span class="page-dots">...</span>';
                }
                for ($i = $start; $i <= $end; $i++) {
                    echo '<a href="' . $base . $i . '" class="page-num' . ($i == $page ? ' active' : '') . '">' . $i . '</a>';
                }
                if ($end < $lastpg) {
                    if ($end < $lastpg - 1) echo '<span class="page-dots">...</span>';
                    echo '<a href="' . $base . $lastpg . '" class="page-num">' . $lastpg . '</a>';
                }
                ?>
                <?php if ($nextpg): ?>
                <a href="<?php echo $base . $nextpg; ?>" class="page-btn">下一页</a>
                <?php else: ?>
                <span class="page-btn disabled">下一页</span>
                <?php endif; ?>
                <a href="<?php echo $base . $lastpg; ?>" class="page-btn<?php echo $page==$lastpg?' disabled':''; ?>">尾页</a>
            </div>
        </div>
        <?php } ?>

    <?php else: ?>
        <div style="text-align:center;padding:60px 20px;color:#999;">
            <i class="fas fa-search" style="font-size:48px;margin-bottom:16px;display:block;color:#ddd;"></i>
            <p style="font-size:16px;">未找到与"<strong style="color:#d4a853;"><?php echo $kw_html; ?></strong>"相关的本草资料</p>
            <p style="font-size:14px;margin-top:8px;">换个关键词试试吧，如：人参、枸杞、当归</p>
        </div>
    <?php endif; ?>

<?php else: ?>
        <div style="text-align:center;padding:40px 20px;color:#999;">
            <i class="fas fa-leaf" style="font-size:48px;margin-bottom:16px;display:block;color:#ddd;"></i>
            <p style="font-size:16px;">输入药名开始搜索</p>
            <p style="font-size:14px;margin-top:8px;">例如：人参、黄芪、当归、枸杞</p>
        </div>
<?php endif; ?>
    </div>
</div>

<div class="ad-top-banner">
<script src="https://www.liequ.net/p/ads-960-90.js"></script>
</div>
<footer class="footer"></footer>
<script src="https://www.liequ.net/js/bottom.js"></script>

<div id="ad_your" style="display:none"><script src="https://www.liequ.net/your.php"></script></div>
<script>
(function(){
    var d=new Date();
    var w=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
    document.getElementById("currentDate").innerHTML=d.getFullYear()+"年"+(d.getMonth()+1)+"月"+d.getDate()+"日 "+w[d.getDay()];
    setTimeout(function(){
        var s=document.getElementById("ad_your"),t=document.getElementById("ad_adyour");
        if(t&&s)t.innerHTML=s.innerHTML;
    },500)
})()
</script>
</body>
</html>