<?php
/**
 * Tom's Java Jive - Homepage
 */

$pageTitle = "Tom's Java Jive | Premium Coffee Beans & Fresh Roasts";
$extraHead = '<link rel="stylesheet" href="/assets/css/home.css?v=' . filemtime(__DIR__ . '/assets/css/home.css') . '">
<link rel="stylesheet" href="/assets/css/products.css?v=' . filemtime(__DIR__ . '/assets/css/products.css') . '">';
require_once __DIR__ . '/includes/functions.php';

// Get about us sections
$aboutSections = db()->fetchAll(
    "SELECT * FROM about_us_sections WHERE is_active = 1 ORDER BY sort_order ASC"
);

// Get homepage splashes
$splashBlocks = db()->fetchAll(
    "SELECT * FROM homepage_splashes WHERE is_active = 1 ORDER BY sort_order ASC, id ASC"
);

// Get featured products
$featuredProducts = db()->fetchAll(
    "SELECT * FROM products WHERE is_active = 1 AND is_featured = 1 ORDER BY created_at DESC LIMIT 4"
);

// If no featured products, get latest products
if (empty($featuredProducts)) {
    $featuredProducts = db()->fetchAll(
        "SELECT * FROM products WHERE is_active = 1 ORDER BY created_at DESC LIMIT 4"
    );
}

$metaTitle = "Fresh Roasted Artisan Coffee | Tom's Java Jive";
$metaDescription = "Premium artisan coffee beans freshly roasted and delivered to your door. Shop single origin, blends, and specialty coffee from Tom's Java Jive in Weatherford, Texas.";
$metaKeywords = 'artisan coffee beans, fresh roasted coffee, single origin coffee, specialty coffee, Weatherford Texas';
$canonicalUrl = 'https://tomsjavajive.com/';
require_once __DIR__ . '/includes/header.php';
?>

<!-- Hero Section -->
<section class="hero">
    <div class="container">
        <h1>Premium Coffee, Delivered Fresh</h1>
        <p>Artisan roasted coffee beans sourced from the world's finest growing regions. Experience the perfect cup, every time.</p>
        <div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
            <a href="/shop.php" class="btn btn-primary btn-lg">Shop Now</a>
            <a href="#about" class="btn btn-outline btn-lg">Learn More</a>
        </div>
    </div>
</section>

<!-- Coffee Splash Blocks -->
<?php if (!empty($splashBlocks)): ?>
<?php $scrollable = count($splashBlocks) > 4; ?>
<section class="section splash-section" style="background: var(--color-surface);">
    <div class="<?= $scrollable ? 'container splash-scroll-wrap' : 'container' ?>">
        <?php if ($scrollable): ?>
        <button class="splash-arrow splash-arrow-left" id="splashPrev" aria-label="Scroll left"><i class="fas fa-chevron-left"></i></button>
        <?php endif; ?>
        <div class="<?= $scrollable ? 'splash-scroll-track' : 'features-grid' ?>" id="splashTrack">
            <?php foreach ($splashBlocks as $sp): ?>
            <div class="feature-card<?= $scrollable ? ' splash-item' : '' ?>">
                <div class="feature-icon">
                    <?php if (!empty($sp['image_url'])): ?>
                        <img src="<?= htmlspecialchars($sp['image_url']) ?>" alt="<?= htmlspecialchars($sp['title']) ?>" style="width:36px;height:36px;object-fit:cover;border-radius:6px">
                    <?php else: ?>
                        <i class="<?= htmlspecialchars($sp['icon']) ?>"></i>
                    <?php endif; ?>
                </div>
                <h3><?= htmlspecialchars($sp['title']) ?></h3>
                <p><?= htmlspecialchars($sp['description'] ?? '') ?></p>
            </div>
            <?php endforeach; ?>
        </div>
        <?php if ($scrollable): ?>
        <button class="splash-arrow splash-arrow-right" id="splashNext" aria-label="Scroll right"><i class="fas fa-chevron-right"></i></button>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>

