<?php
$page_title = 'Home';
$page_description = 'Buy Local Lowveld — supporting local businesses across the Lowveld region.';

require_once __DIR__ . '/includes/db.php';

// Load data from DB (falls back to arrays on fresh installs)
if (db_is_ready() && (int)db_value('SELECT COUNT(*) FROM listings') > 0) {
    $categories = db_all('SELECT slug, name, icon, image_path FROM categories ORDER BY sort_order, name LIMIT 100');
    $db_rows    = db_all('SELECT * FROM listings WHERE published = 1');
    $listings   = array_map(fn($l) => [
        'id'          => (int)$l['id'],
        'slug'        => $l['slug'],
        'name'        => $l['name'],
        'category'    => $l['category_slug'],
        'tier'        => $l['tier'],
        'featured'    => (int)$l['featured'] === 1,
        'description' => $l['description'],
        'address'     => $l['address'],
        'logo_path'   => $l['logo_path'] ?? null,
    ], $db_rows);
} else {
    $categories = require __DIR__ . '/data/categories.php';
    $listings   = require __DIR__ . '/data/listings.php';
}

// Curated sets for each section
$diamond_members  = array_values(array_filter($listings, fn($l) => $l['tier'] === 'Diamond'));
$platinum_members = array_values(array_filter($listings, fn($l) => $l['tier'] === 'Platinum'));
// Top 3 listings — based on real pageviews in the last 30 days
// Falls back to featured listings if metrics table is empty or doesn't exist
$top_3 = [];
try {
    $top_rows = db_all(
        "SELECT l.*, COUNT(pv.id) AS view_count
           FROM listings l
           INNER JOIN metrics_pageviews pv
                   ON pv.listing_id = l.id
                  AND pv.viewed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
          WHERE l.published = 1
          GROUP BY l.id
          ORDER BY view_count DESC, l.name
          LIMIT 3"
    );
    foreach ($top_rows as $r) {
        $top_3[] = [
            'id'          => (int)$r['id'],
            'slug'        => $r['slug'],
            'name'        => $r['name'],
            'tier'        => $r['tier'],
            'description' => $r['description'],
            'address'     => $r['address'],
            'logo_path'   => $r['logo_path'] ?? null,
            'view_count'  => (int)$r['view_count'],
        ];
    }
} catch (Throwable $e) { /* metrics table not ready */ }

// If no view data yet, fall back to featured listings
if (empty($top_3)) {
    $top_3 = array_slice(array_values(array_filter($listings, fn($l) => !empty($l['featured']))), 0, 3);
}

$featured_categories = array_slice($categories, 0, 4);

require 'includes/header.php';
?>

<!-- ═══════════════════════════════════════════
     HERO  (full-screen video + badge logo)
 ═══════════════════════════════════════════ -->
<section class="hero">
    <video autoplay muted loop playsinline poster="assets/img/hero-poster.jpg">
        <source src="assets/video/buylocal.mp4" type="video/mp4">
    </video>

    <div class="hero-content">
        <!-- Buy Local stamp -->
        <img src="assets/img/buylocal-stamp.png" alt="Buy Local Lowveld" class="hero-badge-img">

        <p class="hashtag">#LekkerLocalLowveld</p>

        <a href="become-member.php" class="btn btn-outline-light">Become a Member</a>

        <form class="hero-search" action="directory.php" method="get" role="search">
            <input type="search" name="q" placeholder="Search our Directory" aria-label="Search our directory">
            <button type="submit">Search</button>
        </form>
    </div>
</section>

<!-- ═══════════════════════════════════════════
     Green support-local strip
 ═══════════════════════════════════════════ -->
<section class="member-strip reveal">
    <p class="quote">
        By supporting local you <strong>encourage local entrepreneurship.</strong>
    </p>
</section>

<!-- ═══════════════════════════════════════════
     Diamond package members — auto-scroll marquee
 ═══════════════════════════════════════════ -->
