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

$counts = [
    'members_total'     => (int)db_value("SELECT COUNT(*) FROM members"),
    'members_active'    => (int)db_value("SELECT COUNT(*) FROM members WHERE status='active'"),
    'members_pending'   => (int)db_value("SELECT COUNT(*) FROM members WHERE status='pending'"),
    'members_cancelled' => (int)db_value("SELECT COUNT(*) FROM members WHERE status='cancelled'"),
    'invoices_unpaid'   => (int)db_value("SELECT COUNT(*) FROM invoices WHERE status IN ('unpaid','overdue')"),
    'invoices_overdue'  => (int)db_value("SELECT COUNT(*) FROM invoices WHERE status='overdue'"),
    'claims_pending'    => (int)db_value("SELECT COUNT(*) FROM business_claims WHERE status='pending'"),
    'subs_active'       => (int)db_value("SELECT COUNT(*) FROM payment_tokens WHERE status='active'"),
];

// Journey summary — active members only
require_once __DIR__ . '/../includes/journey.php';
$active_member_ids = array_column(
    db_all("SELECT id FROM members WHERE status='active'"),
    'id'
);
$journey_summaries = journey_summaries_for_members($active_member_ids);
$j_done = 0; $j_in_prog = 0; $j_not_started = 0; $j_avg = 0;
foreach ($journey_summaries as $js) {
    if ($js['percent'] === 100)     $j_done++;
    elseif ($js['percent'] > 0)     $j_in_prog++;
    else                            $j_not_started++;
    $j_avg += $js['percent'];
}
$j_total = count($journey_summaries);
$j_avg = $j_total ? (int)round($j_avg / $j_total) : 0;

// Top "needs attention" members — anything not at 100%.
// Ordering priority:
//   0 = not started (highest priority — brand new, hasn't started)
//   1 = in progress (has active steps right now — may be stalled)
//   2 = partial (some done, rest pending, nothing currently in progress)
$journey_attention = db_all(
    "SELECT m.id, m.business_name, m.tier,
            (SELECT COUNT(*) FROM member_journey mj2 JOIN journey_steps js2 ON js2.id=mj2.step_id
              WHERE mj2.member_id=m.id AND js2.active=1 AND mj2.status='done') AS done_count,
            (SELECT COUNT(*) FROM journey_steps js3 WHERE js3.tier=m.tier AND js3.active=1) AS total_count,
            (SELECT COUNT(*) FROM member_journey mj4 JOIN journey_steps js4 ON js4.id=mj4.step_id
              WHERE mj4.member_id=m.id AND js4.active=1 AND mj4.status='in_progress') AS in_progress_count,
            (SELECT MAX(mj3.updated_at) FROM member_journey mj3
              WHERE mj3.member_id=m.id) AS last_activity,
            m.created_at
       FROM members m
       WHERE m.status='active'
         AND (SELECT COUNT(*) FROM journey_steps jst WHERE jst.tier=m.tier AND jst.active=1) > 0
         -- Show if journey isn't complete: done_count < total_count
         AND (
            SELECT COUNT(*) FROM member_journey mjy JOIN journey_steps jsy ON jsy.id=mjy.step_id
             WHERE mjy.member_id=m.id AND jsy.active=1 AND mjy.status='done'
         ) < (
            SELECT COUNT(*) FROM journey_steps jst2 WHERE jst2.tier=m.tier AND jst2.active=1
         )
       ORDER BY
         CASE
           WHEN NOT EXISTS (
             SELECT 1 FROM member_journey mjz
               JOIN journey_steps jsz ON jsz.id=mjz.step_id
              WHERE mjz.member_id=m.id AND jsz.active=1
                AND mjz.status IN ('done','in_progress')
           ) THEN 0  -- Not started
           WHEN EXISTS (
             SELECT 1 FROM member_journey mja
              WHERE mja.member_id=m.id AND mja.status='in_progress'
           ) THEN 1  -- In progress
           ELSE 2    -- Partial (some done, rest pending)
         END,
         last_activity ASC,
         m.created_at DESC
       LIMIT 8"
);

$mrr = (int)db_value(
    "SELECT COALESCE(SUM(i.amount_cents),0)
       FROM invoices i
       INNER JOIN (SELECT member_id, MAX(id) AS max_id FROM invoices
                   WHERE type='membership' AND status='paid' GROUP BY member_id) latest
               ON latest.max_id=i.id
       INNER JOIN payment_tokens pt ON pt.member_id=i.member_id
       WHERE pt.status='active'"
);

