<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);

// Flash sale products
$flashStmt = $pdo->query("SELECT p.*, fsp.flash_order FROM products p
    JOIN flash_sale_products fsp ON p.id = fsp.product_id
    WHERE p.stock >= 0
    ORDER BY fsp.flash_order ASC LIMIT 20");
$flashProducts = $flashStmt->fetchAll();

// Categories with products
$catStmt = $pdo->query("SELECT * FROM categories WHERE status = 1 ORDER BY id ASC");
$categories = $catStmt->fetchAll();
$catProducts = [];
foreach ($categories as $cat) {
    $ps = $pdo->prepare("SELECT p.* FROM products p WHERE p.category_id = ? ORDER BY p.created_at DESC LIMIT 10");
    $ps->execute([$cat['id']]);
    $catProducts[$cat['id']] = $ps->fetchAll();
}

function getProductVariations($pdo, $productId) {
    $stmt = $pdo->prepare("SELECT * FROM product_variations WHERE product_id = ? ORDER BY variation_name, variation_value");
    $stmt->execute([$productId]);
    $vars = $stmt->fetchAll();
    $grouped = [];
    foreach ($vars as $v) $grouped[$v['variation_name']][] = $v;
    return $grouped;
}

// Render a product card
// Variable product → "Buy Now" goes to product page first
// Simple product   → "Buy Now" goes direct to checkout-add
function renderProductCard($p, $vars, $baseUrl, $uploadsUrl) {
    $hasVars    = !empty($vars);
    $outOfStock = $p['stock'] <= 0;
    $pid        = $p['id'];

    // For simple products direct link; for variable products, link starts pointing at product page
    // JS will update it after variation selection
    $firstVarId  = '';
    if ($hasVars) foreach ($vars as $vg) { $firstVarId = $vg[0]['id']; break; }

    $buyHref = $hasVars
        ? $baseUrl . '/product.php?id=' . $pid
        : $baseUrl . '/checkout-add.php?product_id=' . $pid . '&variation_id=&qty=1';

    $name  = htmlspecialchars($p['name'],    ENT_QUOTES,'UTF-8');
    $img   = htmlspecialchars($p['image']??'',ENT_QUOTES,'UTF-8');
    ob_start();
?>
<div class="product-card">
    <?php if ($p['is_flash']): ?><span class="flash-tag">🔥 সেল</span><?php endif; ?>
    <?php if ($outOfStock): ?><span class="out-of-stock-tag">স্টক নেই</span><?php endif; ?>

    <a href="<?= $baseUrl ?>/product.php?id=<?= $pid ?>">
        <?php if ($img): ?>
            <img class="card-img" src="<?= $uploadsUrl . $img ?>" alt="<?= $name ?>" loading="lazy">
        <?php else: ?>
            <div class="card-img-placeholder"><i class="fas fa-image"></i></div>
        <?php endif; ?>
    </a>

    <div class="card-body">
        <div class="card-title"><a href="<?= $baseUrl ?>/product.php?id=<?= $pid ?>"><?= $name ?></a></div>
        <div class="card-price" id="cprice-<?= $pid ?>">৳<?= number_format($p['price'], 2) ?></div>

        <?php if ($hasVars): ?>
            <?php foreach ($vars as $varName => $options): ?>
                <div class="var-label"><?= htmlspecialchars($varName,ENT_QUOTES,'UTF-8') ?></div>
                <div class="card-variations" data-pid="<?= $pid ?>" data-base="<?= (float)$p['price'] ?>">
                    <?php foreach ($options as $opt): ?>
                        <span class="var-option"
                              data-varid="<?= $opt['id'] ?>"
                              data-extra="<?= (float)$opt['extra_price'] ?>"
                              data-pid="<?= $pid ?>">
                            <?= htmlspecialchars($opt['variation_value'],ENT_QUOTES,'UTF-8') ?>
                            <?php if ($opt['extra_price'] > 0): ?>(+৳<?= (int)$opt['extra_price'] ?>)<?php endif; ?>
                        </span>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!$outOfStock): ?>
            <a class="btn-buy card-buy-btn"
               id="cbuy-<?= $pid ?>"
               href="<?= $buyHref ?>"
               data-pid="<?= $pid ?>"
               data-hasvars="<?= $hasVars ? '1' : '0' ?>"
               data-base="<?= (float)$p['price'] ?>"
               data-baseurl="<?= $baseUrl ?>">
               <i class="fas fa-bolt"></i> এখনই কিনুন
            </a>
        <?php else: ?>
            <button class="btn-buy" disabled style="opacity:.45;cursor:not-allowed;">স্টক নেই</button>
        <?php endif; ?>
    </div>
</div>
<?php return ob_get_clean();
}

include __DIR__ . '/includes/header.php';
?>

<!-- Hero Banner -->
<?php if (!empty($settings['banner_image'])): ?>
<div class="hero-banner">
    <img src="<?= UPLOADS_URL . e($settings['banner_image']) ?>" alt="<?= e($settings['site_name']) ?>">
    <div class="hero-overlay">
        <div class="hero-text">
            <h1><?= e($settings['site_name']) ?></h1>
            <p>সেরা মানের পণ্য, সেরা দামে পান</p>
            <a href="#products" class="btn-hero">কেনাকাটা শুরু করুন</a>
        </div>
    </div>
