<?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">
<meta name="csrf-token" content="<?= htmlspecialchars(csrf_token()) ?>">
<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_request_at']) && empty($member['cancel_effective_at'])): ?>
                <span class="muted" style="font-size:.85rem;">⏳ Cancellation request received — our team will contact you shortly.</span>
            <?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>
                <button type="button" id="btn-request-cancel" class="btn" style="background:#b91c1c;border-color:#b91c1c;font-size:.85rem;">Request Cancellation</button>
            <?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 -->
<!-- ── Cancel Request Modal ───────────────────────────────────────────── -->
<div id="cancel-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:var(--radius,8px);padding:2rem;max-width:500px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.25);position:relative;">
        <button id="close-cancel-modal"
                style="position:absolute;top:.75rem;right:1rem;background:none;border:none;font-size:1.4rem;cursor:pointer;color:var(--ink-muted);line-height:1;"
                aria-label="Close">×</button>
        <h2 style="margin:0 0 .5rem;font-size:1.15rem;">Request Cancellation</h2>
        <p style="font-size:.875rem;color:var(--ink-muted);margin:0 0 1.25rem;">
            Please tell us why you would like to cancel. Our team will review your request and contact you directly to assist.
        </p>

        <div id="cancel-modal-error" style="display:none;background:#fef2f2;border:1px solid #fca5a5;border-radius:var(--radius);padding:.75rem 1rem;font-size:.875rem;color:#991b1b;margin-bottom:1rem;"></div>
        <div id="cancel-modal-success" style="display:none;background:#ecfdf5;border:1px solid #6ee7b7;border-radius:var(--radius);padding:.75rem 1rem;font-size:.875rem;color:#065f46;margin-bottom:1rem;"></div>

        <div id="cancel-modal-form">
            <label style="display:block;font-size:.875rem;font-weight:600;margin-bottom:.4rem;" for="cancel-reason">
                Reason for cancellation <span style="color:#b91c1c;">*</span>
            </label>
            <select id="cancel-reason-preset" style="width:100%;padding:.45rem .75rem;border:1px solid var(--line);border-radius:var(--radius);font-size:.875rem;margin-bottom:.6rem;box-sizing:border-box;">
                <option value="">— Select a reason —</option>
                <option value="Too expensive">Too expensive</option>
                <option value="Not getting enough value">Not getting enough value from my listing</option>
                <option value="Business is closing">My business is closing</option>
                <option value="Switching to a different package">Switching to a different package</option>
                <option value="Moving out of the area">Moving out of the area</option>
                <option value="Other">Other — please specify below</option>
            </select>
            <textarea id="cancel-reason"
                      placeholder="Additional details (optional)"
                      rows="4"
                      style="width:100%;padding:.55rem .75rem;border:1px solid var(--line);border-radius:var(--radius);font-size:.875rem;resize:vertical;box-sizing:border-box;font-family:inherit;"></textarea>
            <p style="font-size:.78rem;color:var(--ink-muted);margin:.4rem 0 1.25rem;">
                Your membership stays active — a team member will contact you to process the cancellation.
            </p>
            <div style="display:flex;gap:.75rem;">
                <button id="submit-cancel-request" class="btn" style="background:#b91c1c;">
                    Send Request
                </button>
                <button type="button" id="close-cancel-modal-2" class="btn btn-outline">
                    Keep My Membership
                </button>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const trigger  = document.getElementById('btn-request-cancel');
    const modal    = document.getElementById('cancel-modal');
    const closeBtn = document.getElementById('close-cancel-modal');
    const closeBtn2 = document.getElementById('close-cancel-modal-2');
    const preset   = document.getElementById('cancel-reason-preset');
    const textarea = document.getElementById('cancel-reason');
    const errBox   = document.getElementById('cancel-modal-error');
    const okBox    = document.getElementById('cancel-modal-success');
    const formWrap = document.getElementById('cancel-modal-form');
    const submitBtn = document.getElementById('submit-cancel-request');

    if (!trigger) return;

    function openModal()  { modal.style.display = 'flex'; document.body.style.overflow = 'hidden'; }
    function closeModal() { modal.style.display = 'none'; document.body.style.overflow = ''; }

    trigger.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);
    closeBtn2.addEventListener('click', closeModal);
    modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });

    // When preset selected, pre-fill textarea
    preset.addEventListener('change', function () {
        if (this.value && this.value !== 'Other') {
            textarea.placeholder = 'Any additional details? (optional)';
        }
    });

    submitBtn.addEventListener('click', function () {
        errBox.style.display = 'none';

        // Build reason string
        let reason = preset.value;
        const extra = textarea.value.trim();
        if (reason === 'Other' || reason === '') reason = extra;
        else if (extra) reason += ': ' + extra;

        if (!reason) {
            errBox.textContent = 'Please select or describe a reason before submitting.';
            errBox.style.display = 'block';
            return;
        }

        submitBtn.disabled = true;
        submitBtn.textContent = 'Sending…';

        // Get CSRF token from a hidden field on the page
        const metaTag = document.querySelector('meta[name="csrf-token"]');
        const csrf = metaTag ? metaTag.getAttribute('content') : '';

        const fd = new FormData();
        fd.append('_csrf', csrf);
        fd.append('reason', reason);

        fetch('request-cancel.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(data => {
                if (data.ok) {
                    formWrap.style.display = 'none';
                    okBox.textContent = data.message || 'Request sent! Our team will be in touch shortly.';
                    okBox.style.display = 'block';
                    // Refresh page after 3s so the "pending" banner appears
                    setTimeout(() => location.reload(), 3000);
                } else {
                    errBox.textContent = data.error || 'Something went wrong. Please try again.';
                    errBox.style.display = 'block';
                    submitBtn.disabled = false;
                    submitBtn.textContent = 'Send Request';
                }
            })
            .catch(() => {
                errBox.textContent = 'Network error. Please check your connection and try again.';
                errBox.style.display = 'block';
                submitBtn.disabled = false;
                submitBtn.textContent = 'Send Request';
            });
    });
})();
</script>

<?php require __DIR__ . '/_footer.php'; ?>