<?php
/**
 * 芋头CMS - 家具定制企业网站模板 - 首页
 */
if (!defined('ROOT_PATH')) { exit('Access Denied'); }

$pageTitle = '网站首页';
$extraHead = '';

$slideList = $db->fetchAll("SELECT * FROM {$db->table('slide')} WHERE status = 1 ORDER BY sort_order ASC, id DESC LIMIT 5");

// 产品分类（模型2=产品）
$productChannels = $db->fetchAll("SELECT * FROM {$db->table('channel')} WHERE parent_id = 0 AND channel_type = 2 AND is_show = 1 ORDER BY list_order ASC, id ASC LIMIT 8");

// 按分类获取产品
$productByCat = [];
foreach ($productChannels as $pch) {
    $products = $db->fetchAll("SELECT * FROM {$db->table('product')} WHERE channel_id = ? AND status = 1 ORDER BY create_time DESC LIMIT 4", [$pch['id']]);
    if (!empty($products)) {
        $productByCat[$pch['id']] = [
            'channel' => $pch,
            'products' => $products
        ];
    }
}

// 关于我们内容（取第一个文章模型栏目）
$aboutChannel = $db->fetch("SELECT * FROM {$db->table('channel')} WHERE channel_type = 1 AND is_show = 1 ORDER BY id ASC LIMIT 1");
$aboutArticle = null;
$aboutLitpic = '';
if ($aboutChannel) {
    $aboutArticle = $db->fetch("SELECT * FROM {$db->table('article')} WHERE channel_id = ? AND status = 1 ORDER BY create_time DESC LIMIT 1", [$aboutChannel['id']]);
    $aboutLitpic = $db->fetch("SELECT litpic FROM {$db->table('article')} WHERE channel_id = ? AND status = 1 AND litpic != '' ORDER BY create_time DESC LIMIT 1", [$aboutChannel['id']]);
}

// 案例（取产品模型作为案例展示）
$caseProducts = $db->fetchAll("SELECT p.*, c.channel_name FROM {$db->table('product')} p LEFT JOIN {$db->table('channel')} c ON p.channel_id = c.id WHERE p.status = 1 AND p.litpic != '' ORDER BY p.create_time DESC LIMIT 4");

// 新闻（文章模型）
$newsArticles = $db->fetchAll("SELECT a.*, c.channel_name, c.id as cid FROM {$db->table('article')} a LEFT JOIN {$db->table('channel')} c ON a.channel_id = c.id WHERE a.status = 1 ORDER BY a.create_time DESC LIMIT 6");
$featuredNews = !empty($newsArticles[0]) ? $newsArticles[0] : null;
$otherNews = array_slice($newsArticles, 1);

require_once __DIR__ . '/_header.php';
?>

<!-- 幻灯片 -->
<section class="slider" id="slider">
<?php if (!empty($slideList)): ?>
<div class="slider-wrapper" id="sliderWrapper" style="width:<?php echo count($slideList); ?>00%;">
<?php foreach ($slideList as $si => $slide): ?>
<div class="slider-slide">
<img src="<?php echo htmlspecialchars($slide['litpic']); ?>" alt="<?php echo htmlspecialchars($slide['title']); ?>">
<div class="slider-overlay"></div>
<div class="slider-content">
<p><?php echo htmlspecialchars($slide['title']); ?></p>
<?php if (!empty($slide['link'])): ?>
<a href="<?php echo htmlspecialchars($slide['link']); ?>" class="slider-btn">了解更多</a>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="slider-dots" id="sliderDots">
<?php foreach ($slideList as $si => $slide): ?>
<span class="slider-dot<?php echo $si === 0 ? ' active' : ''; ?>" data-index="<?php echo $si; ?>"></span>
<?php endforeach; ?>
</div>
<div class="slider-arrow prev" id="sliderPrev">‹</div>
<div class="slider-arrow next" id="sliderNext">›</div>
<?php else: ?>
<div class="slider-wrapper">
<div class="slider-slide">
<img src="https://picsum.photos/1920/500?random=1" alt="">
<div class="slider-overlay"></div>
<div class="slider-content">
<h1>专业家具定制</h1>
<p>匠心工艺，品质生活</p>
<a href="#" class="slider-btn">了解更多</a>
</div>
</div>
</div>
<div class="slider-dots"><span class="slider-dot active"></span></div>
<?php endif; ?>
</section>