<?php if (!empty($diamond_members)): ?>
<section class="member-carousel reveal">
    <div class="section-title">
        <h2>Diamond Package Members</h2>
        <p class="subtitle">Support our Diamond Package Members</p>
    </div>
    <div class="marquee" data-direction="left" style="--base-count: <?= count($diamond_members) ?>;">
        <div class="marquee-track">
            <?php
            // Ensure the track has enough tiles to always fill the screen.
            // Tile is ~215px wide including gap; widest viewport ~2000px → need at least 10 tiles visible.
            // We triple for loop seamlessness, so multiply up to reach min 24.
            $min_tiles = 24;
            $reps = max(3, (int)ceil($min_tiles / max(1, count($diamond_members))));
            $diamond_display = [];
            for ($i = 0; $i < $reps; $i++) $diamond_display = array_merge($diamond_display, $diamond_members);
            foreach ($diamond_display as $d):
            ?>
                <a href="directory-item.php?id=<?= $d['id'] ?>" class="member-tile">
                    <div class="tile-photo">
                        <?php if (!empty($d['logo_path'])): ?>
                            <img src="<?= htmlspecialchars($d['logo_path']) ?>" alt="<?= htmlspecialchars($d['name']) ?>">
                        <?php else: ?>
                            <div class="tile-initials">
                                <?= htmlspecialchars(strtoupper(mb_substr($d['name'], 0, 2))) ?>
                            </div>
                        <?php endif; ?>
                        <span class="tile-pin tile-Diamond">Diamond</span>
                    </div>
                    <div class="tile-name"><?= htmlspecialchars($d['name']) ?></div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ═══════════════════════════════════════════
     Platinum package members — auto-scroll marquee (reversed)
 ═══════════════════════════════════════════ -->
<?php if (!empty($platinum_members)): ?>
<section class="member-carousel reveal" style="padding-top:0;padding-bottom:4rem;">
    <div class="section-title">
        <h2>Platinum Package Members</h2>
        <p class="subtitle">Support our Platinum Package Members</p>
    </div>
    <div class="marquee" data-direction="right" style="--base-count: <?= count($platinum_members) ?>;">
        <div class="marquee-track">
            <?php
            $min_tiles = 24;
            $reps = max(3, (int)ceil($min_tiles / max(1, count($platinum_members))));
            $platinum_display = [];
            for ($i = 0; $i < $reps; $i++) $platinum_display = array_merge($platinum_display, $platinum_members);
            foreach ($platinum_display as $p):
            ?>
                <a href="directory-item.php?id=<?= $p['id'] ?>" class="member-tile">
                    <div class="tile-photo">
                        <?php if (!empty($p['logo_path'])): ?>
                            <img src="<?= htmlspecialchars($p['logo_path']) ?>" alt="<?= htmlspecialchars($p['name']) ?>">
                        <?php else: ?>
                            <div class="tile-initials">
                                <?= htmlspecialchars(strtoupper(mb_substr($p['name'], 0, 2))) ?>
                            </div>
                        <?php endif; ?>
                        <span class="tile-pin tile-Platinum">Platinum</span>
                    </div>
                    <div class="tile-name"><?= htmlspecialchars($p['name']) ?></div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ═══════════════════════════════════════════
     Two-column mission statement
 ═══════════════════════════════════════════ -->
<section class="two-col-intro reveal">
    <div class="container">
        <div class="grid grid-2">
            <div>
                <p class="quote">
                    "<strong>Buy Local</strong> Lowveld believes in creating a sustainable city
                    through the promotion and support of locally owned businesses."
                </p>
                <a href="learn-more.php" class="btn btn-outline">Learn More</a>
            </div>
            <div class="small-body">
                <p>
                    We aim to <strong>STIMULATE</strong> the Lowveld economy by encouraging
                    shoppers to support and spend their money <strong>LOCALLY</strong>.
                </p>
                <p>
                    Our <strong>FOCUS</strong> is on the people, businesses and families that
                    have built our community, created jobs and invested their time, resources
                    and love into creating a better region <strong>FOR US ALL</strong>.
                </p>
                <p>
                    We stand for excellence and aim to spread the spirit of
                    <strong>UBUNTU IN THE LOWVELD COMMUNITY</strong>.
                </p>
            </div>
        </div>
    </div>
