<?php require __DIR__.'/../layouts/header.php'; $logs=$logs??[]; $verifications=$verifications??[]; $visitorCountries=$visitorCountries??[]; $visitorCities=$visitorCities??[]; $recentVisits=$recentVisits??[]; ?>
<div class="admin-hero">
  <div>
    <div class="eyebrow">ADMIN CONTROL CENTER</div>
    <h1>Operations dashboard</h1>
    <p class="muted">Live counters for members, money, and <strong>global visitor traffic</strong> (city / country / GPS when shared).</p>
  </div>
  <div class="admin-hero-actions">
    <a class="btn small" href="#visitor-intel">Visitor intel</a>
    <a class="btn ghost small" href="#manual-premium">Manual premium</a>
    <a class="btn ghost small" href="#payment-settings">Gateways</a>
  </div>
</div>

<div class="dash-counters">
  <div class="dash-card accent">
    <span class="dash-label">Total users</span>
    <span class="dash-value"><?= (int)($stats['users'] ?? 0) ?></span>
  </div>
  <div class="dash-card">
    <span class="dash-label">Active</span>
    <span class="dash-value"><?= (int)($stats['active'] ?? 0) ?></span>
  </div>
  <div class="dash-card paid">
    <span class="dash-label">Paid members</span>
    <span class="dash-value"><?= (int)($stats['paid_users'] ?? 0) ?></span>
  </div>
  <div class="dash-card">
    <span class="dash-label">Matches</span>
    <span class="dash-value"><?= (int)($stats['matches'] ?? 0) ?></span>
  </div>
  <div class="dash-card">
    <span class="dash-label">Messages</span>
    <span class="dash-value"><?= (int)($stats['messages'] ?? 0) ?></span>
  </div>
  <div class="dash-card">
    <span class="dash-label">Live subs</span>
    <span class="dash-value"><?= (int)($stats['subscriptions'] ?? 0) ?></span>
  </div>
  <div class="dash-card warn">
    <span class="dash-label">Open reports</span>
    <span class="dash-value"><?= (int)($stats['reports'] ?? 0) ?></span>
  </div>
  <div class="dash-card money">
    <span class="dash-label">Revenue</span>
    <span class="dash-value">KES <?= number_format((float)($stats['revenue'] ?? 0)) ?></span>
  </div>
  <div class="dash-card geo">
    <span class="dash-label">Visits today</span>
    <span class="dash-value"><?= (int)($stats['visits_today'] ?? 0) ?></span>
  </div>
  <div class="dash-card geo">
    <span class="dash-label">Unique today</span>
    <span class="dash-value"><?= (int)($stats['unique_sessions_today'] ?? 0) ?></span>
  </div>
  <div class="dash-card geo">
    <span class="dash-label">Visits 7 days</span>
    <span class="dash-value"><?= (int)($stats['visits_7d'] ?? 0) ?></span>
  </div>
  <div class="dash-card geo">
    <span class="dash-label">Countries (30d)</span>
    <span class="dash-value"><?= (int)($stats['countries'] ?? 0) ?></span>
  </div>
</div>