<!-- 产品中心 -->
<section class="products-section" id="products">
<div class="container">
<div class="section-title">
<h2>产品中心</h2>
<p>甄选材质，匠心工艺，为您定制专属家居</p>
</div>

<?php if (!empty($productByCat)): ?>
<div class="product-categories" id="productCats">
<button class="product-cat-btn active" data-catid="all">全部产品</button>
<?php foreach ($productByCat as $catId => $group): ?>
<button class="product-cat-btn" data-catid="<?php echo $catId; ?>"><?php echo htmlspecialchars($group['channel']['channel_name']); ?></button>
<?php endforeach; ?>
</div>

<?php foreach ($productByCat as $catId => $group): ?>
<div class="product-group<?php echo $catId === array_key_first($productByCat) ? ' active' : ''; ?>" id="group_<?php echo $catId; ?>">
<div style="margin-bottom:8px;font-size:14px;color:var(--accent);font-weight:600;">
<a href="<?php echo getUrl('channel', $group['channel']['id']); ?>" style="color:var(--accent);">
<?php echo htmlspecialchars($group['channel']['channel_name']); ?>系列 &raquo;
</a>
</div>
<div class="product-grid">
<?php foreach ($group['products'] as $p): ?>
<a href="<?php echo getUrl('product', $p['id']); ?>" class="product-card">
<div class="product-card-img">
<?php if (!empty($p['litpic'])): ?>
<img src="<?php echo htmlspecialchars($p['litpic']); ?>" alt="<?php echo htmlspecialchars($p['title']); ?>">
<?php else: ?>
<img src="https://picsum.photos/400/300?random=<?php echo $p['id']; ?>" alt="<?php echo htmlspecialchars($p['title']); ?>">
<?php endif; ?>
</div>
<div class="product-card-info">
<h3><?php echo htmlspecialchars($p['title']); ?></h3>
<?php if (!empty($p['price'])): ?>
<p class="price">¥<?php echo number_format($p['price'], 2); ?></p>
<?php else: ?>
<p class="price"><small>查看详情</small></p>
<?php endif; ?>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>

<?php else: ?>
<div class="product-grid" style="grid-template-columns:repeat(4,1fr);">
<?php
$allProducts = $db->fetchAll("SELECT * FROM {$db->table('product')} WHERE status = 1 ORDER BY create_time DESC LIMIT 8");
foreach ($allProducts as $p):
?>
<a href="<?php echo getUrl('product', $p['id']); ?>" class="product-card">
<div class="product-card-img">
<?php if (!empty($p['litpic'])): ?>
<img src="<?php echo htmlspecialchars($p['litpic']); ?>" alt="<?php echo htmlspecialchars($p['title']); ?>">
<?php else: ?>
<img src="https://picsum.photos/400/300?random=<?php echo $p['id']; ?>" alt="">
<?php endif; ?>
</div>
<div class="product-card-info">
<h3><?php echo htmlspecialchars($p['title']); ?></h3>
<?php if (!empty($p['price'])): ?>
<p class="price">¥<?php echo number_format($p['price'], 2); ?></p>
<?php endif; ?>
</div>
</a>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</section>

