<?php
$pageTitle = '本地风俗查询';
require_once 'header.php';
require_once 'config.php';

// 获取所有分类
$stmt = $pdo->query("SELECT * FROM custom_categories ORDER BY sort_order");
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 获取所有风俗详情
$stmt = $pdo->query("SELECT cd.*, cc.name as category_name, cc.icon FROM custom_details cd 
                      LEFT JOIN custom_categories cc ON cd.category_id = cc.id 
                      ORDER BY cd.category_id, cd.sort_order");
$details = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 按分类分组
$grouped_details = [];
foreach ($details as $detail) {
    $grouped_details[$detail['category_id']][] = $detail;
}

// 动态查找婚宴酒店分类ID
$stmt = $pdo->query("SELECT id FROM custom_categories WHERE name = '婚宴酒店'");
$hotelRow = $stmt->fetch(PDO::FETCH_ASSOC);
$HOTEL_CATEGORY_ID = $hotelRow ? (int)$hotelRow['id'] : 0;
?>

<main class="site-main">

    <!-- 页面标题 -->
    <section class="page-banner">
        <div class="container">
            <h1>🏮 本地风俗查询</h1>
            <p>深入了解阳泉传统婚俗文化</p>
        </div>
    </section>

    <!-- 风俗分类导航 -->
    <!-- 搜索框 -->
    <div class="custom-search">
        <div class="container">
            <div class="search-wrapper">
                <input type="text" id="customSearch" placeholder="搜索风俗关键词..." onkeyup="searchCustom()">
            </div>
        </div>
    </div>
    <section class="custom-nav">
        <div class="container">
            <div class="category-tabs">
                <?php foreach ($categories as $cat): ?>
                <button class="category-btn" data-category="<?php echo $cat['id']; ?>">
                    <span class="category-icon"><?php echo $cat['icon']; ?></span>
                    <span class="category-name"><?php echo $cat['name']; ?></span>
                </button>
                <?php endforeach; ?>
            </div>
        </div>
    </section>

    <!-- 风俗详情展示 -->
    <section class="custom-details">
        <div class="container">
            <?php foreach ($categories as $cat): ?>
            <div class="category-section" id="category-<?php echo $cat['id']; ?>">
                <h2><?php echo $cat['icon']; ?> <?php echo $cat['name']; ?></h2>
                
                <?php if ($cat['id'] == $HOTEL_CATEGORY_ID): ?>
                    <!-- 酒店列表以表格形式展示 -->
                    <?php if (isset($grouped_details[$cat['id']])): ?>
                    <div class="hotel-table-wrapper">
                        <table class="hotel-table">
                            <thead>
                                <tr>
                                    <th style="width:8%;">区域</th>
                                    <th style="width:18%;">酒店名称</th>
                                    <th style="width:14%;">地址</th>
                                    <th style="width:10%;">最大桌数</th>
                                    <th style="width:16%;">参考餐标</th>
                                    <th style="width:24%;">特色</th>
                                    <th style="width:10%;">电话</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $currentRegion = '';
                                $displayOrder = 0;
                                $totalHotels = count($grouped_details[$cat['id']]);
                                foreach ($grouped_details[$cat['id']] as $detail): 
                                    // 解析 content 字段
                                    $fields = [];
                                    preg_match('/地址：(.+?) \| /', $detail['content'], $m);  $fields['address'] = $m[1] ?? '-';
                                    preg_match('/最大容纳：(.+?) \| /', $detail['content'], $m); $fields['capacity'] = $m[1] ?? '-';
                                    preg_match('/餐标：(.+?) \| /', $detail['content'], $m);   $fields['price'] = $m[1] ?? '-';
                                    preg_match('/特色：(.+?)$/', $detail['content'], $m);        $fields['feature'] = $m[1] ?? '-';
                                    preg_match('/\| 电话：(.+?)$/', $detail['content'], $m);      $fields['phone'] = $m[1] ?? '-';
                                    if (strpos($detail['content'], '电话：') !== false && $fields['phone'] === '-') {
                                        preg_match('/电话：(.+?)$/', $detail['content'], $m);
                                        $fields['phone'] = $m[1] ?? '-';
                                    }
                                    
                                    // 判断区域（根据 sort_order）
                                    $sort = $detail['sort_order'];
                                    if ($sort <= 5) $region = '开发区';
                                    elseif ($sort <= 9) $region = '城区';
                                    elseif ($sort <= 11) $region = '近郊景区';
                                    elseif ($sort <= 15) $region = '平定';
                                    else { $region = ''; continue; } // 跳过推荐行
                                    
                                    if ($currentRegion !== $region) {
                                        $currentRegion = $region;
                                    }
                                ?>
                                <tr class="hotel-row">
                                    <td class="hotel-region"><?php echo $region; ?></td>
                                    <td class="hotel-name"><?php echo htmlspecialchars($detail['title']); ?></td>
                                    <td><?php echo htmlspecialchars($fields['address']); ?></td>
                                    <td class="hotel-capacity"><?php echo htmlspecialchars($fields['capacity']); ?></td>
                                    <td class="hotel-price"><?php echo htmlspecialchars($fields['price']); ?></td>
                                    <td class="hotel-feature"><?php echo htmlspecialchars($fields['feature']); ?></td>
                                    <td class="hotel-phone"><?php echo $fields['phone'] !== '-' ? htmlspecialchars($fields['phone']) : '-'; ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 推荐优先级 -->
                    <?php 
                    // 找推荐行
                    $recDetail = null;
                    foreach ($grouped_details[$cat['id']] as $d) {
                        if ($d['sort_order'] == 16) { $recDetail = $d; break; }
                    }
                    if ($recDetail): 
                    ?>
                    <div class="hotel-recommend">
                        <div class="hotel-rec-title">💡 推荐优先级</div>
                        <div class="hotel-rec-content"><?php echo nl2br(htmlspecialchars($recDetail['content'])); ?></div>
                    </div>
                    <?php endif; ?>
                    <?php endif; ?>
                    
                <?php else: ?>
                    <!-- 其他分类：卡片网格展示 -->
                    <div class="custom-grid">
                        <?php if (isset($grouped_details[$cat['id']])): ?>
                            <?php foreach ($grouped_details[$cat['id']] as $detail): ?>
                            <div class="custom-card" onclick="showDetail(<?php echo $detail['id']; ?>)">
                                <h3><?php echo $detail['title']; ?></h3>
                                <p><?php echo mb_substr($detail['content'], 0, 100); ?>...</p>
                                <div class="custom-card-footer">
                                    <span class="read-more">查看详情 →</span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- 详情弹窗 -->
    <div class="modal-overlay" id="modalOverlay" onclick="closeModal()">
        <div class="modal-content" onclick="event.stopPropagation()">
            <button class="modal-close" onclick="closeModal()">&times;</button>
            <div id="modalBody">
                <h2 id="modalTitle"></h2>
                <div id="modalContent"></div>
                <div id="modalTips" class="modal-tips"></div>
            </div>
        </div>
    </div>

</main>

<script>
// 搜索功能
function searchCustom() {
    const searchTerm = document.getElementById('customSearch').value.toLowerCase();
    const cards = document.querySelectorAll('.custom-card');
    
    cards.forEach(card => {
        const title = card.querySelector('h3').textContent.toLowerCase();
        const content = card.querySelector('p').textContent.toLowerCase();
        
        if (title.includes(searchTerm) || content.includes(searchTerm)) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

// 分类切换
document.addEventListener('DOMContentLoaded', function() {
    const buttons = document.querySelectorAll('.category-btn');
    buttons.forEach(btn => {
        btn.addEventListener('click', function() {
            const categoryId = this.getAttribute('data-category');
            const target = document.getElementById('category-' + categoryId);
            if (target) {
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });
});

// 弹窗详情
function showDetail(id) {
    fetch('custom_detail.php?id=' + id)
        .then(res => res.json())
        .then(data => {
            document.getElementById('modalTitle').innerText = data.title;
            document.getElementById('modalContent').innerText = data.content;
            document.getElementById('modalTips').innerText = data.tips || '';
            document.getElementById('modalOverlay').style.display = 'flex';
        });
}

function closeModal() {
    document.getElementById('modalOverlay').style.display = 'none';
}
</script>

<?php require_once 'footer.php'; ?>