<?php
require_once 'includes/db.php';

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS site_settings (
        id INT AUTO_INCREMENT PRIMARY KEY,
        site_name VARCHAR(255) DEFAULT 'Our Store'
    )");

    $stmt_check_site = $pdo->query("SELECT COUNT(*) FROM site_settings");
    if ($stmt_check_site && $stmt_check_site->fetchColumn() == 0) {
        $pdo->exec("INSERT INTO site_settings (site_name) VALUES ('Our Store')");
    }
} catch (Exception $e) {
    // Ignore table creation errors
}

$site_data = [];
try {
    $stmt_site = $pdo->query("SELECT site_name FROM site_settings LIMIT 1");
    if ($stmt_site) {
        $site_data = $stmt_site->fetch(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {}

$page_title = $site_data['site_name'] ?? 'Home';

require_once 'includes/header.php';

$sliders = [];
try {
    $stmt_sliders = $pdo->query("SELECT * FROM sliders WHERE status = 'active' ORDER BY id DESC");
    if ($stmt_sliders) {
        $sliders = $stmt_sliders->fetchAll();
    }
} catch (Exception $e) {}

$categories = [];
try {
    $stmt_cats = $pdo->query("SELECT * FROM categories ORDER BY id DESC");
    if ($stmt_cats) {
        $categories = $stmt_cats->fetchAll();
    }
} catch (Exception $e) {}

// Currency Glitch Protection & Setup
$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '৳';
if (is_numeric($currency)) {
    $currency = '৳';
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" />

<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&family=Noto+Serif+Bengali:wght@300;400;500;600;700&display=swap');

    body {
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-color: #f8fafc;
        margin: 0;
        padding: 0;
    }
    
    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px; 
        box-sizing: border-box;
    }

    h1, h2, h3, .section-title, .product-title {
        font-family: 'Roboto', 'Noto Serif Bengali', sans-serif !important;
    }
    
    .category-box, .product-card, .info-card {
        box-shadow: none !important;
        border: 1px solid #e2e8f0 !important;
        border-radius: 8px !important;
        transition: all 0.3s ease-in-out !important;
        background: #ffffff !important;
    }
    
    .product-card {
        position: relative !important;
        display: flex;
        flex-direction: column;
        padding: 12px;
        text-decoration: none;
        overflow: hidden;
        height: auto;
    }
    
    .category-box:hover, .product-card:hover, .info-card:hover {
        transform: translateY(-2px) !important;
        border-color: #94a3b8 !important;
        background: #f8fafc !important;
    }
    
    .btn-buy {
        border-radius: 4px !important;
        box-shadow: none !important;
        transition: background 0.3s ease, color 0.3s ease !important;
        border: 1px solid transparent !important;
        background: #00059E !important;
        color: #ffffff !important;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        text-decoration: none;
        padding: 10px;
        margin-top: auto;
        font-weight: 400;
        font-family: 'Roboto', sans-serif !important;
    }
    
    .btn-buy:hover {
        background: #00037a !important;
        color: #ffffff !important;
    }
    
    .view-more {
        transition: opacity 0.3s ease !important;
        color: #ffffff !important;
        background: #00059E !important;
        padding: 6px 14px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        gap: 5px;
        font-size: 0.85rem;
        text-decoration: none;
        font-weight: 600;
        font-family: 'Roboto', sans-serif !important;
    }
    
    .view-more:hover {
        opacity: 0.8 !important;
        background: #00037a !important;
    }

    .product-img {
        width: calc(100% + 24px);
        aspect-ratio: 1 / 1;
        height: auto !important;
        object-fit: cover !important; 
        background-color: #f1f5f9; 
        border-bottom: 1px solid #f1f5f9 !important;
        border-radius: 0 !important;
        transition: opacity 0.3s ease !important;
        margin: -12px -12px 10px -12px;
        padding: 0;
        box-sizing: border-box;
    }
    
    .product-card:hover .product-img {
        opacity: 0.9 !important;
    }

    .product-title {
        font-size: 1.1rem;
        color: #0f172a;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        font-weight: 700;
    }

    .product-price {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        font-family: 'Roboto', sans-serif !important;
    }

    .old-price {
        font-size: 0.8rem;
        color: #94a3b8;
        text-decoration: line-through;
        font-weight: 600;
    }

    .new-price {
        font-size: 1.15rem;
        font-weight: 800;
        color: #00059E;
    }
    
    .sale-badge {
        position: absolute !important;
        top: 10px !important;
        right: 10px !important;
        border-radius: 50% !important;
        box-shadow: none !important;
        background: #84cc16 !important;
        color: #fff !important;
        width: 40px !important;
        height: 40px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        font-size: 0.75rem !important;
        font-weight: 800 !important;
        z-index: 2 !important;
        font-family: 'Roboto', sans-serif !important;
    }
    
    .section-title {
        color: #00059E !important;
        font-size: 1.4rem;
        margin: 0;
        font-weight: 700;
    }

    .category-wrapper {
        display: flex;
        gap: 15px;
        overflow-x: auto;
        padding-bottom: 15px;
        margin-bottom: 25px;
        scrollbar-width: none;
        -ms-overflow-style: none;
        width: 100%;
    }
    .category-wrapper::-webkit-scrollbar { display: none; }
    
    .category-box {
        min-width: 100px;
        padding: 15px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
        text-decoration: none;
        flex-shrink: 0;
    }
    
    .category-icon { width: 45px; height: 45px; object-fit: contain; }
    .category-name { font-size: 0.85rem; font-weight: 600; color: #0f172a; white-space: nowrap; font-family: 'Roboto', sans-serif !important; }

    .product-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        margin-bottom: 30px;
    }
    
    @media (min-width: 768px) {
        .product-grid { grid-template-columns: repeat(3, 1fr); gap: 20px; }
    }
    
    @media (min-width: 1024px) {
        .product-grid { grid-template-columns: repeat(4, 1fr); }
    }

    .info-cards-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 15px;
        margin-bottom: 30px;
    }
    
    @media (min-width: 768px) {
        .info-cards-grid { grid-template-columns: repeat(3, 1fr); gap: 20px; }
    }
    
    .info-card { padding: 25px 15px; text-align: center; }
    .info-title { font-size: 1.25rem; color: #0f172a; margin: 15px 0 5px; font-weight: 700; }
    .info-desc { font-size: 0.9rem; color: #64748b; margin: 0; font-family: 'Roboto', sans-serif !important; }

    .swiper-slide img {
        width: 100%;
        height: auto;
        aspect-ratio: 21/9;
        object-fit: cover;
    }

    .bannerSwiper {
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid #e2e8f0;
        margin-bottom: 25px;
        background: #fff;
        width: 100%;
    }
</style>

<div class="container" style="margin-top: 15px; margin-bottom: 80px;">

    <div class="swiper bannerSwiper">
        <div class="swiper-wrapper">
            <?php if(count($sliders) > 0): ?>
                <?php foreach($sliders as $slider): ?>
                    <div class="swiper-slide">
                        <a href="<?php echo htmlspecialchars($slider['link']); ?>">
                            <img src="<?php echo get_image_url('sliders', $slider['image']); ?>" alt="Offer Banner" style="width: 100%; display: block;">
                        </a>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="swiper-slide" style="background: #00059E; color: white; text-align: center; padding: 60px 20px;">
                    <h2 style="margin:0 0 10px; font-weight: 700;">Welcome to <?php echo htmlspecialchars($site_data['site_name'] ?? 'Our Store'); ?></h2>
                    <p style="margin:0; font-family: 'Roboto', sans-serif;">Premium Digital Products at Best Price</p>
                </div>
            <?php endif; ?>
        </div>
        <div class="swiper-pagination"></div>
    </div>

    <div class="category-wrapper">
        <?php foreach($categories as $cat): ?>
            <?php
            $cat_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $cat['name'])));
            ?>
            <a href="/products/category/<?php echo urlencode($cat_slug); ?>" class="category-box">
                <img src="<?php echo get_image_url('categories', $cat['icon']); ?>" alt="<?php echo htmlspecialchars($cat['name']); ?>" class="category-icon">
                <div class="category-name"><?php echo htmlspecialchars($cat['name']); ?></div>
            </a>
        <?php endforeach; ?>
        
        <?php if(count($categories) == 0): ?>
            <p style="color: #94a3b8; width: 100%; text-align: center; font-family: 'Roboto', sans-serif;">No categories added yet.</p>
        <?php endif; ?>
    </div>

    <?php 
    foreach($categories as $cat): 
        $cat_id = $cat['id'];
        $cat_name = $cat['name'];
        $cat_slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $cat_name)));
        $products = [];
        try {
            $stmt_prods = $pdo->prepare("SELECT * FROM products WHERE category_id = ? AND status = 'active' ORDER BY id DESC LIMIT 8");
            $stmt_prods->execute([$cat_id]);
            if ($stmt_prods) {
                $products = $stmt_prods->fetchAll();
            }
        } catch (Exception $e) {}
        
        if(count($products) > 0):
    ?>
    
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <h2 class="section-title"><?php echo htmlspecialchars($cat['name']); ?></h2>
        <a href="/products/category/<?php echo urlencode($cat_slug); ?>" class="view-more">
            View More 
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" /></svg>
        </a>
    </div>

    <div class="product-grid">
        <?php foreach($products as $prod): 
            $product_url = "/product/" . urlencode($cat_slug) . "/" . urlencode($prod['slug']);
        ?>
            <div class="product-card">
                
                <?php if($prod['old_price'] > 0 && $prod['old_price'] > $prod['price']): ?>
                    <?php $discount_pct = round((($prod['old_price'] - $prod['price']) / $prod['old_price']) * 100); ?>
                    <span class="sale-badge">-<?php echo $discount_pct; ?>%</span>
                <?php endif; ?>
                
                <img src="<?php echo get_image_url('products/images', $prod['main_image']); ?>" alt="Product" class="product-img" loading="lazy">
                
                <div class="product-title"><?php echo htmlspecialchars($prod['title']); ?></div>
                
                <div class="product-price">
                    <?php if($prod['old_price'] > 0 && $prod['old_price'] > $prod['price']): ?>
                        <span class="old-price"><?php echo $currency . number_format($prod['old_price'], 2); ?></span>
                    <?php endif; ?>
                    <span class="new-price"><?php echo $currency . number_format($prod['price'], 2); ?></span>
                </div>
                
                <a href="<?php echo $product_url; ?>" class="btn-buy">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                    Buy Now
                </a>
            </div>
        <?php endforeach; ?>
    </div>
    
    <?php endif; endforeach; ?>

    <div class="info-cards-grid">
        <div class="info-card">
            <div style="margin-bottom: 15px;">
                <svg width="45" height="45" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="margin: 0 auto; display: block; color: #00059E;"><path stroke-linecap="round" stroke-linejoin="round" d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" /></svg>
            </div>
            <h3 class="info-title">Fast Delivery</h3>
            <p class="info-desc">Instant access to your digital files.</p>
        </div>
        <div class="info-card">
            <div style="margin-bottom: 15px;">
                <svg width="45" height="45" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="margin: 0 auto; display: block; color: #00059E;"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" /></svg>
            </div>
            <h3 class="info-title">Secure Checkout</h3>
            <p class="info-desc">100% safe and secure payment system.</p>
        </div>
        <div class="info-card">
            <div style="margin-bottom: 15px;">
                <svg width="45" height="45" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" style="margin: 0 auto; display: block; color: #00059E;"><path stroke-linecap="round" stroke-linejoin="round" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" /></svg>
            </div>
            <h3 class="info-title">100% Satisfaction</h3>
            <p class="info-desc">Premium quality code and support.</p>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        if(document.querySelector('.bannerSwiper')) {
            var bannerSwiper = new Swiper(".bannerSwiper", {
                loop: true,
                autoplay: {
                    delay: 3500,
                    disableOnInteraction: false,
                },
                pagination: {
                    el: ".swiper-pagination",
                    clickable: true,
                },
                autoHeight: true
            });
        }
    });
</script>

<?php require_once 'includes/footer.php'; ?>
<?php require_once 'includes/mobile-nav.php'; ?>
