<?php
require 'core.php';

// === 【安全整改】移除隐身门禁 (跳转百度版) ===
// 微信爬虫极度反感外跳百度逻辑，现改为允许公开访问首页，敏感操作由登录拦截。
// ==========================================

// === 【安全增强】实时检查用户状态 ===
check_user_exists(); 

// 1. 获取分类列表
$cats = $DB->query("SELECT * FROM categories ORDER BY sort DESC, id ASC")->fetchAll();
$cid = isset($_GET['cid']) ? intval($_GET['cid']) : 0;
$kw  = isset($_GET['kw']) ? trim($_GET['kw']) : '';

// 2. 查询逻辑 (新增搜索优先)
if (!empty($kw)) {
    // 搜索模式：全局模糊搜索
    $stmt = $DB->prepare("SELECT * FROM products WHERE name LIKE ? ORDER BY id DESC");
    $stmt->execute(['%'.$kw.'%']);
} elseif ($cid > 0) {
    // 分类模式
    $stmt = $DB->prepare("SELECT * FROM products WHERE category_id = ? ORDER BY id DESC");
    $stmt->execute([$cid]);
} else {
    // 默认模式：限制显示最新50个，防止卡顿
    $stmt = $DB->query("SELECT * FROM products ORDER BY id DESC LIMIT 50");
}
$products = $stmt->fetchAll();
//更多源码在：wwww.baozl.asia
// 3. 获取轮播图与公告
try {
    $slides = $DB->query("SELECT * FROM slides ORDER BY sort DESC, id DESC")->fetchAll();
} catch(Exception $e) { $slides = []; }
$site_notice = get_config('site_notice');