<!-- 关于我们 -->
<section class="about-section section" id="about">
<div class="container">
<div class="section-title">
<h2>关于我们</h2>
<p>匠心品质，专注定制家具行业</p>
</div>
<div class="about-content">
<div class="about-img">
<?php if ($aboutLitpic && !empty($aboutLitpic['litpic'])): ?>
<img src="<?php echo htmlspecialchars($aboutLitpic['litpic']); ?>" alt="关于我们">
<?php else: ?>
<img src="https://picsum.photos/600/400?random=10" alt="关于我们">
<?php endif; ?>
</div>
<div class="about-text">
<?php if ($aboutArticle): ?>
<h3><?php echo htmlspecialchars($aboutArticle['title']); ?></h3>
<p><?php echo htmlspecialchars(mb_substr(strip_tags($aboutArticle['content']), 0, 300)); ?>...</p>
<div class="about-features">
<div class="about-feature">专业设计团队</div>
<div class="about-feature">精选环保材质</div>
<div class="about-feature">免费上门测量</div>
<div class="about-feature">终身售后服务</div>
<div class="about-feature">快速交货周期</div>
<div class="about-feature">量身定制方案</div>
</div>
<div style="margin-top:24px;">
<a href="<?php echo getUrl('article', $aboutArticle['id']); ?>" class="slider-btn" style="display:inline-block;padding:10px 30px;border-radius:4px;">查看详情</a>
</div>
<?php else: ?>
<h3>专注定制家具行业</h3>
<p>我们是一家专业从事家具定制设计、生产、销售及服务的企业。拥有多年行业经验，致力于为客户提供高品质、个性化的家具定制解决方案。</p>
<p>公司引进先进的生产设备和技术，选用环保材质，由资深设计团队倾力打造。每一件产品都经过严格质量检验，确保交付给客户的都是精品。</p>
<div class="about-features">
<div class="about-feature">专业设计团队</div>
<div class="about-feature">精选环保材质</div>
<div class="about-feature">免费上门测量</div>
<div class="about-feature">终身售后服务</div>
<div class="about-feature">快速交货周期</div>
<div class="about-feature">量身定制方案</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</section>

<!-- 案例展示 -->
<section class="cases-section" id="cases">
<div class="container">
<div class="section-title">
<h2>案例展示</h2>
<p>精选定制案例，品质见证</p>
</div>
</div>
<?php if (!empty($caseProducts)): ?>
<div class="cases-marquee-wrapper">
<div class="cases-marquee" id="casesMarquee">
<?php
$marqueeItems = array_merge($caseProducts, $caseProducts); // 复制一份实现无缝滚动
foreach ($marqueeItems as $p):
?>
<a href="<?php echo getUrl('product', $p['id']); ?>" class="case-card">
<div class="case-card-img">
<?php if (!empty($p['litpic'])): ?>
<img src="<?php echo htmlspecialchars($p['litpic']); ?>" alt="<?php echo htmlspecialchars($p['title']); ?>">
<?php else: ?>
<img src="https://picsum.photos/300/200?random=<?php echo $p['id'] + 100; ?>" alt="">
<?php endif; ?>
</div>
<div class="case-card-info">
<h3><?php echo htmlspecialchars($p['title']); ?></h3>
<p><?php echo htmlspecialchars($p['channel_name'] ?? ''); ?></p>
</div>
</a>
<?php endforeach; ?>
</div>
</div>
<?php else: ?>
<div style="text-align:center;color:var(--gray-light);padding:40px 0;">暂无案例内容</div>
<?php endif; ?>

<!-- 新闻资讯 -->
<section class="news-section section" id="news">
<div class="container">
<div class="section-title">
<h2>新闻资讯</h2>
<p>实时资讯，了解行业动态</p>
</div>
<div class="news-layout">
<?php if ($featuredNews): ?>
<a href="<?php echo getUrl('article', $featuredNews['id']); ?>" class="news-featured">
<?php if (!empty($featuredNews['litpic'])): ?>
<img src="<?php echo htmlspecialchars($featuredNews['litpic']); ?>" alt="<?php echo htmlspecialchars($featuredNews['title']); ?>">
<?php else: ?>
<img src="https://picsum.photos/600/340?random=20" alt="">
<?php endif; ?>
<div class="news-featured-overlay">
<h3><?php echo htmlspecialchars($featuredNews['title']); ?></h3>
<span><?php echo date('Y-m-d', $featuredNews['create_time']); ?></span>
</div>
</a>
<?php endif; ?>

<div class="news-list">
<?php if (!empty($otherNews)): ?>
<?php foreach ($otherNews as $na): ?>
<a href="<?php echo getUrl('article', $na['id']); ?>" class="news-item">
<div class="news-item-date">
<span class="day"><?php echo date('d', $na['create_time']); ?></span>
<span class="month"><?php echo date('m月', $na['create_time']); ?></span>
</div>
<div class="news-item-info">
<h3><?php echo htmlspecialchars($na['title']); ?></h3>
<p><?php echo htmlspecialchars(mb_substr(strip_tags($na['description'] ?? ''), 0, 60)); ?></p>
</div>
</a>
<?php endforeach; ?>
<?php else: ?>
<p style="color:var(--gray-light);text-align:center;padding:40px 0;">暂无新闻资讯</p>
<?php endif; ?>
</div>
</div>
</div>
</section>

