<?php
/**
 * Starter 2026 — Home Page (Premium Storefront)
 * Distinctly modern design: asymmetric layouts, glassmorphism, rich animations
 * CodeIgniter 3.1.9
 */
$currency = $store_setting['currency_sign'] ?? '$';
$slider_raw = !empty($store_setting['homepage_slider']) ? $store_setting['homepage_slider'] : '[]';
$slider = is_array($slider_raw) ? $slider_raw : json_decode($slider_raw, true);
if (!is_array($slider)) $slider = [];

$home_categories = !empty($category) ? $category : (!empty($category_tree) ? $category_tree : []);

// Load products directly
$db =& get_instance();
$_products = $db->db->query("
    SELECT p.*
    FROM product p
    WHERE p.is_campaign_product = 0 AND p.product_status = 1 AND p.on_store = 1
    GROUP BY p.product_id
    ORDER BY p.product_id DESC
    LIMIT 8
")->result_array();

// Best sellers (by sales count)
$_best_sellers = $db->db->query("
    SELECT p.*
    FROM product p
    WHERE p.is_campaign_product = 0 AND p.product_status = 1 AND p.on_store = 1 AND p.product_sales_count > 0
    GROUP BY p.product_id
    ORDER BY p.product_sales_count DESC
    LIMIT 4
")->result_array();

$store_name = $store_setting['name'] ?? 'Store';
?>

<!-- ═══════════════════════════════════════════════════════════════
     SECTION 1 — HERO (Asymmetric Split with Animated Gradient)
     ═══════════════════════════════════════════════════════════════ -->
<section class="s26-hero s26-hero--home" style="padding:0;background:none;overflow:visible;">
    <div class="s26-hero__canvas">
        <!-- Animated gradient background -->
        <div class="s26-hero__gradient"></div>
        <!-- Floating geometric shapes -->
        <div class="s26-hero__shape s26-hero__shape--1"></div>
        <div class="s26-hero__shape s26-hero__shape--2"></div>
        <div class="s26-hero__shape s26-hero__shape--3"></div>

        <div class="container position-relative" style="z-index:5;">
            <div class="row align-items-center" style="min-height:clamp(520px, 75vh, 700px);">
                <!-- Left: Text Content -->
                <div class="col-lg-6 col-xl-5">
                    <div class="s26-hero__content">
                        <div class="s26-hero__tag">
                            <span class="s26-hero__tag-dot"></span>
                            <?= __('store.new_collection') ?? 'New Collection' ?>
                        </div>

                        <?php if (!empty($slider) && isset($slider[0])): ?>
                            <?php
                                $slide = $slider[0];
                                $txt_color = !empty($slide['slider_text_color']) ? $slide['slider_text_color'] : '#ffffff';
                            ?>
                            <h1 class="s26-hero__title" style="color:<?= $txt_color ?>">
                                <?= htmlspecialchars($slide['title'] ?? (__('store.welcome_to_store') ?? 'Discover What\'s Next')) ?>
                            </h1>
                            <?php if (!empty($slide['sub_title'])): ?>
                            <p class="s26-hero__subtitle" style="color:<?= $txt_color ?>;opacity:0.85;">
                                <?= htmlspecialchars($slide['sub_title']) ?>
                            </p>
                            <?php endif; ?>
                            <?php if (!empty($slide['content'])): ?>
                            <p class="s26-hero__desc" style="color:<?= $txt_color ?>;opacity:0.7;">
                                <?= htmlspecialchars($slide['content']) ?>
                            </p>
                            <?php endif; ?>
                            <div class="s26-hero__actions">
                                <?php if (!empty($slide['button_text'])): ?>
                                <a href="<?= $slide['button_link'] ?? base_url('store/category') ?>"
                                   class="s26-btn-hero-primary"
                                   style="<?= !empty($slide['button_bg_color']) ? 'background:'.$slide['button_bg_color'].';' : '' ?><?= !empty($slide['button_text_color']) ? 'color:'.$slide['button_text_color'].';' : '' ?>">
                                    <?= htmlspecialchars($slide['button_text']) ?>
                                    <i class="fas fa-arrow-right"></i>
                                </a>
                                <?php else: ?>
                                <a href="<?= base_url('store/category') ?>" class="s26-btn-hero-primary">
                                    <?= __('store.shop_now') ?? 'Shop Now' ?>
                                    <i class="fas fa-arrow-right"></i>
                                </a>
                                <?php endif; ?>
                                <a href="#s26-featured" class="s26-btn-hero-ghost">
                                    <?= __('store.explore') ?? 'Explore' ?>
                                    <i class="fas fa-chevron-down"></i>
                                </a>
                            </div>
                        <?php else: ?>
                            <h1 class="s26-hero__title"><?= __('store.welcome_to_store') ?? 'Discover What\'s Next' ?></h1>
                            <p class="s26-hero__subtitle"><?= __('store.curated_collection_desc') ?? 'Curated products, unbeatable prices, delivered with care.' ?></p>
                            <div class="s26-hero__actions">
                                <a href="<?= base_url('store/category') ?>" class="s26-btn-hero-primary">
                                    <?= __('store.shop_now') ?? 'Shop Now' ?>
                                    <i class="fas fa-arrow-right"></i>
                                </a>
                                <a href="#s26-featured" class="s26-btn-hero-ghost">
                                    <?= __('store.explore') ?? 'Explore' ?>
                                    <i class="fas fa-chevron-down"></i>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Right: Hero Visual -->
                <div class="col-lg-6 col-xl-7 d-none d-lg-block">
                    <div class="s26-hero__visual">
                        <?php if (!empty($slider) && !empty($slider[0]['slider_background_image'])): ?>
                        <div class="s26-hero__image-frame">
                            <img src="<?= base_url('assets/images/site/' . $slider[0]['slider_background_image']) ?>"
                                 alt="<?= htmlspecialchars($store_name) ?>"
                                 class="s26-hero__image" loading="eager">
                        </div>
                        <?php else: ?>
                        <!-- Decorative product collage when no slider image -->
                        <div class="s26-hero__collage">
                            <?php
                            $hero_products = array_slice($_products, 0, 3);
                            foreach ($hero_products as $hi => $hp):
                                $himg = !empty($hp['product_featured_image'])
                                    ? base_url('assets/images/product/upload/thumb/' . $hp['product_featured_image'])
                                    : base_url('assets/store/default/img/pr-img.png');
                            ?>
                            <div class="s26-hero__collage-item s26-hero__collage-item--<?= $hi + 1 ?>">
                                <img src="<?= $himg ?>" alt="" loading="eager">
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>

                        <!-- Floating stat badges -->
                        <div class="s26-hero__float-badge s26-hero__float-badge--top">
                            <i class="fas fa-fire"></i>
                            <span><?= count($_products) ?>+ <?= __('store.products') ?? 'Products' ?></span>
                        </div>
                        <div class="s26-hero__float-badge s26-hero__float-badge--bottom">
                            <i class="fas fa-star"></i>
                            <span><?= __('store.top_rated') ?? 'Top Rated' ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>


<!-- ═══════════════════════════════════════════════════════════════
     SECTION 2 — FEATURES BAR (Glassmorphism Floating Strip)
     ═══════════════════════════════════════════════════════════════ -->
<div class="container" style="margin-top:-48px;position:relative;z-index:10;">
    <div class="s26-features-bar s26-features-bar--home">
        <div class="row g-0">
            <div class="col-6 col-md-3">
                <div class="s26-feature-item s26-feature-item--home">
                    <div class="s26-feature-icon-ring">
                        <i class="fas fa-truck"></i>
                    </div>
                    <div>
                        <h6><?= __('store.free_shipping') ?? 'Free Shipping' ?></h6>
                        <p><?= __('store.on_orders_over_50') ?? 'On orders over $50' ?></p>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="s26-feature-item s26-feature-item--home">
                    <div class="s26-feature-icon-ring">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div>
                        <h6><?= __('store.secure_payment') ?? 'Secure Payment' ?></h6>
                        <p><?= __('store.100_protected') ?? '100% protected' ?></p>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="s26-feature-item s26-feature-item--home">
                    <div class="s26-feature-icon-ring">
                        <i class="fas fa-undo"></i>
                    </div>
                    <div>
                        <h6><?= __('store.easy_returns') ?? 'Easy Returns' ?></h6>
                        <p><?= __('store.30_day_policy') ?? '30-day return policy' ?></p>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="s26-feature-item s26-feature-item--home">
                    <div class="s26-feature-icon-ring">
                        <i class="fas fa-headset"></i>
                    </div>
                    <div>
                        <h6><?= __('store.247_support') ?? '24/7 Support' ?></h6>
                        <p><?= __('store.always_here') ?? 'Always here to help' ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<!-- ═══════════════════════════════════════════════════════════════
     SECTION 3 — CATEGORIES (Horizontal Scroll Pill Cards)
     ═══════════════════════════════════════════════════════════════ -->
<?php if (!empty($home_categories)): ?>
<section class="s26-section s26-categories-section">
    <div class="container">
        <div class="s26-section-header">
            <div>
                <p class="s26-section-eyebrow"><?= __('store.browse_by') ?? 'Browse By' ?></p>
                <h2 class="s26-section-title"><?= __('store.categories') ?? 'Categories' ?></h2>
            </div>
            <a href="<?= base_url('store/category') ?>" class="s26-link-arrow">
                <?= __('store.all_categories') ?? 'All Categories' ?>
                <i class="fas fa-arrow-right"></i>
            </a>
        </div>

        <div class="s26-category-scroll">
            <?php
            $cat_icons = ['fas fa-tshirt','fas fa-laptop','fas fa-couch','fas fa-football-ball','fas fa-gem','fas fa-book','fas fa-gamepad','fas fa-utensils','fas fa-camera','fas fa-paint-brush'];
            $cat_gradients = [
                'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
                'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
                'linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%)',
                'linear-gradient(135deg, #fccb90 0%, #d57eeb 100%)',
                'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)',
                'linear-gradient(135deg, #f5576c 0%, #ff6a88 100%)',
                'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            ];
            $ci = 0;
            foreach ($home_categories as $cat):
            ?>
            <a href="<?= base_url('store/category/' . ($cat['slug'] ?? $cat['id'] ?? '')) ?>" class="s26-category-card s26-category-card--pill s26-reveal">
                <div class="s26-category-card__icon" style="background:<?= $cat_gradients[$ci % count($cat_gradients)] ?>">
                    <?php if (!empty($cat['image'])): ?>
                        <img src="<?= base_url('assets/images/product/upload/thumb/' . $cat['image']) ?>" alt="">
                    <?php else: ?>
                        <i class="<?= $cat_icons[$ci % count($cat_icons)] ?>"></i>
                    <?php endif; ?>
                </div>
                <span class="s26-category-card__name"><?= htmlspecialchars($cat['name']) ?></span>
                <span class="s26-category-card__arrow"><i class="fas fa-chevron-right"></i></span>
            </a>
            <?php $ci++; endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ═══════════════════════════════════════════════════════════════
     SECTION 4 — FEATURED PRODUCTS (Staggered Grid)
     ═══════════════════════════════════════════════════════════════ -->
<?php if (!empty($_products)): ?>
<section class="s26-section" id="s26-featured">
    <div class="container">
        <div class="s26-section-header">
            <div>
                <p class="s26-section-eyebrow"><?= __('store.hand_picked_for_you') ?? 'Hand-Picked For You' ?></p>
                <h2 class="s26-section-title"><?= __('store.featured_products') ?? 'Featured Products' ?></h2>
            </div>
            <a href="<?= base_url('store/category') ?>" class="s26-btn-outline s26-btn--sm">
                <?= __('admin.view_all') ?? 'View All' ?>
                <i class="fas fa-arrow-right"></i>
            </a>
        </div>

        <div class="row g-3 g-lg-4">
            <?php foreach ($_products as $pi => $p):
                $img = !empty($p['product_featured_image'])
                    ? base_url('assets/images/product/upload/thumb/' . $p['product_featured_image'])
                    : base_url('assets/store/default/img/pr-img.png');
                $qty = (int)($p['product_quantity'] ?? 0);
                $url = base_url('store/product/' . $p['product_slug']);
                $is_oos = ($qty == 0 && isset($p['product_quantity']) && $p['product_quantity'] !== '');

                // Rating
                $avg = 0; $rev_cnt = 0;
                $rev_data = $db->db->query("SELECT AVG(rating_number) as avg_star, COUNT(*) as cnt FROM rating WHERE products_id = ? AND rating_status = 1", [$p['product_id']])->row();
                if ($rev_data && $rev_data->cnt > 0) { $avg = round($rev_data->avg_star, 1); $rev_cnt = (int)$rev_data->cnt; }
            ?>
            <div class="col-6 col-md-4 col-lg-3 s26-reveal">
                <div class="s26-product-card s26-product-card--home">
                    <!-- Image -->
                    <div class="card-img-wrapper">
                        <a href="<?= $url ?>">
                            <img src="<?= $img ?>" alt="<?= htmlspecialchars($p['product_name']) ?>" loading="lazy">
                        </a>

                        <?php if ($is_oos): ?>
                        <span class="s26-badge s26-badge-oos"><?= __('store.out_of_stock') ?? 'Out of Stock' ?></span>
                        <?php endif; ?>

                        <!-- Quick actions overlay -->
                        <div class="quick-actions">
                            <button class="quick-view-btn" data-product-id="<?= $p['product_id'] ?>">
                                <i class="fas fa-eye"></i>
                                <span class="d-none d-md-inline"><?= __('store.quick_view') ?? 'Quick View' ?></span>
                            </button>
                        </div>
                    </div>

                    <!-- Details -->
                    <div class="card-body">
                        <?php if ($avg > 0): ?>
                        <div class="s26-stars">
                            <?php for ($s = 1; $s <= 5; $s++): ?>
                                <i class="<?= $s <= round($avg) ? 'fas' : 'far' ?> fa-star"></i>
                            <?php endfor; ?>
                            <small class="text-muted ms-1">(<?= $rev_cnt ?>)</small>
                        </div>
                        <?php endif; ?>

                        <a href="<?= $url ?>" class="product-title"><?= htmlspecialchars($p['product_name']) ?></a>

                        <div class="product-price"><?= $currency ?><?= number_format((float)$p['product_price'], 2) ?></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- ═══════════════════════════════════════════════════════════════
     SECTION 4.5 — BEST SELLERS MARQUEE (if available)
     ═══════════════════════════════════════════════════════════════ -->
<?php if (!empty($_best_sellers)): ?>
<section class="s26-section s26-bestsellers-section">
    <div class="container">
        <div class="s26-section-header">
            <div>
                <p class="s26-section-eyebrow"><i class="fas fa-fire" style="color:var(--s26-danger);"></i> <?= __('store.trending_now') ?? 'Trending Now' ?></p>
                <h2 class="s26-section-title"><?= __('store.best_sellers') ?? 'Best Sellers' ?></h2>
            </div>
        </div>

        <div class="s26-bestseller-strip">
            <?php foreach ($_best_sellers as $bp):
                $bimg = !empty($bp['product_featured_image'])
                    ? base_url('assets/images/product/upload/thumb/' . $bp['product_featured_image'])
                    : base_url('assets/store/default/img/pr-img.png');
                $burl = base_url('store/product/' . $bp['product_slug']);

                $bavg = 0;
                $brev = $db->db->query("SELECT AVG(rating_number) as avg_star, COUNT(*) as cnt FROM rating WHERE products_id = ? AND rating_status = 1", [$bp['product_id']])->row();
                if ($brev && $brev->cnt > 0) { $bavg = round($brev->avg_star, 1); }
            ?>
            <a href="<?= $burl ?>" class="s26-bestseller-card s26-reveal">
                <div class="s26-bestseller-card__img">
                    <img src="<?= $bimg ?>" alt="<?= htmlspecialchars($bp['product_name']) ?>" loading="lazy">
                </div>
                <div class="s26-bestseller-card__info">
                    <h4><?= htmlspecialchars($bp['product_name']) ?></h4>
                    <?php if ($bavg > 0): ?>
                    <div class="s26-stars" style="font-size:11px;">
                        <?php for ($s = 1; $s <= 5; $s++): ?>
                            <i class="<?= $s <= round($bavg) ? 'fas' : 'far' ?> fa-star"></i>
                        <?php endfor; ?>
                    </div>
                    <?php endif; ?>
                    <span class="s26-bestseller-card__price"><?= $currency ?><?= number_format((float)$bp['product_price'], 2) ?></span>
                </div>
                <span class="s26-bestseller-card__badge"><?= (int)$bp['product_sales_count'] ?> <?= __('store.sold') ?? 'sold' ?></span>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>


<!-- Newsletter section removed — no backend functionality -->


<!-- ═══════════════════════════════════════════════════════════════
     HOME PAGE ANIMATIONS (scroll reveal re-init)
     ═══════════════════════════════════════════════════════════════ -->
<script>
(function() {
    // Re-initialize intersection observer for home page reveal elements
    if ('IntersectionObserver' in window) {
        var homeObserver = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry, idx) {
                if (entry.isIntersecting) {
                    // Stagger the animation
                    var delay = Math.min(idx * 80, 400);
                    setTimeout(function() {
                        entry.target.classList.add('visible');
                    }, delay);
                    homeObserver.unobserve(entry.target);
                }
            });
        }, { threshold: 0.08, rootMargin: '0px 0px -30px 0px' });

        document.querySelectorAll('.s26-reveal').forEach(function(el) {
            homeObserver.observe(el);
        });
    } else {
        // Fallback: show all immediately
        document.querySelectorAll('.s26-reveal').forEach(function(el) {
            el.classList.add('visible');
        });
    }

    // Smooth scroll for "Explore" button
    document.querySelectorAll('a[href="#s26-featured"]').forEach(function(a) {
        a.addEventListener('click', function(e) {
            e.preventDefault();
            var target = document.getElementById('s26-featured');
            if (target) {
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    });
})();
</script>
