<?php
$page_title = 'Listings';
require __DIR__ . '/_guard.php';

// Quick actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['listing_id'] ?? 0);

    if ($do === 'toggle_published' && $id) {
        $cur = (int)db_value('SELECT published FROM listings WHERE id=:id', ['id'=>$id]);
        db_exec('UPDATE listings SET published=:p WHERE id=:id', ['p'=>$cur?0:1,'id'=>$id]);
    }
    if ($do === 'toggle_featured' && $id) {
        $cur = (int)db_value('SELECT featured FROM listings WHERE id=:id', ['id'=>$id]);
        db_exec('UPDATE listings SET featured=:f WHERE id=:id', ['f'=>$cur?0:1,'id'=>$id]);
    }
    if ($do === 'delete' && $id) {
        // Remove logo file if present
        $logo = db_value('SELECT logo_path FROM listings WHERE id=:id', ['id'=>$id]);
        if ($logo) {
            $path = __DIR__ . '/../' . ltrim($logo, '/');
            if (file_exists($path)) @unlink($path);
        }
        db_exec('DELETE FROM listings WHERE id=:id', ['id'=>$id]);
        header('Location: listings.php?msg=deleted'); exit;
    }
    header('Location: listings.php?'.http_build_query($_GET)); exit;
}

$q        = trim($_GET['q'] ?? '');
$tier     = $_GET['tier']     ?? '';
$cat      = $_GET['cat']      ?? '';
$status   = $_GET['status']   ?? '';
$featured = $_GET['featured'] ?? '';

$where  = ['1=1'];
$params = [];

if ($q !== '') {
    $where[] = '(l.name LIKE :q1 OR l.description LIKE :q2 OR l.address LIKE :q3)';
    $params['q1'] = '%'.$q.'%';
    $params['q2'] = '%'.$q.'%';
    $params['q3'] = '%'.$q.'%';
}
if ($tier && in_array($tier, ['Bronze','Silver','Gold','Platinum','Diamond'], true)) {
    $where[] = 'l.tier = :tier'; $params['tier'] = $tier;
}
if ($cat !== '') {
    $where[] = 'l.id IN (SELECT listing_id FROM listing_categories WHERE category_slug = :cat)';
    $params['cat'] = $cat;
}
if ($status === 'published')   $where[] = 'l.published = 1';
if ($status === 'unpublished') $where[] = 'l.published = 0';
if ($status === 'unclaimed')   $where[] = 'l.member_id IS NULL';
if ($featured === '1')         $where[] = 'l.featured = 1';

$listings = db_all(
    "SELECT l.*, m.email AS member_email, m.business_name AS member_biz,
            c.name AS category_name,
            (SELECT GROUP_CONCAT(c2.name ORDER BY lc.is_primary DESC, c2.name SEPARATOR ', ')
               FROM listing_categories lc
               JOIN categories c2 ON c2.slug = lc.category_slug
              WHERE lc.listing_id = l.id) AS all_categories,
            (SELECT COUNT(*) FROM metrics_pageviews
               WHERE listing_id=l.id
                 AND viewed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)) AS views_30d
       FROM listings l
       LEFT JOIN members m    ON m.id = l.member_id
       LEFT JOIN categories c ON c.slug = l.category_slug
       WHERE ".implode(' AND ', $where)."
       ORDER BY FIELD(l.tier,'Diamond','Platinum','Gold','Silver','Bronze'), l.name
       LIMIT 500",
    $params
);

$counts = [
    'all'         => (int)db_value('SELECT COUNT(*) FROM listings'),
    'published'   => (int)db_value('SELECT COUNT(*) FROM listings WHERE published=1'),
    'unpublished' => (int)db_value('SELECT COUNT(*) FROM listings WHERE published=0'),
    'unclaimed'   => (int)db_value('SELECT COUNT(*) FROM listings WHERE member_id IS NULL'),
    'featured'    => (int)db_value('SELECT COUNT(*) FROM listings WHERE featured=1'),
];

