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

$listing_complete = db_value('SELECT profile_complete FROM listings WHERE member_id=:m LIMIT 1', ['m'=>$member['id']]);
$needs_profile    = ($member['status']==='active' && !$listing_complete);

$subscription = db_row(
    "SELECT * FROM payment_tokens WHERE member_id=:m AND status='active' ORDER BY created_at DESC LIMIT 1",
    ['m'=>$member['id']]
);
$is_subscribed  = !empty($subscription) && $member['status']==='active';
$next_charge    = $subscription['next_charge_at'] ?? null;
$days_to_charge = $next_charge ? (int)ceil((strtotime($next_charge)-time())/86400) : null;

$orders = db_all(
    'SELECT o.*, (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) AS item_count
       FROM orders o WHERE o.member_id=:m ORDER BY o.created_at DESC LIMIT 20',
    ['m'=>$member['id']]
);
$invoices = db_all(
    'SELECT * FROM invoices WHERE member_id=:m ORDER BY issued_at DESC LIMIT 20',
    ['m'=>$member['id']]
);
$unpaid_count = (int)db_value(
    'SELECT COUNT(*) FROM invoices WHERE member_id=:m AND status IN ("unpaid","overdue")',
    ['m'=>$member['id']]
);
$own_listing = db_row('SELECT * FROM listings WHERE member_id=:m LIMIT 1', ['m'=>$member['id']]);

function cr(int $c): string {
    $neg = $c<0; $abs = abs($c);
    return ($neg?'-':'').'R '.number_format($abs/100,2,'.','&nbsp;');
}
?>
<style>
/* ── Shared member portal styles ── */
.m-page { padding: 2rem 0 3rem; }
.m-hero { display:flex; justify-content:space-between; align-items:flex-start;
          flex-wrap:wrap; gap:1rem; margin-bottom:1.75rem; }
.m-hero h1 { margin:0 0 .25rem; font-size:1.75rem; }
.m-hero .sub { font-size:.9rem; color:var(--ink-muted); margin:0; }

.m-grid-4 { display:grid; grid-template-columns:repeat(4,1fr); gap:1rem; margin-bottom:1.5rem; }
.m-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:1rem; }
.m-grid-3 { display:grid; grid-template-columns:repeat(3,1fr); gap:1rem; }

.action-card { background:#fff; border:1px solid var(--line); border-radius:var(--radius);
               padding:1.25rem; text-align:center; text-decoration:none; color:inherit;
               transition:box-shadow .15s, transform .15s; display:block; }
.action-card:hover { box-shadow:0 4px 16px rgba(0,0,0,.1); transform:translateY(-2px); }
.action-card .icon { font-size:2rem; margin-bottom:.5rem; }
.action-card h3 { margin:0 0 .25rem; font-size:.95rem; }
.action-card p  { margin:0; font-size:.8rem; color:var(--ink-muted); }

.m-section { background:#fff; border:1px solid var(--line); border-radius:var(--radius);
             margin-bottom:1.25rem; overflow:hidden; }
.m-section-head { padding:1rem 1.25rem; border-bottom:1px solid var(--line);
                  display:flex; justify-content:space-between; align-items:center; }
.m-section-head h2 { margin:0; font-size:1rem; }