<section class="panel section" id="visitor-intel">
  <h2>Global visitor intelligence</h2>
  <p class="muted">Every page view is logged (path, IP, device). When the browser allows location, GPS coordinates are attached so you can see cities and countries worldwide.</p>
  <div class="grid two">
    <div>
      <h3>Top countries (30 days)</h3>
      <?php if (empty($visitorCountries)): ?>
        <p class="muted">No country data yet — visits will appear after traffic and optional GPS share.</p>
      <?php else: ?>
        <div class="list compact-list">
          <?php foreach ($visitorCountries as $vc): ?>
            <div class="match compact-row">
              <div class="match-info"><b><?= e($vc['country'] ?? '—') ?></b></div>
              <span class="badge"><?= (int)($vc['c'] ?? 0) ?> visits</span>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
    <div>
      <h3>Top cities (30 days)</h3>
      <?php if (empty($visitorCities)): ?>
        <p class="muted">No city tags yet. GPS will fill this when users allow location.</p>
      <?php else: ?>
        <div class="list compact-list">
          <?php foreach ($visitorCities as $vc): ?>
            <div class="match compact-row">
              <div class="match-info"><b><?= e($vc['city'] ?? '—') ?></b><p><?= e($vc['country'] ?? '') ?></p></div>
              <span class="badge"><?= (int)($vc['c'] ?? 0) ?></span>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
  <h3 style="margin-top:16px">Recent visits</h3>
  <div class="table-wrap">
    <table class="admin-table">
      <thead>
        <tr>
          <th>When</th><th>Path</th><th>Visitor</th><th>IP</th><th>Location</th><th>GPS</th>
        </tr>
      </thead>
      <tbody>
      <?php if (empty($recentVisits)): ?>
        <tr><td colspan="6" class="muted">No visits logged yet. Import <code>database/VISITOR_ANALYTICS.sql</code> if this stays empty.</td></tr>
      <?php else: foreach ($recentVisits as $v): ?>
        <tr>
          <td><small><?= e($v['created_at'] ?? '') ?></small></td>
          <td><code><?= e($v['path'] ?? '') ?></code></td>
          <td>
            <?php if (!empty($v['user_name'])): ?>
              <?= e($v['user_name']) ?><br><small class="muted"><?= e($v['user_email'] ?? '') ?></small>
            <?php else: ?>
              <span class="muted">Guest</span>
            <?php endif; ?>
          </td>
          <td><small><?= e($v['ip'] ?? '') ?></small></td>
          <td>
            <?php
              $loc = array_filter([$v['city'] ?? '', $v['region'] ?? '', $v['country'] ?? '']);
              echo $loc ? e(implode(', ', $loc)) : '<span class="muted">—</span>';
            ?>
          </td>
          <td>
            <?php if (!empty($v['latitude']) && !empty($v['longitude'])): ?>
              <small><?= e(number_format((float)$v['latitude'], 4)) ?>, <?= e(number_format((float)$v['longitude'], 4)) ?></small>
              <br><a class="muted" target="_blank" rel="noopener" href="https://www.openstreetmap.org/?mlat=<?= e($v['latitude']) ?>&mlon=<?= e($v['longitude']) ?>#map=12/<?= e($v['latitude']) ?>/<?= e($v['longitude']) ?>">Map</a>
            <?php else: ?>
              <span class="muted"><?= e($v['geo_source'] ?? 'none') ?></span>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</section>

<section class="panel admin-section">
  <h2>Admin checklist</h2>
  <ul class="checklist">
    <li>Review <b>open reports</b> every day — resolve or dismiss with notes in activity log.</li>
    <li>Suspend or ban accounts that harass, scam, or upload illegal content.</li>
    <li>Adjust <b>subscription prices</b> only after legal/finance sign-off.</li>
    <li>Use <b>credit adjustments</b> sparingly; every change is logged.</li>
    <li>Never process real money until a real payment provider with server-side verification is live.</li>
    <li>Change the default admin password immediately on any shared or production server.</li>
  </ul>
</section>

<section class="panel admin-section">
  <h2>Users</h2>
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>ID</th><th>User</th><th>Email</th><th>Role</th><th>Status</th><th>City</th><th>Profile</th><th>Credits</th><th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($users as $x): ?>
        <tr>
          <td><?= (int)$x['id'] ?></td>
          <td><b><?= e($x['name']) ?></b><br><small><?= e($x['created_at'] ?? '') ?></small></td>
          <td><?= e($x['email']) ?></td>
          <td>
            <?php if (($x['role'] ?? '') === 'admin'): ?>
              <span class="badge">admin</span>
            <?php else: ?>
              <form method="post" action="<?= url('admin/user/role') ?>" class="inline"><?= csrf() ?>
                <input type="hidden" name="user_id" value="<?= (int)$x['id'] ?>">
                <select name="role" onchange="this.form.submit()">
                  <?php foreach (['user','moderator','support','finance','verification'] as $r): ?>
                    <option value="<?= $r ?>" <?= (($x['role'] ?? '') === $r) ? 'selected' : '' ?>><?= $r ?></option>
                  <?php endforeach; ?>
                </select>
              </form>
            <?php endif; ?>
          </td>
          <td>
            <?php if (($x['role'] ?? '') === 'admin'): ?>
              <?= e($x['status']) ?>
            <?php else: ?>
              <form method="post" action="<?= url('admin/user/status') ?>" class="inline"><?= csrf() ?>
                <input type="hidden" name="user_id" value="<?= (int)$x['id'] ?>">
                <select name="status" onchange="this.form.submit()">
                  <?php foreach (['active','paused','suspended','banned'] as $s): ?>
                    <option value="<?= $s ?>" <?= (($x['status'] ?? '') === $s) ? 'selected' : '' ?>><?= $s ?></option>
                  <?php endforeach; ?>
                </select>
              </form>
            <?php endif; ?>
          </td>
          <td><?= e($x['city'] ?? '') ?></td>
          <td><?= (int)($x['profile_completion'] ?? 0) ?>%</td>
          <td><?= (int)($x['credits'] ?? 0) ?></td>
          <td>
            <?php if (($x['role'] ?? '') !== 'admin'): ?>
              <form method="post" action="<?= url('admin/credit') ?>" class="inline credit-form"><?= csrf() ?>
                <input type="hidden" name="user_id" value="<?= (int)$x['id'] ?>">
                <input type="number" name="amount" placeholder="+/-" style="width:70px" required>
                <button class="btn small" type="submit">Credits</button>
              </form>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</section>