</section>

<!-- ═══════════════════════════════════════════
     Full-width members photo
 ═══════════════════════════════════════════ -->
<div class="photo-banner reveal">
    <img src="assets/img/buylocal-members.webp" alt="Buy Local Lowveld members" loading="lazy">
</div>

<!-- ═══════════════════════════════════════════
     Our Directory (category tiles)
 ═══════════════════════════════════════════ -->
<section class="our-directory reveal">
    <div class="container">
        <h2>Our Directory</h2>
        <p class="subtitle">Find the best local businesses by category</p>

        <div class="category-grid">
            <?php foreach ($featured_categories as $cat):
                $img = !empty($cat['image_path']) ? $cat['image_path'] : null;
                $has_img = (bool)$img;
            ?>
                <a href="directory.php?cat=<?= htmlspecialchars($cat['slug']) ?>"
                   class="category-tile <?= $has_img ? 'has-img' : '' ?>"
                   <?= $has_img ? 'style="background-image: url(\''.htmlspecialchars($img).'\');"' : '' ?>>
                    <?php if (!$has_img): ?>
                        <span class="cat-name"><?= htmlspecialchars($cat['name']) ?></span>
                    <?php endif; ?>
                </a>
            <?php endforeach; ?>
        </div>

        <a href="directory.php" class="btn btn-outline">View Our Directory</a>
    </div>
</section>

<!-- ═══════════════════════════════════════════
     Top 3 local listings
 ═══════════════════════════════════════════ -->
<?php if (!empty($top_3)): ?>
<section class="top-listings reveal">
    <div class="container">
        <h2>Top 3 Local Listings</h2>
        <p class="subtitle">Top Performing Listings of the Month</p>

        <div class="top-listings-grid">
            <?php foreach ($top_3 as $l): ?>
                <a href="directory-item.php?id=<?= $l['id'] ?>" class="top-listing">
                    <div class="tl-box">
                        <?php if (!empty($l['logo_path'])): ?>
                            <img src="<?= htmlspecialchars($l['logo_path']) ?>"
                                 alt="<?= htmlspecialchars($l['name']) ?>">
                        <?php else: ?>
                            <span class="tl-initials">
                                <?= htmlspecialchars(strtoupper(mb_substr($l['name'], 0, 2))) ?>
                            </span>
                        <?php endif; ?>
                    </div>
                    <div class="name"><?= htmlspecialchars($l['name']) ?></div>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>

<!-- ═══════════════════════════════════════════
     Get In Touch CTA
 ═══════════════════════════════════════════ -->
<section class="cta-strip reveal">
    <div class="container">
        <div>
            <h2>Interested in finding out more?</h2>
            <p>
                We'd love to chat. Whether you're a Lowveld business thinking about joining,
                a shopper keen to support local, or a sponsor looking to back our work —
                get in touch and we'll come back to you within one business day.
            </p>
        </div>
        <div style="text-align:right;">
            <p style="font-size:1.05rem;margin:0 0 1rem;">
                I am interested in finding out more.<br>
                Please can someone get in touch with me.
            </p>
            <a href="contact.php" class="btn btn-outline-light">Get in Touch</a>
        </div>
    </div>
</section>

<script>
// Reveal-on-scroll using IntersectionObserver
(function () {
    if (!('IntersectionObserver' in window)) {
        // Fallback: just show everything
        document.querySelectorAll('.reveal').forEach(el => el.classList.add('visible'));
        return;
    }
    const io = new IntersectionObserver((entries) => {
        entries.forEach(e => {
            if (e.isIntersecting) {
                e.target.classList.add('visible');
                io.unobserve(e.target);
            }
        });
    }, { threshold: 0.12, rootMargin: '0px 0px -50px 0px' });
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
})();
</script>

<?php require 'includes/footer.php'; ?>