.mtbl { width:100%; border-collapse:collapse; font-size:.875rem; }
.mtbl 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); text-align:left; white-space:nowrap; }
.mtbl td { padding:.65rem 1.25rem; border-bottom:1px solid var(--line); vertical-align:middle; }
.mtbl tr:last-child td { border-bottom:none; }
.mtbl tbody tr:hover td { background:#fafafa; }
.mtbl .empty td { padding:1.25rem; color:var(--ink-muted); }

.sub-status { display:inline-flex; align-items:center; gap:.4rem;
              padding:.3em .9em; border-radius:999px; font-size:.82rem; font-weight:700; }
.sub-status.ok  { background:#d4f4dd; color:#1b5e20; }
.sub-status.off { background:#fde8e8; color:#9b1c1c; }

.stat-pill { text-align:center; }
.stat-pill .lbl { font-size:.72rem; text-transform:uppercase; letter-spacing:.05em;
                  color:var(--ink-muted); margin:0 0 .2rem; }
.stat-pill .val { font-size:1.3rem; font-weight:800; margin:0; }

.warn-banner { background:#fff8e1; border:2px solid #f59e0b; border-radius:var(--radius);
               padding:1rem 1.25rem; margin-bottom:1.5rem;
               display:flex; justify-content:space-between; align-items:center; gap:1rem; }
</style>

<div class="m-page">
<div class="container">

<?php if ($needs_profile): ?>
<div class="warn-banner">
    <div>
        <strong>⚠️ Your listing isn't live yet.</strong>
        Complete your company profile to appear in the directory.
    </div>
    <a href="complete-profile.php" class="btn" style="white-space:nowrap;">Complete now →</a>
</div>
<?php endif; ?>

<?php if (!empty($member['cancel_effective_at'])): ?>
<div class="m-alert m-alert-warn" style="display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1.25rem;flex-wrap:wrap;">
    <div style="flex:1;min-width:240px;">
        <strong>⏱ Your membership is scheduled to end on
            <?= htmlspecialchars(date('j F Y', strtotime($member['cancel_effective_at']))) ?>.</strong>
        <p style="margin:.25rem 0 0;font-size:.88rem;">
            You won't be charged again. Your listing stays live until that date.
            Changed your mind? Reactivate now — no new charge, your subscription just resumes.
        </p>
    </div>
    <form method="post" action="cancel-membership.php" style="margin:0;">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="reactivate">
        <button type="submit" class="btn" style="background:#059669;color:#fff;border:none;font-weight:700;white-space:nowrap;">
            ↻ Reactivate
        </button>
    </form>
</div>
<?php elseif ($member['status'] === 'cancelled'): ?>
<div class="m-alert m-alert-warn" style="display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1.25rem;flex-wrap:wrap;">
    <div style="flex:1;min-width:240px;">
        <strong>Your membership has ended.</strong>
        <p style="margin:.25rem 0 0;font-size:.88rem;">
            To come back, set up a fresh subscription — pricing and tiers are the same as before.
        </p>
    </div>
    <a href="checkout-membership.php?reactivate=1" class="btn" style="white-space:nowrap;">Re-subscribe →</a>
</div>
<?php endif; ?>

<!-- Hero -->
<div class="m-hero">
    <div>
        <h1>Welcome back, <?= htmlspecialchars($member['first_name']) ?></h1>
        <p class="sub">
            <?= htmlspecialchars($member['business_name']) ?>
            &nbsp;·&nbsp;
            <span style="font-weight:600;"><?= htmlspecialchars($member['tier']) ?></span>
            <?php if ($member['status']==='pending'): ?>
                &nbsp;·&nbsp;<span style="color:var(--brand-accent);">Pending payment</span>
            <?php endif; ?>
        </p>
    </div>
    <?php if ($own_listing): ?>
        <a href="../directory-item.php?id=<?= $own_listing['id'] ?>"
           class="btn btn-outline" target="_blank">View my listing ↗</a>
    <?php endif; ?>
</div>

<!-- Quick action cards -->
<div class="m-grid-4" style="margin-bottom:1.75rem;">
    <a href="complete-profile.php" class="action-card">
        <div class="icon">🏢</div>
        <h3>My Listing</h3>
        <p>Update your directory page</p>
    </a>
    <a href="view-statement.php" class="action-card">
        <div class="icon">📄</div>
        <h3>Statement</h3>
        <p>Account history &amp; banking</p>
    </a>
    <a href="view-transactions.php" class="action-card">
        <div class="icon">💳</div>
        <h3>Transactions</h3>
        <p>Every charge &amp; payment</p>
    </a>
    <a href="../additional-branding.php" class="action-card">
        <div class="icon">🎨</div>
        <h3>Branding</h3>
        <p>Co-branded marketing items</p>
    </a>
</div>

<!-- Membership status -->
<div class="m-section">
    <div class="m-section-head">
        <h2>Membership</h2>
        <?php if ($is_subscribed): ?>
            <span class="sub-status ok">✓ Subscribed</span>
        <?php else: ?>
            <span class="sub-status off">Not subscribed</span>
        <?php endif; ?>
    </div>
    <div style="padding:1.25rem;">
        <div class="m-grid-3" style="margin-bottom:1.25rem;">
            <div class="stat-pill">
                <p class="lbl">Package</p>
                <p class="val"><?= htmlspecialchars($member['tier']) ?></p>
            </div>
            <div class="stat-pill">
                <p class="lbl">Member since</p>
                <p class="val" style="font-size:1rem;">
                    <?= $member['join_date'] ? date('j M Y', strtotime($member['join_date'])) : '—' ?>
                </p>
            </div>
            <div class="stat-pill">
                <p class="lbl"><?= $is_subscribed ? 'Next charge' : 'Renewal date' ?></p>
                <p class="val" style="font-size:1rem;">
                    <?php $ds = $next_charge ?? $member['renewal_date'];
                    echo $ds ? date('j M Y', strtotime($ds)) : '—';
                    if ($days_to_charge!==null && $days_to_charge<=7 && $days_to_charge>=0)
                        echo ' <span class="tag tag-err" style="font-size:.72rem;">'.$days_to_charge.'d</span>';
                    ?>
                </p>
            </div>
        </div>
        <div style="display:flex;gap:.75rem;align-items:center;">
            <?php if (!$is_subscribed): ?>
                <a href="checkout-membership.php" class="btn">Activate subscription →</a>
            <?php elseif (!empty($member['cancel_effective_at'])): ?>
                <span class="muted" style="font-size:.85rem;">Cancellation pending — contact us to reactivate.</span>
            <?php else: ?>
                <a href="change-subscription.php" class="btn btn-outline">Change package</a>
                <a href="cancel-membership.php" class="muted" style="font-size:.85rem;">Cancel subscription</a>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Invoices -->
<div class="m-section">
    <div class="m-section-head">
        <h2>
            Invoices
            <?php if ($unpaid_count>0): ?>
                <span class="tag tag-err" style="margin-left:.5rem;font-size:.75rem;"><?= $unpaid_count ?> unpaid</span>
            <?php endif; ?>
        </h2>
        <a href="view-statement.php" style="font-size:.82rem;">Full statement →</a>
    </div>
    <?php if (empty($invoices)): ?>
        <div style="padding:1.25rem;color:var(--ink-muted);font-size:.875rem;">No invoices yet.</div>
    <?php else: ?>
    <table class="mtbl">
        <thead>
            <tr>
                <th>Invoice</th>
                <th>Date</th>
                <th>Description</th>
                <th style="text-align:right;">Amount</th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($invoices as $inv):
            $paid = $inv['status']==='paid';
            $cls  = $paid ? 'tag-ok' : 'tag-err';
        ?>
            <tr>
                <td>
                    <a href="invoice.php?id=<?= $inv['id'] ?>">
                        <code style="font-size:.8rem;"><?= htmlspecialchars($inv['number']) ?></code>
                    </a>
                </td>
                <td style="color:var(--ink-muted);white-space:nowrap;">
                    <?= date('j M Y', strtotime($inv['issued_at'])) ?>
                </td>
                <td><?= htmlspecialchars($inv['description']) ?></td>
                <td style="text-align:right;font-weight:600;"><?= cr((int)$inv['amount_cents']) ?></td>
                <td><span class="tag <?= $cls ?>"><?= htmlspecialchars($inv['status']) ?></span></td>
                <td style="white-space:nowrap;">
                    <?php if (!$paid): ?>
                        <a href="<?= $inv['type']==='membership'?'checkout-membership.php':'checkout-cart.php' ?>"
                           class="btn" style="padding:.25rem .65rem;font-size:.8rem;">Pay now</a>
                    <?php else: ?>
                        <a href="invoice.php?id=<?= $inv['id'] ?>" style="font-size:.82rem;color:var(--ink-muted);">Receipt</a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

<!-- Orders (only show if any exist) -->
<?php if (!empty($orders)): ?>
<div class="m-section">
    <div class="m-section-head">
        <h2>Branding orders</h2>
        <a href="cart.php" style="font-size:.82rem;">View cart →</a>
    </div>
    <table class="mtbl">
        <thead>
            <tr>
                <th>Date</th>
                <th>Items</th>
                <th style="text-align:right;">Total</th>
                <th>Status</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($orders as $o):
            $paid = $o['status']==='paid';
        ?>
            <tr>
                <td style="color:var(--ink-muted);"><?= date('j M Y', strtotime($o['created_at'])) ?></td>
                <td><?= (int)$o['item_count'] ?></td>
                <td style="text-align:right;font-weight:600;"><?= cr((int)$o['total_cents']) ?></td>
                <td><span class="tag tag-<?= $paid?'ok':'err' ?>"><?= htmlspecialchars($o['status']) ?></span></td>
                <td>
                    <?php if ($o['status']==='cart' || $o['status']==='pending_payment'): ?>
                        <a href="cart.php" style="font-size:.82rem;">View →</a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

</div><!-- /container -->
</div><!-- /m-page -->
<?php require __DIR__ . '/_footer.php'; ?>