<section class="panel admin-section">
  <h2>Reports</h2>
  <?php if (!$reports): ?><p class="muted">No reports yet.</p><?php else: ?>
  <div class="table-wrap">
    <table>
      <thead><tr><th>ID</th><th>Reporter</th><th>Reported</th><th>Reason</th><th>Status</th><th>Created</th><th>Update</th></tr></thead>
      <tbody>
      <?php foreach ($reports as $r): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td><?= e($r['reporter']) ?></td>
          <td><?= e($r['reported']) ?></td>
          <td><b><?= e($r['reason']) ?></b><br><small><?= e(mb_substr($r['details'] ?? '', 0, 120)) ?></small></td>
          <td><span class="badge"><?= e($r['status']) ?></span></td>
          <td><?= e($r['created_at']) ?></td>
          <td>
            <form method="post" action="<?= url('admin/report/status') ?>" class="inline"><?= csrf() ?>
              <input type="hidden" name="report_id" value="<?= (int)$r['id'] ?>">
              <select name="status" onchange="this.form.submit()">
                <?php foreach (['open','reviewing','resolved','dismissed'] as $s): ?>
                  <option value="<?= $s ?>" <?= ($r['status'] === $s) ? 'selected' : '' ?>><?= $s ?></option>
                <?php endforeach; ?>
              </select>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</section>

<section class="panel admin-section">
  <h2>Verification requests</h2>
  <?php if (!$verifications): ?><p class="muted">No verification requests.</p><?php else: ?>
  <div class="table-wrap">
    <table>
      <thead><tr><th>ID</th><th>User</th><th>Type</th><th>Status</th><th>Created</th><th>Action</th></tr></thead>
      <tbody>
      <?php foreach ($verifications as $v): ?>
        <tr>
          <td><?= (int)$v['id'] ?></td>
          <td><?= e($v['name']) ?><br><small><?= e($v['email']) ?></small></td>
          <td><?= e($v['type']) ?></td>
          <td><?= e($v['status']) ?></td>
          <td><?= e($v['created_at']) ?></td>
          <td>
            <?php if ($v['status'] === 'pending'): ?>
              <form method="post" action="<?= url('admin/verification') ?>" class="inline"><?= csrf() ?>
                <input type="hidden" name="request_id" value="<?= (int)$v['id'] ?>">
                <button class="btn small" name="status" value="approved">Approve</button>
                <button class="btn ghost small" name="status" value="rejected">Reject</button>
              </form>
            <?php else: ?>—<?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</section>

<section class="panel admin-section">
  <h2>Subscription plans</h2>
  <div class="table-wrap">
    <table>
      <thead><tr><th>Plan</th><th>Price (KES)</th><th>Description</th><th>Active</th><th>Save</th></tr></thead>
      <tbody>
      <?php foreach ($plans as $p): ?>
        <tr>
          <form method="post" action="<?= url('admin/plan/save') ?>">
            <?= csrf() ?>
            <input type="hidden" name="plan_id" value="<?= (int)$p['id'] ?>">
            <td><b><?= e($p['name']) ?></b></td>
            <td><input type="number" step="0.01" name="price_kes" value="<?= e($p['price_kes']) ?>" style="width:100px"></td>
            <td><input type="text" name="description" value="<?= e($p['description']) ?>" style="width:100%"></td>
            <td><label class="check"><input type="checkbox" name="active" <?= ((int)$p['active'] ? 'checked' : '') ?>> Active</label></td>
            <td><button class="btn small" type="submit">Save</button></td>
          </form>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</section>

