<?php
$page_title = 'Our Directory';
$page_description = 'Browse the Buy Local Lowveld member directory by category or search by name.';

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

// Prefer DB (Phase 2a); fall back to Phase 1 arrays when DB is empty.
if (db_is_ready() && (int)db_value('SELECT COUNT(*) FROM listings') > 0) {
    $categories = db_all('SELECT slug, name, icon, image_path, banner_path FROM categories ORDER BY sort_order, name');
    $db_rows    = db_all('SELECT * FROM listings WHERE published = 1 ORDER BY FIELD(tier,"Diamond","Platinum","Gold","Silver","Bronze"), name');

    // Pre-load categories per listing (many-to-many)
    $listing_cats_map = [];
    try {
        $all_lc = db_all(
            'SELECT lc.listing_id, lc.category_slug, lc.is_primary, c.name AS category_name
               FROM listing_categories lc
               LEFT JOIN categories c ON c.slug = lc.category_slug'
        );
        foreach ($all_lc as $lc) {
            $listing_cats_map[(int)$lc['listing_id']][] = [
                'slug'       => $lc['category_slug'],
                'name'       => $lc['category_name'] ?? $lc['category_slug'],
                'is_primary' => (int)$lc['is_primary'] === 1,
            ];
        }
    } catch (Throwable $e) { /* junction not migrated yet */ }

    $listings = array_map(function ($l) use ($listing_cats_map) {
        $id = (int)$l['id'];
        $cats = $listing_cats_map[$id] ?? [];
        // Fallback: single category from legacy column
        if (empty($cats) && !empty($l['category_slug'])) {
            $cats = [['slug' => $l['category_slug'], 'name' => $l['category_slug'], 'is_primary' => true]];
        }
        return [
            'id'          => $id,
            'slug'        => $l['slug'],
            'name'        => $l['name'],
            'category'    => $l['category_slug'],
            'categories'  => $cats,
            'tier'        => $l['tier'],
            'featured'    => (int)$l['featured'] === 1,
            'description' => $l['description'],
            'tagline'     => $l['tagline'] ?? '',
            'phone'       => $l['phone'],
            'email'       => $l['email'],
            'website'     => $l['website'],
            'address'     => $l['address'],
            'logo_path'   => $l['logo_path']   ?? null,
            'banner_path' => $l['banner_path'] ?? null,
        ];
    }, $db_rows);
} else {
    $categories = require __DIR__ . '/data/categories.php';
    $listings   = require __DIR__ . '/data/listings.php';
}

$selected_cat = $_GET['cat'] ?? '';
$q            = trim($_GET['q'] ?? '');

// Build a quick lookup: slug -> full category record
$cat_lookup = [];
foreach ($categories as $c) { $cat_lookup[$c['slug']] = $c; }

// Apply filters
$filtered = $listings;
if ($selected_cat !== '') {
    $filtered = array_filter($filtered, function ($l) use ($selected_cat) {
        foreach ($l['categories'] ?? [] as $c) {
            if (($c['slug'] ?? '') === $selected_cat) return true;
        }
        return false;
    });
}
if ($q !== '') {
    $needle = mb_strtolower($q);
    $filtered = array_filter($filtered, function ($l) use ($needle) {
        return mb_strpos(mb_strtolower($l['name']), $needle) !== false
            || mb_strpos(mb_strtolower($l['description']), $needle) !== false;
    });
}
$filtered = array_values($filtered);

// Track the search if user actually filtered/searched
if ($q !== '' || $selected_cat !== '') {
    require_once __DIR__ . '/includes/metrics.php';
    metrics_track_search($q ?: null, $selected_cat ?: null, null, count($filtered));
}

require 'includes/header.php';
?>

<?php
// Pick which banner to show — per-category if selected + has banner, else default
$active_cat    = $selected_cat !== '' ? ($cat_lookup[$selected_cat] ?? null) : null;
$banner_img    = !empty($active_cat['banner_path']) ? $active_cat['banner_path'] : 'assets/img/directory-banner.webp';
$banner_title  = $active_cat ? $active_cat['name'] : 'Our Directory';
$banner_sub    = $active_cat
    ? (count($filtered) . ' listing' . (count($filtered)===1?'':'s') . ' in this category')
    : (count($listings) . ' local members across ' . count($categories) . ' categories');