$categories = db_all('SELECT slug, name FROM categories ORDER BY sort_order, name');
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);white-space:nowrap;text-align:left;}
.atbl td{padding:.6rem 1rem;border-bottom:1px solid var(--line);vertical-align:middle;}
.atbl tr:last-child td{border-bottom:none;}
.atbl tbody tr:hover td{background:#fafafa;}
.ftab{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .85rem;border-radius:999px;font-size:.82rem;border:1px solid var(--line);text-decoration:none;color:var(--ink);}
.ftab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.ftab .cnt{background:rgba(0,0,0,.12);border-radius:999px;padding:.05em .45em;font-size:.78em;font-weight:700;}
.l-logo{width:46px;height:46px;border-radius:8px;border:1px solid var(--line);background:#fff;display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;}
.l-logo img{max-width:100%;max-height:100%;object-fit:contain;padding:4px;}
.l-logo .init{font-family:var(--font-display);font-size:1.1rem;color:var(--ink-light);}
.tb{display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
.tb-bronze{background:#cd7f32;color:#fff;}.tb-silver{background:#a0a0ad;color:#fff;}
.tb-gold{background:#c9a227;color:#fff;}.tb-platinum{background:#6a5acd;color:#fff;}
.tb-diamond{background:#1a1a2e;color:#fff;}
.inline-form{display:inline;}
.inline-form button{background:none;border:none;cursor:pointer;color:var(--brand-primary);font-size:.82rem;padding:0;font-family:inherit;}
.inline-form button:hover{text-decoration:underline;}
.inline-form.danger button{color:#b91c1c;}
.star-on{color:#e4b93d;}
.star-off{color:var(--line);}
</style>

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

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.25rem;">
    <h1 style="margin:0;">Listings <span class="muted" style="font-size:1rem;font-weight:400;">(<?= $counts['all'] ?>)</span></h1>
    <a href="listing-edit.php?action=add" class="btn">+ Add listing</a>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success" data-autohide>
        <?= $_GET['msg']==='deleted' ? 'Listing deleted.' : htmlspecialchars($_GET['msg']) ?>
    </div>
<?php endif; ?>

<!-- Filter tabs -->
<div style="display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:.75rem;">
    <a href="?status=" class="ftab <?= $status===''?'on':'' ?>">All <span class="cnt"><?= $counts['all'] ?></span></a>
    <a href="?status=published"   class="ftab <?= $status==='published'?'on':'' ?>">Published <span class="cnt"><?= $counts['published'] ?></span></a>
    <a href="?status=unpublished" class="ftab <?= $status==='unpublished'?'on':'' ?>">Unpublished <span class="cnt"><?= $counts['unpublished'] ?></span></a>
    <a href="?status=unclaimed"   class="ftab <?= $status==='unclaimed'?'on':'' ?>">Unclaimed <span class="cnt"><?= $counts['unclaimed'] ?></span></a>
    <a href="?featured=1"         class="ftab <?= $featured==='1'?'on':'' ?>">⭐ Featured <span class="cnt"><?= $counts['featured'] ?></span></a>
</div>

<!-- Search + filters -->
<form method="get" style="display:flex;gap:.5rem;margin-bottom:1.1rem;flex-wrap:wrap;">
    <input type="hidden" name="status"   value="<?= htmlspecialchars($status) ?>">
    <input type="hidden" name="featured" value="<?= htmlspecialchars($featured) ?>">
    <input type="search" name="q" value="<?= htmlspecialchars($q) ?>"
           placeholder="Search name, description, address…" style="flex:1;min-width:220px;">
    <select name="tier" style="width:130px;">
        <option value="">Any tier</option>
        <?php foreach (['Diamond','Platinum','Gold','Silver','Bronze'] as $t): ?>
            <option value="<?= $t ?>" <?= $tier===$t?'selected':'' ?>><?= $t ?></option>
        <?php endforeach; ?>
    </select>
    <select name="cat" style="width:180px;">
        <option value="">Any category</option>
        <?php foreach ($categories as $c): ?>
            <option value="<?= htmlspecialchars($c['slug']) ?>" <?= $cat===$c['slug']?'selected':'' ?>>
                <?= htmlspecialchars($c['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
    <button type="submit" class="btn">Filter</button>
    <?php if ($q||$tier||$cat||$status||$featured): ?>
        <a href="listings.php" class="btn btn-outline">Clear</a>
    <?php endif; ?>
</form>

<?php if (empty($listings)): ?>
    <div class="card"><p class="muted" style="margin:0;">No listings match your filters.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th style="width:60px;"></th>
                <th>Business</th>
                <th>Tier</th>
                <th>Category</th>
                <th>Member</th>
                <th style="text-align:center;">⭐</th>
                <th>Status</th>
                <th style="text-align:right;">Views (30d)</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($listings as $l):
            $tier_lc = strtolower($l['tier']);
        ?>
            <tr>
                <td>
                    <div class="l-logo">
                        <?php if (!empty($l['logo_path'])): ?>
                            <img src="../<?= htmlspecialchars($l['logo_path']) ?>" alt="">
                        <?php else: ?>
                            <span class="init"><?= htmlspecialchars(strtoupper(mb_substr($l['name'], 0, 2))) ?></span>
                        <?php endif; ?>
                    </div>
                </td>
                <td>
                    <strong><?= htmlspecialchars($l['name']) ?></strong>
                    <?php if ($l['tagline'] ?? ''): ?>
                        <br><small class="muted" style="font-size:.78rem;">
                            <?= htmlspecialchars(mb_substr($l['tagline'], 0, 70)) ?>
                        </small>
                    <?php endif; ?>
                </td>
                <td><span class="tb tb-<?= $tier_lc ?>"><?= htmlspecialchars($l['tier']) ?></span></td>
                <td class="muted">
                    <?= htmlspecialchars($l['all_categories'] ?: $l['category_name'] ?: $l['category_slug']) ?>
                </td>
                <td>
                    <?php if ($l['member_id']): ?>
                        <a href="member-edit.php?id=<?= $l['member_id'] ?>" style="font-size:.82rem;">
                            <?= htmlspecialchars($l['member_biz']) ?>
                        </a>
                    <?php else: ?>
                        <span class="tag tag-err" style="font-size:.7rem;">Unclaimed</span>
                    <?php endif; ?>
                </td>
                <td style="text-align:center;">
                    <form method="post" class="inline-form">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="toggle_featured">
                        <input type="hidden" name="listing_id" value="<?= $l['id'] ?>">
                        <button type="submit" style="font-size:1rem;color:<?= $l['featured']?'#e4b93d':'var(--line)' ?>;" title="Toggle featured">
                            <?= $l['featured'] ? '★' : '☆' ?>
                        </button>
                    </form>
                </td>
                <td>
                    <span class="tag <?= $l['published']?'tag-ok':'muted' ?>">
                        <?= $l['published'] ? 'Published' : 'Hidden' ?>
                    </span>
                </td>
                <td style="text-align:right;font-weight:600;">
                    <?= number_format((int)$l['views_30d']) ?>
                </td>
                <td style="white-space:nowrap;">
                    <a href="listing-edit.php?id=<?= $l['id'] ?>">Edit</a>
                    &nbsp;·&nbsp;
                    <a href="../directory-item.php?id=<?= $l['id'] ?>" target="_blank">View</a>
                    &nbsp;·&nbsp;
                    <form method="post" class="inline-form">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="toggle_published">
                        <input type="hidden" name="listing_id" value="<?= $l['id'] ?>">
                        <button type="submit"><?= $l['published']?'Hide':'Show' ?></button>
                    </form>
                    &nbsp;·&nbsp;
                    <form method="post" class="inline-form danger"
                          onsubmit="return confirm('Delete this listing permanently? This cannot be undone.');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="do" value="delete">
                        <input type="hidden" name="listing_id" value="<?= $l['id'] ?>">
                        <button type="submit">Delete</button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<p class="muted" style="font-size:.8rem;margin:.5rem 0 0;"><?= count($listings) ?> result<?= count($listings)===1?'':'s' ?>.</p>
<?php endif; ?>

</div>
</section>
<?php require __DIR__ . '/_footer.php'; ?>