<section class="panel admin-section">
  <h2>Recent payments</h2>
  <?php if (!$payments): ?><p class="muted">No payments yet.</p><?php else: ?>
  <div class="table-wrap">
    <table>
      <thead><tr><th>ID</th><th>User</th><th>Plan</th><th>Amount</th><th>Provider</th><th>Ref</th><th>Status</th><th>When</th></tr></thead>
      <tbody>
      <?php foreach ($payments as $pt): ?>
        <tr>
          <td><?= (int)$pt['id'] ?></td>
          <td><?= e($pt['name']) ?></td>
          <td><?= e($pt['plan_name'] ?? '—') ?></td>
          <td><?= e($pt['currency']) ?> <?= number_format((float)$pt['amount'], 2) ?></td>
          <td><?= e($pt['provider']) ?></td>
          <td><small><?= e($pt['reference']) ?></small></td>
          <td><?= e($pt['status']) ?></td>
          <td><?= e($pt['created_at']) ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</section>

<section class="panel admin-section">
  <h2>Admin audit log</h2>
  <p class="muted" style="font-size:12px">Immutable record of admin actions: logins, manual premium, payment settings, user status, credits.</p>
  <?php if (!$logs): ?><p class="muted">No admin actions logged yet.</p><?php else: ?>
  <div class="table-wrap">
    <table>
      <thead><tr><th>When</th><th>Admin</th><th>Action</th><th>Target</th><th>Meta</th></tr></thead>
      <tbody>
      <?php foreach ($logs as $l): ?>
        <tr>
          <td><?= e($l['created_at']) ?></td>
          <td><?= e($l['admin_name'] ?? '—') ?></td>
          <td><?= e($l['action']) ?></td>
          <td><?= e(($l['target_type'] ?? '') . ' #' . ($l['target_id'] ?? '')) ?></td>
          <td><small><?= e(is_string($l['metadata'] ?? '') ? $l['metadata'] : json_encode($l['metadata'] ?? [])) ?></small></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</section>


<section class="panel section" id="manual-premium">
  <h2>Manual premium activation</h2>
  <p class="muted">Use this when M-Pesa or Stripe fails but the member has paid (or you are granting complimentary access). Unlocks inbox, messaging, and the blue verified badge.</p>
  <form method="post" action="<?= url('admin/grant-premium') ?>" class="stack"><?= csrf() ?>
    <div class="grid two">
      <label>User
        <select name="user_id" required>
          <option value="">— Select member —</option>
          <?php foreach (($users ?? []) as $uu): if (!is_array($uu)) continue; ?>
            <option value="<?= (int)$uu['id'] ?>">
              #<?= (int)$uu['id'] ?> · <?= e($uu['name'] ?? '') ?> · <?= e($uu['email'] ?? '') ?>
              <?php if (!empty($uu['is_verified_paid']) || (!empty($uu['paid_until']) && strtotime($uu['paid_until']) > time())): ?> · PAID<?php endif; ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>
      <label>Duration (days)
        <input type="number" name="days" min="1" max="365" value="30" required>
      </label>
      <label style="grid-column:1/-1">Note (optional, internal)
        <input type="text" name="note" maxlength="200" placeholder="e.g. Paid via bank transfer / STK timed out">
      </label>
    </div>
    <button class="btn" type="submit">Activate premium / paid mode</button>
  </form>
  <hr style="margin:16px 0;border:0;border-top:1px solid rgba(255,255,255,.08)">
  <form method="post" action="<?= url('admin/revoke-premium') ?>" class="stack" onsubmit="return confirm('Revoke premium for this user?');"><?= csrf() ?>
    <label>Revoke premium
      <select name="user_id" required>
        <option value="">— Select member —</option>
        <?php foreach (($users ?? []) as $uu): if (!is_array($uu)) continue; ?>
          <option value="<?= (int)$uu['id'] ?>">#<?= (int)$uu['id'] ?> · <?= e($uu['name'] ?? '') ?> · <?= e($uu['email'] ?? '') ?></option>
        <?php endforeach; ?>
      </select>
    </label>
    <button class="btn ghost" type="submit">Revoke paid access</button>
  </form>
