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

$id = (int)($_GET['id'] ?? 0);

// Prefer DB (Phase 2a); fall back to static arrays for safety.
if (db_is_ready() && (int)db_value('SELECT COUNT(*) FROM listings') > 0) {
    $row = db_row('SELECT * FROM listings WHERE id = :id AND published = 1', ['id' => $id]);
    if (!$row) { header('Location: directory.php'); exit; }

    // Load all categories this listing belongs to
    $listing_cats = [];
    try {
        $listing_cats = db_all(
            'SELECT lc.category_slug AS slug, c.name, lc.is_primary
               FROM listing_categories lc
               LEFT JOIN categories c ON c.slug = lc.category_slug
              WHERE lc.listing_id = :id',
            ['id' => $id]
        );
    } catch (Throwable $e) { /* junction not migrated */ }
    if (empty($listing_cats) && !empty($row['category_slug'])) {
        $listing_cats = [['slug' => $row['category_slug'], 'name' => $row['category_slug'], 'is_primary' => 1]];
    }

    $listing = [
        'id'          => (int)$row['id'],
        'slug'        => $row['slug'],
        'name'        => $row['name'],
        'category'    => $row['category_slug'],
        'categories'  => $listing_cats,
        'tier'        => $row['tier'],
        'description' => $row['description'],
        'tagline'     => $row['tagline'] ?? '',
        'phone'       => $row['phone'],
        'email'       => $row['email'],
        'website'     => $row['website'],
        'address'     => $row['address'],
        'logo_path'   => $row['logo_path']   ?? null,
        'banner_path' => $row['banner_path'] ?? null,
    ];
    $categories = db_all('SELECT slug, name FROM categories');
} else {
    $listings   = require __DIR__ . '/data/listings.php';
    $categories = require __DIR__ . '/data/categories.php';
    $listing = null;
    foreach ($listings as $l) { if ((int)$l['id'] === $id) { $listing = $l; break; } }
    if (!$listing) { header('Location: directory.php'); exit; }
    if (empty($listing['categories'])) $listing['categories'] = [];
}

$cat_lookup = [];
foreach ($categories as $c) { $cat_lookup[$c['slug']] = $c; }
$cat = $cat_lookup[$listing['category']] ?? null;

$page_title = $listing['name'];
$page_description = $listing['description'];

$tier_class = 'tier-' . strtolower($listing['tier']);
// Track this listing view (overrides the header's generic pageview tracker
// since we want to associate it with the specific listing_id)
require_once __DIR__ . '/includes/metrics.php';
metrics_track_listing_view((int)$listing['id']);

// Prevent the header include from double-counting this as a generic page view
$GLOBALS['__metrics_tracked'] = true;

require 'includes/header.php';
$banner = !empty($listing['banner_path']) ? $listing['banner_path'] : null;
$logo   = !empty($listing['logo_path'])   ? $listing['logo_path']   : null;
?>

<!-- ═══════════════════════════════════════════
     Listing hero (banner or logo fullscale)
 ═══════════════════════════════════════════ -->
<section class="li-hero" <?= $banner ? 'style="background-image:url(\''.htmlspecialchars($banner).'\');"' : '' ?>>
    <?php if (!$banner): ?>
        <div class="li-hero-fallback">
            <?php if ($logo): ?>
                <img src="<?= htmlspecialchars($logo) ?>" alt="<?= htmlspecialchars($listing['name']) ?>">
            <?php else: ?>
                <span class="li-hero-initials">
                    <?= htmlspecialchars(strtoupper(mb_substr($listing['name'], 0, 2))) ?>
                </span>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <div class="li-hero-shade"></div>
    <div class="container">
        <p class="li-hero-crumb"><a href="directory.php">← Back to directory</a></p>
        <span class="tier-pin tier-<?= htmlspecialchars($listing['tier']) ?> li-hero-tier">
            <?= htmlspecialchars($listing['tier']) ?> Member
        </span>
    </div>
</section>

<!-- ═══════════════════════════════════════════
     Header card — logo + name + categories
 ═══════════════════════════════════════════ -->
<section class="li-header">
    <div class="container">
        <div class="li-header-card">
            <?php if ($logo && $banner): ?>
                <!-- Banner + logo: show logo as a badge overlay -->
                <div class="li-header-logo">
                    <img src="<?= htmlspecialchars($logo) ?>" alt="">
                </div>
            <?php endif; ?>
            <div class="li-header-body">
                <h1><?= htmlspecialchars($listing['name']) ?></h1>
                <?php if (!empty($listing['tagline'])): ?>
                    <p class="li-tagline"><?= htmlspecialchars($listing['tagline']) ?></p>
                <?php endif; ?>
                <?php if (!empty($listing['categories'])): ?>
                    <div class="li-cat-tags">
                        <?php foreach ($listing['categories'] as $c): ?>
                            <a href="directory.php?cat=<?= htmlspecialchars($c['slug']) ?>" class="li-cat-tag">
                                <?= htmlspecialchars($c['name']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- ═══════════════════════════════════════════
     Main content: About + contact sidebar
 ═══════════════════════════════════════════ -->
<section class="section">
    <div class="container">
        <div class="li-layout">
            <div>
                <h2>About</h2>
                <p><?= nl2br(htmlspecialchars($listing['description'])) ?></p>

                <p class="muted" style="margin-top:1.5rem;font-style:italic;">
                    This listing is part of the Buy Local Lowveld directory.
                    When you choose this member, your spend helps keep the Lowveld economy strong.
                </p>
            </div>

            <aside>
                <div class="li-contact-card">
                    <h3>Get in touch</h3>
                    <?php if (!empty($listing['address'])): ?>
                        <div class="li-contact-row">
                            <span class="li-icon">📍</span>
                            <div>
                                <strong>Address</strong>
                                <p><?= htmlspecialchars($listing['address']) ?></p>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($listing['phone'])): ?>
                        <div class="li-contact-row">
                            <span class="li-icon">📞</span>
                            <div>
                                <strong>Phone</strong>
                                <p><a href="tel:<?= preg_replace('/[^0-9+]/','',$listing['phone']) ?>"><?= htmlspecialchars($listing['phone']) ?></a></p>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($listing['email'])): ?>
                        <div class="li-contact-row">
                            <span class="li-icon">✉️</span>
                            <div>
                                <strong>Email</strong>
                                <p><a href="mailto:<?= htmlspecialchars($listing['email']) ?>"><?= htmlspecialchars($listing['email']) ?></a></p>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($listing['website'])): ?>
                        <div class="li-contact-row">
                            <span class="li-icon">🌐</span>
                            <div>
                                <strong>Website</strong>
                                <p><a href="<?= htmlspecialchars($listing['website']) ?>" target="_blank" rel="noopener">
                                    Visit website →
                                </a></p>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </aside>
        </div>
    </div>
</section>

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