<?php
require_once 'config.php';
$pdo = get_db_connection();

// 强行阻断浏览器强缓存
header("Cache-Control: no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

// 1. 获取当前路由识别出来的商户 ID
$my_agent_id = getCurrentAgentId();

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📊 流量大盘自增引擎：只要进页面，总访问量 (PV) 瞬间 +1
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
if ($my_agent_id > 0) {
    $check_cfg = $pdo->prepare("SELECT COUNT(*) FROM system_config WHERE agent_id = ?");
    $check_cfg->execute([$my_agent_id]);
    
    if ($check_cfg->fetchColumn() == 0) {
        // 全新分站初次访问，全自动开辟配置底座并设初值为 1
        $init_cfg = $pdo->prepare("INSERT INTO system_config (agent_id, title, notice, total_views) VALUES (?, '全新独立学院楼群中心', '欢迎新同学，请长按下方群码加入官方组织！', 1)");
        $init_cfg->execute([$my_agent_id]);
    } else {
        // 存在历史记录，total_views 物理自增 +1
        $update_pv = $pdo->prepare("UPDATE system_config SET total_views = total_views + 1 WHERE agent_id = ?");
        $update_pv->execute([$my_agent_id]);
    }
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 🏢 楼栋独立点击流水采集接口：承接前端 1.5 秒倒计时期间发来的计数请求
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
if (isset($_GET['action']) && $_GET['action'] == 'click_building') {
    $b_id = isset($_GET['b_id']) ? intval($_GET['b_id']) : 0;
    if ($b_id > 0) {
        // 死锁当前选定的楼号，让它的被点击次数 click_views 实时自增 +1
        $update_click = $pdo->prepare("UPDATE dorm_building SET click_views = click_views + 1 WHERE id = ?");
        $update_click->execute([$b_id]);
        echo json_encode(['status' => 'success']);
    }
    exit; // 采集流结束，切断后续 HTML 渲染输出
}

// 2. 严格按当前的学校 ID 拉取对应的全局配置、轮播图和大版块
$config = $pdo->prepare("SELECT * FROM system_config WHERE agent_id = ? LIMIT 1");
$config->execute([$my_agent_id]);
$config = $config->fetch() ?: ['title'=>'新一代楼群导航中心', 'notice'=>'', 'total_views' => 0];

$zones = $pdo->prepare("SELECT * FROM dorm_zone WHERE agent_id = ? ORDER BY sort_order ASC");
$zones->execute([$my_agent_id]);
$zones = $zones->fetchAll();

$banners = $pdo->prepare("SELECT * FROM system_banners WHERE agent_id = ? ORDER BY sort_order ASC, id DESC");
$banners->execute([$my_agent_id]);
$banners = $banners->fetchAll();

// 3. 隔离拉取楼宇群码
$buildings = $pdo->prepare("SELECT * FROM dorm_building WHERE agent_id = ? ORDER BY sort_order ASC");
$buildings->execute([$my_agent_id]);
$buildings = $buildings->fetchAll();

$zone_buildings = [];
foreach ($buildings as $b) {
    $z_key = trim((string)$b['zone_id']);
    $zone_buildings[$z_key][] = $b;
}

$cache_buster = time();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($config['title']); ?></title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", Arial, sans-serif; background-color: #f7f9fc; margin: 0; padding: 0; color: #333; }
        .app-container { max-width: 540px; margin: 0 auto; background-color: #fff; min-height: 100vh; box-shadow: 0 0 20px rgba(0,0,0,0.02); display: flex; flex-direction: column; }
        .slider-wrapper { width: 100%; position: relative; overflow: hidden; background: #fafafa; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; }
        .slider-container { display: flex; width: 100%; height: 180px; transition: transform 0.35s ease; }
        .slider-slide { min-width: 100%; width: 100%; height: 100%; cursor: pointer; }
        .slider-slide img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .slider-dots { position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); display: flex; gap: 6px; z-index: 10; }
        .slider-dot { width: 6px; height: 6px; background: rgba(255,255,255,0.4); border-radius: 50%; }
        .slider-dot.active { background: #fff; width: 14px; border-radius: 3px; }
        .fallback-header { background: linear-gradient(135deg, #ff758f 0%, #ff4d6d 100%); padding: 30px 20px; text-align: center; color: white; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; }
        .fallback-title { font-size: 20px; font-weight: 800; margin: 0; }
        .notice-wrapper { padding: 15px 16px 5px 16px; }
        .notice-box { background-color: #fff5f6; border: 1px solid #ffe3e6; padding: 12px 14px; border-radius: 12px; font-size: 13px; color: #ff4d6d; line-height: 1.5; display: flex; }
        .content-body { padding: 15px 16px 30px 16px; flex-grow: 1; }
        .zone-section { margin-bottom: 25px; }
        .zone-title { font-size: 15px; font-weight: 700; color: #1a1a1a; margin-bottom: 12px; display: flex; align-items: center; padding-left: 8px; border-left: 4px solid #ff758f; }
        .building-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 9px; }
        .building-btn { background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 2px; text-align: center; font-size: 13px; font-weight: 600; color: #475569; cursor: pointer; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
        
        .modal-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.6); display: flex; justify-content: center; align-items: center; z-index: 9999; opacity: 0; visibility: hidden; transition: all 0.2s ease; backdrop-filter: blur(4px); }
        .modal-mask.show { opacity: 1; visibility: visible; }
        .modal-card { background-color: #fff; width: 85%; max-width: 330px; border-radius: 20px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.15); }
        .modal-header { background: #fff5f6; padding: 16px; text-align: center; font-weight: 700; color: #ff4d6d; font-size: 16px; border-bottom: 1px solid #ffe3e6; }
        .modal-body { padding: 22px 20px; text-align: center; background: #fff; min-height: 250px; position: relative; }
        .qr-image { width: 100%; max-width: 220px; height: auto; object-fit: contain; aspect-ratio: 1 / 1; border-radius: 10px; border: 1px solid #f1f5f9; display: block; margin: 0 auto; opacity: 0; transition: opacity 0.2s ease; }
        .qr-image.loaded { opacity: 1; }
        
        .global-loader-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255,255,255,0.85); display: flex; flex-direction: column; justify-content: center; align-items: center; z-index: 10000; opacity: 0; visibility: hidden; transition: all 0.2s ease; }
        .global-loader-mask.show { opacity: 1; visibility: visible; }
        .global-spinner { width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid #ff4d6d; border-radius: 50%; animation: spin 0.8s linear infinite; margin-bottom: 15px; }
        .global-loader-text { font-size: 14px; font-weight: 600; color: #ff4d6d; letter-spacing: 1px; }

        .qr-loader { position: absolute; top: 90px; left: 50%; transform: translateX(-50%); font-size: 13px; color: #94a3b8; display: flex; flex-direction: column; align-items: center; gap: 8px; }
        .spinner { width: 24px; height: 24px; border: 3px solid #ffeff2; border-top-color: #ff4d6d; border-radius: 50%; animation: spin 0.8s linear infinite; }
        .scan-tip-badge { display: inline-block; background: #ff4d6d; color: white; font-size: 12px; font-weight: bold; padding: 5px 14px; border-radius: 20px; margin-top: 14px; }
        .scan-tip-badge.loaded { opacity: 1; }
        .modal-notice { font-size: 12px; color: #64748b; line-height: 1.5; margin-top: 8px; background: #f8fafc; padding: 8px 12px; border-radius: 8px; text-align: left; border-left: 3px solid #cbd5e1; }
        .modal-footer { border-top: 1px solid #f1f5f9; display: flex; }
        .modal-close-btn { flex: 1; padding: 14px; text-align: center; font-size: 15px; font-weight: 700; color: #64748b; cursor: pointer; }
        @keyframes spin { to { transform: rotate(360deg); } }
        @media (max-width: 360px) { .building-grid { grid-template-columns: repeat(3, 1fr); } }
    </style>
</head>
<body>

<div class="app-container">

    <?php if(!empty($banners)): ?>
    <div class="slider-wrapper">
        <div class="slider-container" id="sliderContainer">
            <?php foreach($banners as $bn): ?>
                <div class="slider-slide" onclick="handleBannerClick('<?php echo htmlspecialchars($bn['link_url']); ?>')">
                    <img src="<?php echo htmlspecialchars($bn['image_url']) . '?v=' . $cache_buster; ?>">
                </div>
            <?php endforeach; ?>
        </div>
        <div class="slider-dots">
            <?php foreach($banners as $index => $bn): ?><div class="slider-dot <?php echo $index===0?'active':''; ?>"></div><?php endforeach; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="fallback-header"><h1 class="fallback-title"><?php echo htmlspecialchars($config['title']); ?></h1></div>
    <?php endif; ?>

    <?php if(!empty($config['notice'])): ?>
    <div class="notice-wrapper"><div class="notice-box"><div><?php echo nl2br(htmlspecialchars($config['notice'])); ?></div></div></div>
    <?php endif; ?>

    <div class="content-body">
        <?php if(!empty($zones)): foreach($zones as $z): ?>
            <?php $current_z_id = trim((string)$z['id']); ?>
            <div class="zone-section">
                <div class="zone-title"><?php echo htmlspecialchars($z['zone_name']); ?></div>
                <div class="building-grid">
                    <?php if (isset($zone_buildings[$current_z_id]) && !empty($zone_buildings[$current_z_id])): ?>
                        <?php foreach ($zone_buildings[$current_z_id] as $b): ?>
                            <div class="building-btn" onclick="openQrModal('<?php echo htmlspecialchars($b['id']); ?>', '<?php echo htmlspecialchars($b['building_name']); ?>', '<?php echo htmlspecialchars($b['group_code_url']); ?>', '<?php echo htmlspecialchars($b['building_notice']); ?>')">
                                <?php echo htmlspecialchars($b['building_name']); ?>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="font-size:12px;color:#999;padding:6px 5px;grid-column: span 4;">💡 该区域下暂未配置有效楼号按钮</div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; else: echo '<div style="text-align:center;color:#999;padding-top:60px;">暂无公开配置数据。</div>'; endif; ?>
    </div>
</div>

<div class="global-loader-mask" id="globalPageLoader">
    <div class="global-spinner"></div>
    <div class="global-loader-text">安全进群通道动态生成中...</div>
</div>

<div class="modal-mask" id="qrModal" onclick="closeQrModal(event)">
    <div class="modal-card" onclick="event.stopPropagation()">
        <div class="modal-header" id="modalTitle">交流群</div>
        <div class="modal-body">
            <div class="qr-loader" id="qrLoader"><div class="spinner"></div><div>获取最新群码中...</div></div>
            <img src="" id="modalQrImg" class="qr-image">
            <div class="scan-tip-badge" id="scanTip">💡 长按图片 识别二维码进群</div>
            <div class="modal-notice" id="modalNoticeBox"></div>
        </div>
        <div class="modal-footer"><div class="modal-close-btn" onclick="closeQrModal(null)">我知道了</div></div>
    </div>
</div>

<script>
var bannerCount = <?php echo count($banners); ?>; var currentIndex = 0;
var sliderContainer = document.getElementById('sliderContainer'); var dots = document.querySelectorAll('.slider-dot');
function nextSlide() { if(!sliderContainer || bannerCount <= 1) return; currentIndex = (currentIndex + 1) % bannerCount; sliderContainer.style.transform = 'translateX(-' + (currentIndex * 100) + '%)'; dots.forEach((d, i) => d.classList.toggle('active', i === currentIndex)); }
if(bannerCount > 1) setInterval(nextSlide, 3500);

function handleBannerClick(url) {
    if(!url || url.trim() === "" || url === "#" || url === "https://") return;
    if (!/^https?:\/\//i.test(url)) { url = 'https://' + url; }
    window.open(url, '_blank');
}

var qrImg = document.getElementById('modalQrImg'); var qrLoader = document.getElementById('qrLoader'); var scanTip = document.getElementById('scanTip');
qrImg.onload = function() { qrLoader.style.display = 'none'; qrImg.classList.add('loaded'); scanTip.classList.add('loaded'); };

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 📡 核心升级：利用 1.5 秒的转圈时间，静默向后端提交并更新楼栋点击量
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
function openQrModal(id, name, url, notice) {
    // 1. 唤醒全屏 Loading
    var loader = document.getElementById('globalPageLoader');
    loader.classList.add('show');
    
    // 2. ✨ 【独立点击量自增核心】静默利用 fetch 接口去敲醒本页面的 PHP 路由，使数据库对应楼栋点击量 +1
    fetch('index.php?action=click_building&b_id=' + id).catch(e => console.log('网络流延迟保底'));
    
    // 3. 预先重置弹窗基本框架
    document.getElementById('modalTitle').innerText = '🏡 ' + name;
    qrImg.classList.remove('loaded'); scanTip.classList.remove('loaded'); qrImg.src = ''; qrLoader.style.display = 'flex';
    var nb = document.getElementById('modalNoticeBox');
    if(notice && notice.trim() !== "") { nb.innerText = "💡 须知： " + notice; nb.style.display = 'block'; } else { nb.style.display = 'none'; }

    // 4. 1.5 秒后推出弹窗主体
    setTimeout(function() {
        loader.classList.remove('show');
        if(url) qrImg.src = url;
        document.getElementById('qrModal').classList.add('show');
    }, 1500);
}

function closeQrModal(e) { if(e === null || e.target === document.getElementById('qrModal')) document.getElementById('qrModal').classList.remove('show'); }
</script>
</body>
</html>