?>
<section class="dir-banner" style="background-image: url('<?= htmlspecialchars($banner_img) ?>');">
    <div class="dir-banner-overlay">
        <div class="container">
            <h1><?= htmlspecialchars($banner_title) ?></h1>
            <p><?= htmlspecialchars($banner_sub) ?></p>

            <form class="dir-search" method="get" action="directory.php">
                <input type="search" name="q" value="<?= htmlspecialchars($q) ?>"
                       placeholder="Search our Directory..." aria-label="Search">
                <select name="cat" onchange="this.form.submit()" aria-label="Category">
                    <option value="">All categories</option>
                    <?php foreach ($categories as $c): ?>
                        <option value="<?= htmlspecialchars($c['slug']) ?>" <?= $selected_cat === $c['slug'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit">Search</button>
            </form>
        </div>
    </div>
</section>

<section class="section">
    <div class="container">

        <?php
        // Three possible states:
        //  1. No filter at all → show category grid (landing)
        //  2. Category selected OR search active → show listings
        $is_landing = ($selected_cat === '' && $q === '');
        ?>

        <?php if ($is_landing): ?>
            <!-- Landing: browse all categories -->
            <h2 class="text-center mb-3" style="text-transform:uppercase;letter-spacing:.15em;font-weight:300;font-size:1.4rem;">
                Browse by Category
            </h2>
            <p class="text-center muted" style="margin-bottom:3rem;">
                Choose a category to explore our <?= count($listings) ?> local members.
            </p>
            <div class="category-grid">
                <?php foreach ($categories as $c):
                    $img = !empty($c['image_path']) ? $c['image_path'] : null;
                    $has_img = (bool)$img;
                ?>
                    <a href="directory.php?cat=<?= htmlspecialchars($c['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($c['name']) ?></span>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </div>

        <?php else: ?>
            <!-- Filtered: showing listings -->
            <p class="muted" style="margin-bottom:2rem;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:1rem;">
                <span>
                    Showing <strong><?= count($filtered) ?></strong> result<?= count($filtered) === 1 ? '' : 's' ?>
                    <?php if ($selected_cat !== '' && isset($cat_lookup[$selected_cat])): ?>
                        in <strong><?= htmlspecialchars($cat_lookup[$selected_cat]['name']) ?></strong>
                    <?php endif; ?>
                    <?php if ($q !== ''): ?>
                        matching "<strong><?= htmlspecialchars($q) ?></strong>"
                    <?php endif; ?>
                </span>
                <a href="directory.php" class="btn btn-outline" style="font-size:.75rem;padding:.4rem 1rem;">← Back to all categories</a>
            </p>

            <?php if (empty($filtered)): ?>
                <div class="alert alert-info">
                    No listings match your filters. Try a different category, or <a href="directory.php">browse all categories</a>.
                </div>
            <?php else: ?>
                <div class="dir-grid">
                    <?php foreach ($filtered as $l):
                        $tier_class = 'tier-' . strtolower($l['tier']);
                        $hay = $l['name'] . ' ' . $l['description'];
                        foreach ($l['categories'] ?? [] as $c) $hay .= ' ' . ($c['name'] ?? '');
                        $banner = !empty($l['banner_path']) ? $l['banner_path'] : null;
                        $logo   = !empty($l['logo_path']) ? $l['logo_path'] : null;
                    ?>
                        <a href="directory-item.php?id=<?= $l['id'] ?>"
                           class="dir-card"
                           data-listing="<?= htmlspecialchars($hay) ?>">

                            <div class="dir-card-banner">
                                <div class="dir-card-banner-fallback">
                                    <?php if ($logo): ?>
                                        <img src="<?= htmlspecialchars($logo) ?>" alt="<?= htmlspecialchars($l['name']) ?>">
                                    <?php else: ?>
                                        <span class="dir-card-initials">
                                            <?= htmlspecialchars(strtoupper(mb_substr($l['name'], 0, 2))) ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <span class="tier-pin tier-<?= htmlspecialchars($l['tier']) ?>"><?= htmlspecialchars($l['tier']) ?></span>
                            </div>

                            <div class="dir-card-body">
                                <h3><?= htmlspecialchars($l['name']) ?></h3>
                                <?php if (!empty($l['tagline'])): ?>
                                    <p class="dir-card-tagline"><?= htmlspecialchars($l['tagline']) ?></p>
                                <?php endif; ?>

                                <ul class="dir-card-contact">
                                    <?php if (!empty($l['address'])): ?>
                                        <li>📍 <?= htmlspecialchars($l['address']) ?></li>
                                    <?php endif; ?>
                                    <?php if (!empty($l['phone'])): ?>
                                        <li>📞 <?= htmlspecialchars($l['phone']) ?></li>
                                    <?php endif; ?>
                                    <?php if (!empty($l['email'])): ?>
                                        <li>✉️ <?= htmlspecialchars($l['email']) ?></li>
                                    <?php endif; ?>
                                    <?php if (!empty($l['website'])): ?>
                                        <li>🌐 <?= htmlspecialchars(preg_replace('#^https?://#','',$l['website'])) ?></li>
                                    <?php endif; ?>
                                </ul>
                            </div>

                            <div class="dir-card-foot">
                                <?php foreach (($l['categories'] ?? []) as $c): ?>
                                    <span class="dir-card-cat-tag"><?= htmlspecialchars($c['name']) ?></span>
                                <?php endforeach; ?>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

    </div>
</section>

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