<?php
$page_title = 'Journeys';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/journey.php';

$tier_filter = $_GET['tier'] ?? '';
$status_filter = $_GET['progress'] ?? ''; // 'not_started' | 'in_progress' | 'done' | ''

$where  = ["m.status IN ('active','pending')"];
$params = [];
if ($tier_filter && in_array($tier_filter, ['Bronze','Silver','Gold','Platinum','Diamond'], true)) {
    $where[] = "m.tier = :tier";
    $params['tier'] = $tier_filter;
}

$members = db_all(
    "SELECT m.id, m.email, m.first_name, m.last_name, m.business_name, m.tier, m.status,
            m.created_at, m.join_date
       FROM members m
       WHERE " . implode(' AND ', $where) . "
       ORDER BY m.created_at DESC
       LIMIT 500",
    $params
);

$ids = array_column($members, 'id');
$summaries = journey_summaries_for_members($ids);

// Apply progress filter (done client-side after summaries)
if ($status_filter === 'done') {
    $members = array_filter($members, fn($m) => ($summaries[(int)$m['id']]['percent'] ?? 0) === 100);
} elseif ($status_filter === 'not_started') {
    $members = array_filter($members, fn($m) => ($summaries[(int)$m['id']]['percent'] ?? 0) === 0);
} elseif ($status_filter === 'in_progress') {
    $members = array_filter($members, function($m) use ($summaries) {
        $p = $summaries[(int)$m['id']]['percent'] ?? 0;
        return $p > 0 && $p < 100;
    });
}

// Counts for filter badges
$total_count = count($ids);
$done_count       = count(array_filter($ids, fn($id) => ($summaries[(int)$id]['percent'] ?? 0) === 100));
$in_prog_count    = count(array_filter($ids, fn($id) => ($summaries[(int)$id]['percent'] ?? 0) > 0 && ($summaries[(int)$id]['percent'] ?? 0) < 100));
$not_started_count = count(array_filter($ids, fn($id) => ($summaries[(int)$id]['percent'] ?? 0) === 0));
?>

<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);text-align:left;white-space:nowrap;}
.atbl td{padding:.7rem 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;}
.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;}
</style>

<section class="section">
<div class="container">

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1.25rem;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1 style="margin:0;">Member Journeys</h1>
        <p class="muted" style="margin:.25rem 0 0;font-size:.9rem;">
            Track each member's onboarding progress — different steps per tier.
        </p>
    </div>
    <a href="journey-templates.php" class="btn btn-outline">⚙ Manage templates</a>
</div>

<!-- Filter tabs -->
<div style="display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:.75rem;">
    <a href="?progress=" class="ftab <?= $status_filter===''?'on':'' ?>">All <span class="cnt"><?= $total_count ?></span></a>
    <a href="?progress=not_started"  class="ftab <?= $status_filter==='not_started'?'on':'' ?>">Not started <span class="cnt"><?= $not_started_count ?></span></a>
    <a href="?progress=in_progress"  class="ftab <?= $status_filter==='in_progress'?'on':'' ?>">In progress <span class="cnt"><?= $in_prog_count ?></span></a>
    <a href="?progress=done"         class="ftab <?= $status_filter==='done'?'on':'' ?>">Complete <span class="cnt"><?= $done_count ?></span></a>
</div>

<form method="get" style="display:flex;gap:.5rem;margin-bottom:1.1rem;flex-wrap:wrap;">
    <input type="hidden" name="progress" value="<?= htmlspecialchars($status_filter) ?>">
    <select name="tier" onchange="this.form.submit()" style="width:160px;">
        <option value="">All tiers</option>
        <?php foreach (['Diamond','Platinum','Gold','Silver','Bronze'] as $t): ?>
            <option value="<?= $t ?>" <?= $tier_filter===$t?'selected':'' ?>><?= $t ?></option>
        <?php endforeach; ?>
    </select>
</form>

<?php if (empty($members)): ?>
    <div class="card"><p class="muted" style="margin:0;">No members match your filters.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>Member</th>
                <th>Tier</th>
                <th style="min-width:260px;">Progress</th>
                <th style="text-align:center;">Steps</th>
                <th>Joined</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($members as $m):
                $s = $summaries[(int)$m['id']] ?? ['percent'=>0,'done'=>0,'total'=>0,'in_progress'=>0];
                $tier_lc = strtolower($m['tier']);
                $complete = ($s['percent'] === 100);
            ?>
                <tr>
                    <td>
                        <strong><?= htmlspecialchars($m['business_name']) ?></strong>
                        <br><small class="muted"><?= htmlspecialchars($m['first_name'] . ' ' . $m['last_name']) ?> · <?= htmlspecialchars($m['email']) ?></small>
                    </td>
                    <td><span class="tb tb-<?= $tier_lc ?>"><?= htmlspecialchars($m['tier']) ?></span></td>
                    <td>
                        <div class="jp-bar-label">
                            <span><?= $s['done'] ?> / <?= $s['total'] ?> done</span>
                            <span class="pct"><?= $s['percent'] ?>%</span>
                        </div>
                        <div class="jp-bar">
                            <div class="jp-bar-fill <?= $complete ? 'complete' : '' ?>" style="width:<?= $s['percent'] ?>%;"></div>
                        </div>
                    </td>
                    <td style="text-align:center;font-size:.8rem;">
                        <?php if ($s['in_progress']>0): ?>
                            <span class="j-pill j-pill-in_progress"><?= $s['in_progress'] ?> active</span>
                        <?php else: ?>
                            <span class="muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="muted" style="font-size:.82rem;">
                        <?= $m['join_date'] ? date('j M Y', strtotime($m['join_date'])) : '—' ?>
                    </td>
                    <td style="text-align:right;white-space:nowrap;">
                        <a href="member-edit.php?id=<?= $m['id'] ?>#journey">Open →</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<p class="muted" style="font-size:.8rem;margin:.5rem 0 0;"><?= count($members) ?> result<?= count($members)===1?'':'s' ?>.</p>
<?php endif; ?>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>