<!-- Featured Products Section -->
<section class="section">
    <div class="container">
        <div class="section-header">
            <h2>Featured Products</h2>
            <p>Our most popular coffee selections</p>
        </div>
        
        <div class="product-grid">
            <?php if (empty($featuredProducts)): ?>
                <div style="grid-column: 1 / -1; text-align: center; padding: 3rem;">
                    <p class="text-muted">Products coming soon! Check back later.</p>
                    <a href="/admin/products.php" class="btn btn-primary mt-1">Add Products</a>
                </div>
            <?php else: ?>
                <?php foreach ($featuredProducts as $product): 
                    $images = json_decode($product['images'] ?? '[]', true);
                    $imageUrl = !empty($images) ? $images[0] : '/assets/images/placeholder-product.svg';
                    $price = $product['sale_price'] ?? $product['price'];
                ?>
                    <div class="product-card">
                        <a href="/product.php?id=<?= $product['product_id'] ?>" class="product-card-image">
                            <img src="<?= htmlspecialchars($imageUrl) ?>" alt="<?= htmlspecialchars($product['name']) ?>">
                            <?php if ($product['sale_price']): ?>
                                <span class="product-card-badge">Sale</span>
                            <?php endif; ?>
                        </a>
                        <div class="product-card-body">
                            <?php if ($product['category']): ?>
                                <div class="product-card-category"><?= htmlspecialchars($product['category']) ?></div>
                            <?php endif; ?>
                            <h3 class="product-card-title">
                                <a href="/product.php?id=<?= $product['product_id'] ?>"><?= htmlspecialchars($product['name']) ?></a>
                            </h3>
                            <div class="product-card-price">
                                <span class="current"><?= formatCurrency($price) ?></span>
                                <?php if ($product['sale_price']): ?>
                                    <span class="original"><?= formatCurrency($product['price']) ?></span>
                                <?php endif; ?>
                            </div>
                            <button class="btn btn-primary btn-block add-to-cart-btn" data-product-id="<?= $product['product_id'] ?>" onclick="addToCart('<?= $product['product_id'] ?>', 1)">
                                <i class="fas fa-shopping-bag"></i> Add to Cart
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div style="text-align: center; margin-top: 3rem;">
            <a href="/shop.php" class="btn btn-secondary btn-lg">View All Products</a>
        </div>
    </div>
</section>

<!-- About Section -->
<section class="section" id="about" style="background: var(--color-surface);">
    <div class="container">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 4rem; align-items: center;">
            <div>
                <h2 style="font-family: var(--font-display); font-size: 2.5rem; margin-bottom: 1.5rem;">Our Story</h2>
                <?php foreach ($aboutSections as $sec): ?>
                <?php if (!empty($sec['heading'])): ?>
                    <h3 style="font-size:1.25rem;font-weight:600;margin-bottom:.75rem"><?= htmlspecialchars($sec['heading']) ?></h3>
                <?php endif; ?>
                <?php foreach (array_filter(array_map('trim', preg_split('/\n{2,}/', $sec['body']))) as $para): ?>
                <p style="font-size: 1.125rem; color: var(--color-text-muted); margin-bottom: 1.5rem;">
                    <?= nl2br(htmlspecialchars($para)) ?>
                </p>
                <?php endforeach; ?>
                <?php endforeach; ?>
                <a href="/shop.php" class="btn btn-primary">Explore Our Coffee</a>
            </div>
            <div style="position: relative;">
                <img src="/assets/images/coffee-brewing.jpg" alt="Coffee brewing" style="border-radius: var(--radius-lg); box-shadow: var(--shadow-xl);">
            </div>
        </div>
    </div>
</section>

<!-- Newsletter Section -->
<section class="newsletter">
    <div class="container">
        <h2>Join Our Coffee Community</h2>
        <p>Subscribe for exclusive offers, brewing tips, and early access to new roasts.</p>
        <form class="newsletter-form" id="newsletter-form">
            <input type="email" name="email" placeholder="Your email" required>
            <button type="submit">Subscribe</button>
        </form>
        <p id="newsletter-message" style="margin-top: 1rem; display: none;"></p>
    </div>
</section>

<script>
document.getElementById('newsletter-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    const email = this.querySelector('input[name="email"]').value;
    const msgEl = document.getElementById('newsletter-message');
    
    try {
        const response = await fetch('/api/subscribe.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email })
        });
        const data = await response.json();
        
        msgEl.style.display = 'block';
        if (data.success) {
            msgEl.textContent = 'Thanks for subscribing!';
            msgEl.style.color = '#10B981';
            this.reset();
        } else {
            msgEl.textContent = data.error || 'Something went wrong';
            msgEl.style.color = '#EF4444';
        }
    } catch (err) {
        msgEl.style.display = 'block';
        msgEl.textContent = 'Failed to subscribe. Please try again.';
        msgEl.style.color = '#EF4444';
    }
});
</script>

<script>
(function() {
    var track = document.getElementById('splashTrack');
    var prev  = document.getElementById('splashPrev');
    var next  = document.getElementById('splashNext');
    if (!track || !next) return;
    var step = 240;
    function upd() {
        if (prev) prev.disabled = track.scrollLeft <= 0;
        if (next) next.disabled = track.scrollLeft + track.clientWidth >= track.scrollWidth - 1;
    }
    if (next) next.addEventListener('click', function() { track.scrollBy({left: step, behavior: 'smooth'}); });
    if (prev) prev.addEventListener('click', function() { track.scrollBy({left: -step, behavior: 'smooth'}); });
    track.addEventListener('scroll', upd);
    upd();
})();
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