$new_members = db_all(
    "SELECT id, email, first_name, last_name, business_name, tier, status, created_at
       FROM members
       WHERE created_at >= DATE_SUB(NOW(), INTERVAL 3 MONTH)
       ORDER BY created_at DESC LIMIT 50"
);

$unpaid = db_all(
    "SELECT DISTINCT m.id, m.email, m.business_name, m.first_name, m.last_name, m.tier,
            (SELECT COUNT(*) FROM invoices WHERE member_id=m.id AND status IN ('unpaid','overdue')) AS invoice_count,
            (SELECT COALESCE(SUM(amount_cents),0) FROM invoices WHERE member_id=m.id AND status IN ('unpaid','overdue')) AS amount_due
       FROM members m
       JOIN invoices i ON i.member_id=m.id
       WHERE i.status IN ('unpaid','overdue') AND i.issued_at >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
       ORDER BY amount_due DESC LIMIT 50"
);

$active_carts = db_all(
    "SELECT o.id, o.status, o.total_cents, o.updated_at,
            m.id AS member_id, m.email, m.business_name,
            (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) AS items
       FROM orders o
       JOIN members m ON m.id=o.member_id
       WHERE o.status IN ('cart','pending_payment') AND o.total_cents>0
       ORDER BY o.updated_at DESC LIMIT 50"
);

function cr(int $c): string { return 'R '.number_format($c/100, 2, '.', '&nbsp;'); }
?>

<style>
.dash-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:.9rem; margin-bottom:1.75rem; }
.dash-stat { background:#fff; border:1px solid var(--line); border-radius:var(--radius);
             padding:1.1rem 1.25rem; text-decoration:none; color:inherit;
             transition:box-shadow .15s; display:block; }
.dash-stat:hover { box-shadow:0 2px 12px rgba(0,0,0,.08); }
.dash-stat .lbl { font-size:.7rem; text-transform:uppercase; letter-spacing:.06em;
                  color:var(--ink-muted); margin:0 0 .3rem; }
.dash-stat .val { font-size:2rem; font-weight:800; line-height:1; margin:0; }
.dash-stat .sub { font-size:.75rem; color:var(--ink-muted); margin:.3rem 0 0; }

.widget { background:#fff; border:1px solid var(--line); border-radius:var(--radius);
          margin-bottom:1.25rem; overflow:hidden; }
.widget-head { display:flex; justify-content:space-between; align-items:center;
               padding:1rem 1.25rem; border-bottom:1px solid var(--line); }
.widget-head h2 { margin:0; font-size:1rem; }
.widget-head .count { background:var(--surface-alt); color:var(--ink-muted);
                      font-size:.75rem; font-weight:700; padding:.2em .65em;
                      border-radius:999px; }