<!-- 留言 -->
<section class="guestbook-section section" id="guestbook">
<div class="container">
<div class="section-title">
<h2>在线留言</h2>
<p>有任何问题或需求，请给我们留言</p>
</div>
<form class="guestbook-form" id="guestbookForm" method="post" action="/public/guestbook.php">
<input type="hidden" name="ajax" value="1">
<div class="form-row">
<input type="text" name="name" placeholder="您的姓名" required>
<input type="text" name="contact" placeholder="联系电话" required>
</div>
<textarea name="content" placeholder="请输入留言内容..." required></textarea>
<div style="display:flex;justify-content:center;gap:16px;align-items:center;margin-top:4px;">
<button type="submit">提交留言</button>
<span class="guestbook-tip" id="guestbookTip"></span>
</div>
</form>
</div>
</section>

<script>
// 幻灯片
(function(){
var wrapper = document.getElementById('sliderWrapper');
var dots = document.querySelectorAll('.slider-dot');
var prev = document.getElementById('sliderPrev');
var next = document.getElementById('sliderNext');
if (!wrapper) return;
var total = dots.length || document.querySelectorAll('.slider-slide').length;
var current = 0;
var timer;
function go(idx) {
current = (idx + total) % total;
wrapper.style.transform = 'translateX(-' + (current * 100 / total) + '%)';
dots.forEach(function(d,i){ d.classList.toggle('active', i===current); });
}
function nextSlide() { go(current + 1); }
function prevSlide() { go(current - 1); }
function startTimer() { timer = setInterval(nextSlide, 4500); }
function stopTimer() { clearInterval(timer); }
if (next) next.addEventListener('click', function(){ stopTimer(); nextSlide(); startTimer(); });
if (prev) prev.addEventListener('click', function(){ stopTimer(); prevSlide(); startTimer(); });
dots.forEach(function(d){ d.addEventListener('click', function(){ stopTimer(); go(parseInt(this.dataset.index)); startTimer(); }); });
wrapper.addEventListener('mouseenter', stopTimer);
wrapper.addEventListener('mouseleave', startTimer);
startTimer();
})();

// 产品分类切换
(function(){
var btns = document.querySelectorAll('.product-cat-btn');
var groups = document.querySelectorAll('.product-group');
btns.forEach(function(btn){
btn.addEventListener('click', function(){
var catid = this.dataset.catid;
btns.forEach(function(b){ b.classList.remove('active'); });
this.classList.add('active');
groups.forEach(function(g){
if (catid === 'all') { g.classList.add('active'); }
else { g.classList.toggle('active', g.id === 'group_' + catid); }
});
});
});
})();

// 案例自动滚动（默认已由CSS animation驱动，这里可加额外控制）
(function(){
var marquee = document.getElementById('casesMarquee');
if (marquee) {
marquee.addEventListener('mouseenter', function(){ marquee.style.animationPlayState = 'paused'; });
marquee.addEventListener('mouseleave', function(){ marquee.style.animationPlayState = 'running'; });
}
})();

// 留言
(function(){
var form = document.getElementById('guestbookForm');
if (form) {
form.addEventListener('submit', function(e){
e.preventDefault();
var fd = new FormData(form);
fd.append('ajax', '1');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/public/guestbook.php', true);
xhr.onload = function(){
var r;
try { r = JSON.parse(this.responseText); } catch(e) { r = {msg:'提交成功'}; }
var tip = document.getElementById('guestbookTip');
if (r.code == 200) {
form.reset();
tip.style.color = '#16a34a';
tip.textContent = '✅ ' + (r.msg || '提交成功');
} else {
tip.style.color = '#dc2626';
tip.textContent = '❌ ' + (r.msg || '提交失败');
}
};
xhr.send(fd);
});
}
})();
</script>

<?php require_once __DIR__ . '/_footer.php'; ?>