</section>

<section class="panel section" id="payment-settings">
  <h2>Payment gateway integrations</h2>
  <p class="muted"><strong>1) M-Pesa — Safaricom Daraja STK Push</strong> (Kenya). <strong>2) Cards — Stripe Checkout</strong> (global Visa/Mastercard). Fill keys below; leave disabled until ready. Failed STK can be retried by the member or activated manually above.</p>
  <?php $ps = $paySettings ?? payment_settings(); ?>
  <form method="post" action="<?= url('admin/payment-settings') ?>" class="stack"><?= csrf() ?>
    <div class="grid two">
      <label class="check"><input type="checkbox" name="mpesa_enabled" <?= !empty($ps['mpesa_enabled']) ? 'checked' : '' ?>> Enable M-Pesa STK</label>
      <label>M-Pesa environment
        <select name="mpesa_env">
          <option value="sandbox" <?= (($ps['mpesa_env'] ?? '') === 'sandbox') ? 'selected' : '' ?>>Sandbox</option>
          <option value="live" <?= (($ps['mpesa_env'] ?? '') === 'live') ? 'selected' : '' ?>>Live</option>
        </select>
      </label>
      <label>Consumer Key<input name="mpesa_consumer_key" value="<?= e($ps['mpesa_consumer_key'] ?? '') ?>" autocomplete="off"></label>
      <label>Consumer Secret<input name="mpesa_consumer_secret" value="<?= e($ps['mpesa_consumer_secret'] ?? '') ?>" autocomplete="off"></label>
      <label>Business Shortcode<input name="mpesa_shortcode" value="<?= e($ps['mpesa_shortcode'] ?? '') ?>" placeholder="e.g. 174379"></label>
      <label>Passkey<input name="mpesa_passkey" value="<?= e($ps['mpesa_passkey'] ?? '') ?>" autocomplete="off"></label>
      <label>Callback URL<input name="mpesa_callback_url" value="<?= e($ps['mpesa_callback_url'] ?? '') ?>" placeholder="https://your-domain/premium/mpesa/callback"></label>
      <label>Monthly price (KES)<input type="number" step="1" min="1" name="monthly_price_kes" value="<?= e($ps['monthly_price_kes'] ?? 500) ?>"></label>
      <label>Free trial hours<input type="number" min="1" name="trial_hours" value="<?= e($ps['trial_hours'] ?? 72) ?>"></label>
      <label class="check"><input type="checkbox" name="mpesa_strict_ip" <?= !empty($ps['mpesa_strict_ip']) ? 'checked' : '' ?>> Strict M-Pesa callback IP allowlist (Safaricom ranges only)</label>
    </div>
    <hr>
    <div class="grid two">
      <label class="check"><input type="checkbox" name="card_enabled" <?= !empty($ps['card_enabled']) ? 'checked' : '' ?>> Enable card payments</label>
      <label>Card provider<input name="card_provider" value="<?= e($ps['card_provider'] ?? 'stripe') ?>"></label>
      <label>Publishable key<input name="card_publishable_key" value="<?= e($ps['card_publishable_key'] ?? '') ?>" autocomplete="off"></label>
      <label>Secret key<input name="card_secret_key" value="<?= e($ps['card_secret_key'] ?? '') ?>" autocomplete="off"></label>
      <label>Webhook secret (whsec_...)<input name="card_webhook_secret" value="<?= e($ps['card_webhook_secret'] ?? '') ?>" autocomplete="off"></label>
    </div>
    <p class="muted" style="font-size:12px">Stripe webhook endpoint (Dashboard → Developers → Webhooks): <code><?= e(url('premium/stripe/webhook')) ?></code> — events: <code>checkout.session.completed</code>, <code>checkout.session.async_payment_succeeded</code>, <code>checkout.session.expired</code></p>
    <p class="muted" style="font-size:12px">M-Pesa Daraja callback URL: <code><?= e(url('premium/mpesa/callback')) ?></code> (must be public HTTPS in production)</p>
    <button class="btn" type="submit">Save payment settings</button>
  </form>
</section>

<?php require __DIR__.'/../layouts/footer.php'; ?>