// === 读取后台开关状态 ===
$show_slides = get_config('show_slides'); 
$show_notice = get_config('show_notice');
?>


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>项目商城中心</title>
    <link href="https://cdn.staticfile.org/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.staticfile.org/bootstrap-icons/1.10.0/font/bootstrap-icons.css">
    <style>
        /* === 全局高定风格 (V3.0) === */
        :root {
            --primary-blue: #007aff;
            --primary-gradient: linear-gradient(135deg, #007aff, #0062cc);
            --accent-orange: #ff5e00;
            --bg-color: #f7f9fc;
            --card-shadow: 0 1px 3px rgba(0,0,0,0.03); /* 极简阴影 */
            --text-main: #1d1d1f;
            --text-sub: #86868b;
        }

        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; background: var(--bg-color); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
        
        .app-container { display: flex; flex-direction: column; height: 100%; position: relative; max-width: 600px; margin: 0 auto; background: #fff; box-shadow: 0 0 20px rgba(0,0,0,0.05); }
        
        /* === 【新】顶部搜索栏 === */
        .top-search-header {
            padding: 10px 15px;
            background: #fff;
            position: relative;
            z-index: 50;
            border-bottom: 1px solid rgba(0,0,0,0.03);
        }
        .search-box {
            background: #f2f4f7; /* 浅灰输入框背景 */
            border-radius: 20px;
            display: flex;
            align-items: center;
            padding: 0 12px;
            height: 36px;
            transition: all 0.3s;
        }
        .search-box:focus-within { background: #fff; box-shadow: 0 0 0 2px rgba(0,122,255,0.1); border: 1px solid var(--primary-blue); }
        .search-input {
            border: none;
            background: transparent;
            width: 100%;
            height: 100%;
            font-size: 13px;
            color: #333;
            outline: none;
            margin-left: 8px;
        }
        .search-btn {
            border: none;
            background: none;
            color: var(--primary-blue);
            font-size: 13px;
            font-weight: 600;
            padding: 0 5px;
            white-space: nowrap;
        }

        /* 轮播图 */
        .carousel-item img { width: 100%; height: 150px; object-fit: cover; }
        
        /* 公告栏 */
        .notice-bar { background-color: #fff8f2; color: var(--accent-orange); padding: 0 15px; font-size: 12px; display: flex; align-items: center; border-bottom: 1px solid #ffeedd; height: 32px; font-weight: 500; }
        
        /* 主体布局 */
        .main-body { display: flex; flex: 1; overflow: hidden; background: var(--bg-color); }
        
        /* 侧边栏 */
        .sidebar { width: 85px; background-color: #fff; height: 100%; overflow-y: auto; padding-bottom: 140px; flex-shrink: 0; border-right: 1px solid rgba(0,0,0,0.03); }
        .nav-item { display: flex; align-items: center; justify-content: center; height: 50px; width: 100%; color: var(--text-sub); text-decoration: none; font-size: 12px; position: relative; transition: all 0.2s; font-weight: 500; }
        .nav-item.active { background: #f0f8ff; color: var(--primary-blue); font-weight: 700; font-size: 13px; }
        .nav-item.active::before { content: ''; position: absolute; left: 0; top: 12px; bottom: 12px; width: 3px; background-color: var(--primary-blue); border-radius: 0 4px 4px 0; }
        
        /* 商品列表区域 */
        .main-content { flex: 1; height: 100%; overflow-y: auto; padding: 10px; padding-bottom: 160px; background-color: var(--bg-color); }
        
        /* === 商品卡片 (紧凑+多行文本) === */
        .product-item { 
            display: flex; 
            padding: 10px; 
            background: #fff; 
            border-radius: 10px; 
            margin-bottom: 8px; 
            box-shadow: var(--card-shadow); 
            border: none;
            align-items: flex-start; /* 顶部对齐 */
            transition: transform 0.1s;
            position: relative;
        }
        .product-item:active { transform: scale(0.99); background: #fafafa; }
        
        .p-img { 
            width: 64px; height: 64px; 
            border-radius: 6px; 
            object-fit: cover; 
            margin-right: 10px; 
            flex-shrink: 0; 
            background: #f8f8f8; 
            border: 1px solid rgba(0,0,0,0.03);
        }
        
        .p-info { flex: 1; display: flex; flex-direction: column; justify-content: space-between; min-height: 64px; }
        
        /* 【核心】标题样式：小字号 + 3行显示 */
        .p-name { 
            font-size: 12px; /* 字号更小 */
            font-weight: 600; 
            color: var(--text-main); 
            line-height: 1.4; 
            overflow: hidden; 
            display: -webkit-box; 
            -webkit-line-clamp: 3; /* 允许显示3行 */
            -webkit-box-orient: vertical; 
            margin-bottom: 6px;
        }
        
        .p-bottom { display: flex; align-items: center; justify-content: space-between; margin-top: auto; }
        .p-price { color: var(--accent-orange); font-weight: 800; font-size: 15px; }
        .p-price::before { content: '¥'; font-size: 11px; margin-right: 1px; }
        
        /* 按钮美化 */
        .btn-buy-sm { 
            padding: 3px 10px; 
            border-radius: 12px; 
            font-size: 11px; 
            font-weight: 600; 
            background: #fff;
            color: var(--primary-blue); 
            border: 1px solid var(--primary-blue);
            text-decoration: none; 
        }
        
        /* 购物车选择框 */
        .add-cart-btn { 
            width: 22px; height: 22px; 
            border-radius: 50%; 
            border: 1px solid #ddd; 
            display: flex; align-items: center; justify-content: center; 
            background: #fff; color: var(--primary-blue); 
            transition: all 0.2s; 
        }
        .add-cart-btn::before { content: '\F64D'; font-family: "bootstrap-icons"; font-size: 13px; }
        .prod-check { display: none; } 
        .prod-check:checked + .add-cart-btn { 
            background: var(--primary-blue); 
            border-color: var(--primary-blue); 
            color: #fff; 
            box-shadow: 0 2px 5px rgba(0, 122, 255, 0.3);
        }
        .prod-check:checked + .add-cart-btn::before { content: '\F26E'; }

        /* 底部个人中心入口 */
        .tech-navbar { 
            position: fixed; bottom: 85px; left: 5%; width: 90%; height: 48px; 
            background: rgba(255, 255, 255, 0.95); 
            backdrop-filter: blur(10px);
            border-radius: 24px; 
            display: flex; justify-content: space-between; align-items: center; 
            padding: 0 15px; z-index: 990; 
            border: 1px solid rgba(0,0,0,0.05); 
            box-shadow: 0 8px 20px rgba(0,0,0,0.06); 
        }
        
        /* 底部结算栏 */
        .settle-bar { 
            position: fixed; bottom: 0; left: 0; width: 100%; height: 60px; 
            background: #fff; 
            border-top: 1px solid #f0f0f0;
            display: flex; align-items: center; justify-content: space-between; padding: 0 15px; z-index: 1000; 
            max-width: 600px; margin: 0 auto; right: 0; 
        }
        .settle-total { font-size: 12px; color: var(--text-main); margin-right: 4px; }
        .settle-price { color: var(--accent-orange); font-size: 18px; font-weight: 800; font-family: -apple-system, sans-serif; }
        .btn-submit-cart { 
            background: var(--text-main); 
            color: #fff; border: none; border-radius: 30px; 
            padding: 0 20px; height: 34px; 
            font-weight: 600; font-size: 13px; 
        }
        .btn-submit-cart:disabled { background: #eee; color: #aaa; }
        .btn-clear-cart { background: #f5f5f5; color: #666; border: none; border-radius: 30px; padding: 4px 12px; font-size: 12px; margin-right: 8px; }

        @media (min-width: 600px) {
            .app-container { border-left: 1px solid #eee; border-right: 1px solid #eee; }
            .tech-navbar { left: 50%; transform: translateX(-50%); width: 540px; }
        }
    </style>
</head>
<body>
<div class="app-container">
    
    <div class="top-search-header">
        <form action="" method="GET" class="search-box">
            <i class="bi bi-search text-muted ps-1"></i>
            <input type="text" name="kw" class="search-input" placeholder="搜索商品名称..." value="<?php echo htmlspecialchars($kw); ?>">
            <?php if(!empty($kw)): ?><a href="index.php" class="text-secondary me-2"><i class="bi bi-x-circle-fill"></i></a><?php endif; ?>
            <button type="submit" class="search-btn">搜索</button>
        </form>
    </div>

    <?php if($show_slides !== '0' && !empty($slides) && empty($kw)): ?>
    <div id="homeSlide" class="carousel slide" data-bs-ride="carousel">
        <div class="carousel-inner">
            <?php foreach($slides as $k => $s): ?>
            <div class="carousel-item <?php echo $k==0?'active':''; ?>"><img src="<?php echo htmlspecialchars($s['img']); ?>" class="d-block w-100"></div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if($show_notice !== '0' && !empty($site_notice)): ?>
    <div class="notice-bar"><span class="badge bg-warning text-dark me-2" style="font-size:10px;padding:2px 4px;">公告</span><marquee><?php echo htmlspecialchars($site_notice); ?></marquee></div>
    <?php endif; ?>

    <div class="main-body">
        <div class="sidebar">
            <?php foreach($cats as $c): ?>
            <a href="?cid=<?php echo $c['id']; ?>" class="nav-item <?php echo ($cid==$c['id'] && empty($kw))?'active':''; ?>"><?php echo htmlspecialchars($c['name']); ?></a>
            <?php endforeach; ?>
        </div>

        <div class="main-content">
            <form id="multiPayForm" action="select_template.php" method="POST" style="display:none;"></form>
            <?php if(empty($products)): ?>
                <div style="text-align:center; padding:60px 0; color:#ccc;">
                    <i class="bi bi-search fs-1 d-block mb-3 opacity-25"></i>
                    <span style="font-size:12px;">未找到相关商品</span>
                    <?php if(!empty($kw)): ?><div class="mt-3"><a href="index.php" class="btn btn-sm btn-outline-secondary rounded-pill px-4" style="font-size:12px;">返回首页</a></div><?php endif; ?>
                </div>
            <?php else: ?>
                <?php foreach($products as $row): ?>
                <div class="product-item">
                    <img src="<?php echo htmlspecialchars($row['image']); ?>" class="p-img" loading="lazy">
                    <div class="p-info">
                        <div class="p-name"><?php echo htmlspecialchars($row['name']); ?></div>
                        <div class="p-bottom">
                            <div class="p-price"><?php echo $row['price']; ?></div>
                            <div style="display:flex; align-items:center; gap:8px;">
                                <a href="select_template.php?product_id=<?php echo $row['id']; ?>" class="btn-buy-sm">购买</a>
                                <label style="margin:0; cursor:pointer;">
                                    <input type="checkbox" class="prod-check" id="chk_<?php echo $row['id']; ?>" value="<?php echo $row['id']; ?>" onchange="toggleItem(<?php echo $row['id']; ?>, <?php echo $row['price']; ?>)">
                                    <div class="add-cart-btn"></div>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="tech-navbar" id="secret-door-btn">
        <div style="display:flex; align-items:center;">
            <?php if(isset($_SESSION['user_id'])): ?>
                <?php $curr_user = $DB->query("SELECT avatar, nickname FROM users WHERE id=".intval($_SESSION['user_id']))->fetch(); ?>
                <img src="<?php echo htmlspecialchars($curr_user['avatar'] ?: 'youke.png'); ?>" style="width:28px; height:28px; border-radius:50%; margin-right:8px;">
                <div>
                    <div style="font-size:12px; font-weight:700; color:#333; line-height:1.2;"><?php echo htmlspecialchars($curr_user['nickname']); ?></div>
                </div>
            <?php else: ?>
                <img src="youke.png" style="width:28px; height:28px; border-radius:50%; margin-right:8px;">
                <span style="font-size:12px; font-weight:600;">游客访问</span>
            <?php endif; ?>
        </div>
        <a href="<?php echo isset($_SESSION['user_id'])?'user.php':'login.php'; ?>" style="color:#333; text-decoration:none; font-size:12px; font-weight:600; display:flex; align-items:center;">
            <?php echo isset($_SESSION['user_id'])?'个人中心':'立即登录'; ?> <i class="bi bi-chevron-right ms-1" style="font-size:10px;"></i>
        </a>
    </div>

    <div class="settle-bar">
        <div class="settle-info">
            <span class="settle-total">合计</span>
            <span class="settle-price" id="totalPrice">0.00</span>
            <span style="font-size:11px;color:#999;margin-left:2px;">(<span id="totalCount">0</span>)</span>
        </div>
        <div class="settle-btns d-flex align-items-center">
            <button type="button" class="btn-clear-cart" onclick="clearCart()">清空</button>
            <button type="button" class="btn-submit-cart" id="btnSubmit" disabled onclick="submitMultiOrder()">去结算</button>
        </div>
    </div>
</div>

<script src="https://cdn.staticfile.org/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<script>
    const CART_KEY = 'shop_cart_v1';
    function getCart() { var saved = localStorage.getItem(CART_KEY); return saved ? JSON.parse(saved) : {}; }
    function saveCart(cart) { localStorage.setItem(CART_KEY, JSON.stringify(cart)); updateCartUI(); }

    function clearCart() { if(confirm('确认清空已选项目？')) { localStorage.removeItem(CART_KEY); updateCartUI(); } }

    function updateCartUI() {
        var cart = getCart(), total = 0, count = 0;
        for (var id in cart) { total += parseFloat(cart[id]); count++; }
        document.getElementById('totalPrice').innerText = total.toFixed(2);
        document.getElementById('totalCount').innerText = count;
        document.getElementById('btnSubmit').disabled = (count === 0);
        document.querySelectorAll('.prod-check').forEach(box => { box.checked = cart.hasOwnProperty(box.value); });
    }

    function toggleItem(id, price) {
        var cart = getCart(), strId = String(id);
        if (cart.hasOwnProperty(strId)) { delete cart[strId]; } else { cart[strId] = price; }
        saveCart(cart);
    }

    function submitMultiOrder() {
        var cart = getCart(), form = document.getElementById('multiPayForm');
        form.innerHTML = '';
        for (var id in cart) {
            var input = document.createElement('input');
            input.type = 'hidden'; input.name = 'product_ids[]'; input.value = id;
            form.appendChild(input);
        }
        form.submit();
    }

    window.onload = updateCartUI;

    var c=0,t;
    document.getElementById('secret-door-btn').addEventListener('click',function(e){
        if(e.target.tagName !== 'A') {
            c++; clearTimeout(t); t=setTimeout(function(){c=0},800);
            if(c>=5) location.href='admin/login.php';
        }
    });
</script>
</body>
</html>