.widget-head .count.warn { background:#fde8e8; color:#9b1c1c; }

.atbl { width:100%; border-collapse:collapse; font-size:.855rem; }
.atbl th { padding:.5rem 1.25rem; background:var(--surface-alt); font-size:.7rem;
           text-transform:uppercase; letter-spacing:.05em; color:var(--ink-muted);
           border-bottom:1px solid var(--line); white-space:nowrap; text-align:left; }
.atbl td { padding:.6rem 1.25rem; border-bottom:1px solid var(--line); vertical-align:middle; }
.atbl tr:last-child td { border-bottom:none; }
.atbl tbody tr:hover td { background:#fafafa; }
.atbl .actions a { font-size:.8rem; color:var(--brand-primary); text-decoration:none; }
.atbl .actions a:hover { text-decoration:underline; }
.atbl .actions .sep { color:var(--line); margin:0 .25rem; }

.tb { display:inline-block; padding:.12em .5em; border-radius:3px; font-size:.68rem;
      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; }

.empty-row td { padding:1.25rem; color:var(--ink-muted); font-size:.875rem; }
</style>

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

<div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:1.25rem;">
    <h1 style="margin:0;">Dashboard</h1>
    <span class="muted" style="font-size:.85rem;"><?= date('j F Y') ?></span>
</div>

<!-- Stat cards -->
<div class="dash-stats">
    <a href="members.php?status=active" class="dash-stat">
        <p class="lbl">Active members</p>
        <p class="val" style="color:var(--brand-primary);"><?= $counts['members_active'] ?></p>
        <p class="sub"><?= $counts['members_pending'] ?> pending · <?= $counts['members_cancelled'] ?> cancelled</p>
    </a>
    <a href="subscriptions.php?filter=active" class="dash-stat">
        <p class="lbl">Active subscriptions</p>
        <p class="val"><?= $counts['subs_active'] ?></p>
        <p class="sub">MRR <?= cr($mrr) ?></p>
    </a>
    <a href="invoices.php?filter=unpaid" class="dash-stat">
        <p class="lbl">Unpaid invoices</p>
        <p class="val" style="color:<?= $counts['invoices_unpaid']>0?'var(--brand-accent)':'inherit' ?>;">
            <?= $counts['invoices_unpaid'] ?>
        </p>
        <p class="sub"><?= $counts['invoices_overdue'] ?> overdue</p>
    </a>
    <a href="claims.php" class="dash-stat">
        <p class="lbl">Pending claims</p>
        <p class="val" style="color:<?= $counts['claims_pending']>0?'var(--brand-accent)':'inherit' ?>;">
            <?= $counts['claims_pending'] ?>
        </p>
        <p class="sub">awaiting review</p>
    </a>
    <a href="journeys.php" class="dash-stat">
        <p class="lbl">Journey progress</p>
        <p class="val" style="color:var(--brand-primary);"><?= $j_avg ?>%</p>
        <p class="sub"><?= $j_done ?> complete · <?= $j_in_prog ?> in progress · <?= $j_not_started ?> not started</p>
    </a>
</div>

<!-- Widget: Journeys needing attention -->
<?php if (!empty($journey_attention)): ?>
<div class="widget">
    <div class="widget-head">
        <h2>Journeys needing attention <span class="muted" style="font-weight:400;font-size:.875rem;">anything not yet 100% complete</span></h2>
        <a href="journeys.php" style="font-size:.85rem;">See all →</a>
    </div>
    <table class="atbl">
        <thead>
            <tr>
                <th>Business</th>
                <th>Tier</th>
                <th style="min-width:220px;">Progress</th>
                <th>State</th>
                <th>Last activity</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($journey_attention as $j):
            $pct = $j['total_count']
                 ? (int)round(($j['done_count']/$j['total_count'])*100)
                 : 0;
            $tl = strtolower($j['tier']);
            $has_done    = (int)$j['done_count'] > 0;
            $has_active  = (int)$j['in_progress_count'] > 0;
            $not_started = (!$has_done && !$has_active);
        ?>
            <tr>
                <td><strong><?= htmlspecialchars($j['business_name']) ?></strong></td>
                <td><span class="tb tb-<?= $tl ?>"><?= htmlspecialchars($j['tier']) ?></span></td>
                <td>
                    <div class="jp-bar-label">
                        <span><?= $j['done_count'] ?> / <?= $j['total_count'] ?></span>
                        <span class="pct"><?= $pct ?>%</span>
                    </div>
                    <div class="jp-bar"><div class="jp-bar-fill" style="width:<?= $pct ?>%;"></div></div>
                </td>
                <td>
                    <?php if ($not_started): ?>
                        <span class="j-pill j-pill-not_started">Not started</span>
                    <?php elseif ($has_active): ?>
                        <span class="j-pill j-pill-in_progress"><?= (int)$j['in_progress_count'] ?> active</span>
                    <?php else: ?>
                        <span class="j-pill j-pill-done" style="background:#dbeafe;color:#1e40af;">Partial</span>
                    <?php endif; ?>
                </td>
                <td class="muted" style="font-size:.82rem;white-space:nowrap;">
                    <?php if ($not_started): ?>
                        <span style="color:#b91c1c;">— never opened</span>
                    <?php else: ?>
                        <?= $j['last_activity'] ? date('j M Y', strtotime($j['last_activity'])) : '—' ?>
                    <?php endif; ?>
                </td>
                <td class="actions">
                    <a href="member-edit.php?id=<?= $j['id'] ?>#journey">Open →</a>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<!-- Widget 1: New members -->
<div class="widget">
    <div class="widget-head">
        <h2>New members <span class="muted" style="font-weight:400;font-size:.875rem;">last 3 months</span></h2>
        <span class="count <?= count($new_members)===0?'':''; ?>"><?= count($new_members) ?></span>
    </div>
    <table class="atbl">
        <thead>
            <tr>
                <th>Joined</th>
                <th>Name</th>
                <th>Business</th>
                <th>Tier</th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($new_members)): ?>
            <tr class="empty-row"><td colspan="6">No new members in the last 3 months.</td></tr>
        <?php else: ?>
            <?php foreach ($new_members as $m):
                if ($m['status']==='active')         $sc='tag-ok';
                elseif ($m['status']==='cancelled')  $sc='tag-err';
                else                                 $sc='muted';
                $tl = strtolower($m['tier']);
            ?>
            <tr>
                <td style="white-space:nowrap;color:var(--ink-muted);">
                    <?= date('j M Y', strtotime($m['created_at'])) ?>
                </td>
                <td>
                    <?= htmlspecialchars($m['first_name'].' '.$m['last_name']) ?><br>
                    <small style="color:var(--ink-muted);"><?= htmlspecialchars($m['email']) ?></small>
                </td>
                <td><strong><?= htmlspecialchars($m['business_name']) ?></strong></td>
                <td><span class="tb tb-<?= $tl ?>"><?= htmlspecialchars($m['tier']) ?></span></td>
                <td><span class="tag <?= $sc ?>"><?= htmlspecialchars($m['status']) ?></span></td>
                <td class="actions">
                    <a href="member-edit.php?id=<?= $m['id'] ?>">Edit →</a>
                </td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Widget 2: Unpaid -->
<div class="widget">
    <div class="widget-head">
        <h2>Unpaid <span class="muted" style="font-weight:400;font-size:.875rem;">last month</span></h2>
        <span class="count <?= count($unpaid)>0?'warn':'' ?>"><?= count($unpaid) ?></span>
    </div>
    <table class="atbl">
        <thead>
            <tr>
                <th>Business</th>
                <th>Contact</th>
                <th>Tier</th>
                <th>Invoices</th>
                <th style="text-align:right;">Amount due</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($unpaid)): ?>
            <tr class="empty-row"><td colspan="6">All recent invoices are settled. 🎉</td></tr>
        <?php else: ?>
            <?php foreach ($unpaid as $m):
                $tl = strtolower($m['tier']);
            ?>
            <tr>
                <td><strong><?= htmlspecialchars($m['business_name']) ?></strong></td>
                <td>
                    <?= htmlspecialchars($m['first_name'].' '.$m['last_name']) ?><br>
                    <small style="color:var(--ink-muted);"><?= htmlspecialchars($m['email']) ?></small>
                </td>
                <td><span class="tb tb-<?= $tl ?>"><?= htmlspecialchars($m['tier']) ?></span></td>
                <td><?= (int)$m['invoice_count'] ?></td>
                <td style="text-align:right;font-weight:700;color:var(--brand-accent);">
                    <?= cr((int)$m['amount_due']) ?>
                </td>
                <td class="actions">
                    <a href="member-edit.php?id=<?= $m['id'] ?>">Edit</a>
                    <span class="sep">·</span>
                    <a href="invoices.php?filter=unpaid&q=<?= urlencode($m['email']) ?>">Invoices</a>
                </td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Widget 3: Active carts -->