</div>
<?php else: ?>
<div class="hero-banner" style="height:280px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,var(--navy),var(--navy-light));">
    <div class="hero-text" style="text-align:center;">
        <h1 style="color:#fff;font-size:2rem;"><?= e($settings['site_name']) ?></h1>
        <p style="color:rgba(255,255,255,.8);margin:8px 0 20px;">সেরা মানের পণ্য, সেরা দামে পান</p>
        <a href="#products" class="btn-hero">কেনাকাটা শুরু করুন</a>
    </div>
</div>
<?php endif; ?>

<!-- Flash Sale -->
<?php if (!empty($flashProducts)): ?>
<section class="flash-sale-section">
    <div class="container">
        <div class="section-header">
            <div class="flash-badge"><i class="fas fa-bolt"></i> ফ্ল্যাশ সেল</div>
            <h2>বিশেষ ছাড়ের পণ্য</h2>
            <p>সীমিত সময়ের অফার, দ্রুত অর্ডার করুন!</p>
        </div>
        <div class="carousel-wrapper">
            <div class="carousel-track auto-carousel">
                <?php foreach ($flashProducts as $p):
                    echo renderProductCard($p, getProductVariations($pdo,$p['id']), BASE_URL, UPLOADS_URL);
                endforeach; ?>
            </div>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- Category Sections -->
<section class="categories-section" id="products">
    <div class="container">
        <?php foreach ($categories as $cat):
            if (empty($catProducts[$cat['id']])) continue; ?>
        <div class="category-section">
            <div class="cat-header">
                <h3><?= e($cat['name']) ?></h3>
                <a href="<?= BASE_URL ?>/category.php?id=<?= $cat['id'] ?>" class="see-all">
                    সব দেখুন <i class="fas fa-arrow-right"></i>
                </a>
            </div>
            <div class="carousel-wrapper">
                <div class="carousel-track auto-carousel">
                    <?php foreach ($catProducts[$cat['id']] as $p):
                        echo renderProductCard($p, getProductVariations($pdo,$p['id']), BASE_URL, UPLOADS_URL);
                    endforeach; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</section>

<!-- Info Section -->
<section class="info-section">
    <div class="container">
        <div class="info-grid">
            <div class="info-item"><i class="fas fa-truck"></i><h4>দ্রুত ডেলিভারি</h4><p>সারা বাংলাদেশে ৭২ ঘণ্টার মধ্যে</p></div>
            <div class="info-item"><i class="fas fa-shield-alt"></i><h4>নিরাপদ পেমেন্ট</h4><p>ক্যাশ অন ডেলিভারি ও মোবাইল ব্যাংকিং</p></div>
            <div class="info-item"><i class="fas fa-headset"></i><h4>২৪/৭ সাপোর্ট</h4><p>যেকোনো সমস্যায় আমরা সবসময় আছি</p></div>
            <div class="info-item"><i class="fas fa-undo"></i><h4>সহজ রিটার্ন</h4><p>পণ্যে সমস্যা হলে সহজেই ফেরত দিন</p></div>
        </div>
    </div>
</section>

<script>
// ===== VARIATION CHIP SELECTION =====
document.querySelectorAll('.card-variations').forEach(varGroup => {
    const chips   = varGroup.querySelectorAll('.var-option');
    const pid     = varGroup.dataset.pid;
    const base    = parseFloat(varGroup.dataset.base);

    // Select first chip by default
    if (chips.length) {
        chips[0].classList.add('selected');
        // Update buy link with first variation
        const buyBtn = document.getElementById('cbuy-' + pid);
        if (buyBtn && buyBtn.dataset.hasvars === '1') {
            buyBtn.href = buyBtn.dataset.baseurl + '/checkout-add.php?product_id=' + pid
                        + '&variation_id=' + chips[0].dataset.varid + '&qty=1';
        }
    }

    chips.forEach(chip => {
        chip.addEventListener('click', () => {
            chips.forEach(c => c.classList.remove('selected'));
            chip.classList.add('selected');

            // Update price
            const extra   = parseFloat(chip.dataset.extra || 0);
            const priceEl = document.getElementById('cprice-' + pid);
            if (priceEl) priceEl.textContent = '৳' + (base + extra).toFixed(2);

            // Update buy link (now goes direct to checkout since variation chosen)
            const buyBtn = document.getElementById('cbuy-' + pid);
            if (buyBtn && buyBtn.dataset.hasvars === '1') {
                buyBtn.href = buyBtn.dataset.baseurl + '/checkout-add.php?product_id=' + pid
                            + '&variation_id=' + chip.dataset.varid + '&qty=1';
            }
        });
    });
});

// ===== AUTO CAROUSEL =====
document.querySelectorAll('.auto-carousel').forEach(track => {
    let raf;
    let pos = 0;

    function step() {
        const maxScroll = track.scrollWidth - track.clientWidth;
        if (maxScroll <= 0) return;
        pos += 0.6;
        if (pos >= maxScroll) pos = 0;
        track.scrollLeft = pos;
        raf = requestAnimationFrame(step);
    }
    raf = requestAnimationFrame(step);

    track.addEventListener('pointerenter', () => cancelAnimationFrame(raf));
    track.addEventListener('pointerleave', () => { raf = requestAnimationFrame(step); });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