<div class="widget">
    <div class="widget-head">
        <h2>Active carts &amp; pending payments</h2>
        <span class="count"><?= count($active_carts) ?></span>
    </div>
    <table class="atbl">
        <thead>
            <tr>
                <th>Business</th>
                <th>Last updated</th>
                <th>Items</th>
                <th>Status</th>
                <th style="text-align:right;">Total</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php if (empty($active_carts)): ?>
            <tr class="empty-row"><td colspan="6">No active carts right now.</td></tr>
        <?php else: ?>
            <?php foreach ($active_carts as $o):
                $sc = $o['status']==='cart' ? 'muted' : 'tag-err';
            ?>
            <tr>
                <td>
                    <strong><?= htmlspecialchars($o['business_name']) ?></strong><br>
                    <small style="color:var(--ink-muted);"><?= htmlspecialchars($o['email']) ?></small>
                </td>
                <td style="color:var(--ink-muted);white-space:nowrap;">
                    <?= date('j M H:i', strtotime($o['updated_at'])) ?>
                </td>
                <td><?= (int)$o['items'] ?></td>
                <td><span class="tag <?= $sc ?>"><?= htmlspecialchars($o['status']) ?></span></td>
                <td style="text-align:right;font-weight:600;"><?= cr((int)$o['total_cents']) ?></td>
                <td class="actions">
                    <a href="member-edit.php?id=<?= $o['member_id'] ?>">Member →</a>
                </td>
            </tr>
            <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
    </table>
</div>

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