<?php
// ═══════════════════════════════════════════════════════════
//  FICTION IGNITION — admin/index.php
//  Admin dashboard: users, tiers, subscriptions, usage
//  Access: add your email to ADMIN_EMAILS in .env
// ═══════════════════════════════════════════════════════════

declare(strict_types=1);

require_once __DIR__ . '/../api/lib/config.php';
require_once __DIR__ . '/../api/lib/square.php';

// ── Auth check ─────────────────────────────────────────────
$session = fi_get_session();
if (!$session) {
    header('Location: ' . rtrim(env('APP_URL'), '/') . '/index.html?signin=1&next=admin');
    exit;
}
// Admin access is controlled by the isAdmin column in the users table.
// To grant access: UPDATE users SET isAdmin = 1 WHERE email = 'your@email.com';
if (!(bool)($session['isAdmin'] ?? false)) {
    http_response_code(403);
    die('<h1>403 Forbidden</h1><p>You do not have admin access. Set isAdmin = 1 in the users table for your account.</p>');
}

// ── Handle tier change POST ────────────────────────────────
$actionMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $db = fi_db();
    if ($_POST['action'] === 'set_tier' && !empty($_POST['user_id']) && !empty($_POST['tier'])) {
        $userId  = $_POST['user_id'];
        $newTier = $_POST['tier'];
        if (array_key_exists($newTier, TIERS)) {
            $db->prepare('UPDATE users SET tier = ? WHERE id = ?')->execute([$newTier, $userId]);
            $actionMsg = "Tier updated successfully.";
        }
    }
    if ($_POST['action'] === 'toggle_admin' && !empty($_POST['user_id'])) {
        $targetId = $_POST['user_id'];
        // Prevent removing your own admin (safety guard)
        if ($targetId !== $session['id']) {
            $curr = $db->prepare('SELECT isAdmin FROM users WHERE id = ? LIMIT 1');
            $curr->execute([$targetId]);
            $row  = $curr->fetch();
            if ($row) {
                $newVal = $row['isAdmin'] ? 0 : 1;
                $db->prepare('UPDATE users SET isAdmin = ? WHERE id = ?')->execute([$newVal, $targetId]);
                $actionMsg = $newVal ? 'Admin access granted.' : 'Admin access removed.';
            }
        } else {
            $actionMsg = 'You cannot remove your own admin access.';
        }
    }
    if ($_POST['action'] === 'delete_user' && !empty($_POST['user_id'])) {
        $db->prepare('DELETE FROM users WHERE id = ?')->execute([$_POST['user_id']]);
        $actionMsg = "User deleted.";
    }
    if ($_POST['action'] === 'resend_verify' && !empty($_POST['user_id'])) {
        $db     = fi_db();
        $uStmt  = $db->prepare('SELECT name, email FROM users WHERE id = ? LIMIT 1');
        $uStmt->execute([$_POST['user_id']]);
        $u      = $uStmt->fetch();
        if ($u) {
            require_once __DIR__ . '/../api/lib/mailer.php';
            $token     = bin2hex(random_bytes(32));
            $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours'));
            $db->prepare('INSERT INTO email_tokens (token, user_id, expires_at) VALUES (?,?,?)')->execute([$token, $_POST['user_id'], $expiresAt]);
            $verifyUrl = rtrim(env('APP_URL'), '/') . '/api/auth/?action=verify&token=' . $token;
            $html = fi_email_verify_template($u['name'], $verifyUrl);
            fi_send_email($u['email'], $u['name'], 'Verify your Fiction Ignition account', $html);
            $actionMsg = "Verification email resent.";
        }
    }
}

// ── Fetch data ─────────────────────────────────────────────
$db = fi_db();

// Stats
$stats = [];
$stats['total_users']    = (int) $db->query("SELECT COUNT(*) FROM users")->fetchColumn();
$stats['verified_users'] = (int) $db->query("SELECT COUNT(*) FROM users WHERE email_verified = 1")->fetchColumn();
$stats['paid_users']     = (int) $db->query("SELECT COUNT(*) FROM users WHERE tier != 'free'")->fetchColumn();
$stats['active_subs']    = (int) $db->query("SELECT COUNT(*) FROM subscriptions WHERE status = 'active'")->fetchColumn();
$stats['prompts_today']  = (int) $db->query("SELECT COALESCE(SUM(count),0) FROM prompt_usage WHERE used_date = CURDATE()")->fetchColumn();
$stats['prompts_month']  = (int) $db->query("SELECT COALESCE(SUM(count),0) FROM prompt_usage WHERE used_date >= DATE_FORMAT(NOW(),'%Y-%m-01')")->fetchColumn();

// Tier breakdown
$tierCounts = $db->query("SELECT tier, COUNT(*) as cnt FROM users GROUP BY tier ORDER BY FIELD(tier,'free','starter','writer','author_pro')")->fetchAll();

// Users (with usage)
$search  = trim($_GET['search'] ?? '');
$tierFilter = $_GET['tier'] ?? '';
$page    = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page - 1) * $perPage;

$where  = ['1=1'];
$params = [];
if ($search) {
    $where[]  = '(u.name LIKE ? OR u.email LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($tierFilter && array_key_exists($tierFilter, TIERS)) {
    $where[]  = 'u.tier = ?';
    $params[] = $tierFilter;
}
$whereStr = implode(' AND ', $where);

$totalRows = (int) $db->prepare("SELECT COUNT(*) FROM users u WHERE $whereStr")->execute($params) ? $db->prepare("SELECT COUNT(*) FROM users u WHERE $whereStr")->execute($params) : 0;
$countStmt = $db->prepare("SELECT COUNT(*) FROM users u WHERE $whereStr");
$countStmt->execute($params);
$totalRows = (int) $countStmt->fetchColumn();
$totalPages = max(1, (int) ceil($totalRows / $perPage));

$usersStmt = $db->prepare("
    SELECT u.id, u.name, u.email, u.tier, u.email_verified, u.isAdmin, u.created_at,
           COALESCE(s.status, '—') as sub_status,
           COALESCE(s.plan_key, '—') as plan_key,
           COALESCE(s.current_period_end, NULL) as period_end,
           COALESCE((SELECT SUM(pu.count) FROM prompt_usage pu WHERE pu.user_id = u.id AND pu.used_date = CURDATE()), 0) as prompts_today,
           COALESCE((SELECT SUM(pu.count) FROM prompt_usage pu WHERE pu.user_id = u.id), 0) as prompts_total
    FROM users u
    LEFT JOIN subscriptions s ON s.user_id = u.id
    WHERE $whereStr
    ORDER BY u.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$usersStmt->execute($params);
$users = $usersStmt->fetchAll();

// Recent webhook events
$recentEvents = $db->query("SELECT event_type, processed, created_at FROM webhook_events ORDER BY created_at DESC LIMIT 10")->fetchAll();

$tierColors = ['free' => '#8a7458', 'starter' => '#e8610a', 'writer' => '#1b2e5e', 'author_pro' => '#5a1a8a'];
$tierBgs    = ['free' => '#f0ede8', 'starter' => '#fff3e0', 'writer' => '#e8f0fe', 'author_pro' => '#f3e8ff'];

?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fiction Ignition — Admin</title>
<style>
  :root {
    --navy:#1b2e5e; --navy-dark:#111e40; --orange:#e8610a;
    --parchment:#faf6f0; --white:#fff; --border:rgba(27,46,94,.15);
    --font-ui:'Segoe UI',Arial,sans-serif;
  }
  *, *::before, *::after { box-sizing:border-box; margin:0; padding:0; }
  body { font-family:var(--font-ui); background:#f0f2f7; color:#1a2440; font-size:14px; }
  a { color:var(--orange); text-decoration:none; }
  a:hover { text-decoration:underline; }

  /* ── Header ── */
  .admin-header { background:var(--navy); padding:0 2rem; height:58px; display:flex; align-items:center; justify-content:space-between; position:sticky; top:0; z-index:10; box-shadow:0 2px 12px rgba(0,0,0,.2); }
  .admin-logo { display:flex; align-items:center; gap:.6rem; color:#fff; font-size:1.05rem; font-weight:700; }
  .admin-logo img { height:34px; }
  .admin-user { font-size:.82rem; color:rgba(255,255,255,.7); display:flex; align-items:center; gap:1rem; }
  .admin-user a { color:rgba(255,255,255,.6); font-size:.8rem; }

  /* ── Layout ── */
  .admin-main { max-width:1400px; margin:0 auto; padding:1.75rem 2rem; }
  h1 { font-size:1.5rem; font-weight:700; color:var(--navy); margin-bottom:1.5rem; }
  h2 { font-size:1rem; font-weight:600; color:var(--navy); margin-bottom:1rem; }

  /* ── Stats grid ── */
  .stats-grid { display:grid; grid-template-columns:repeat(6,1fr); gap:1rem; margin-bottom:2rem; }
  .stat-card { background:#fff; border:1px solid var(--border); border-radius:10px; padding:1.1rem 1.25rem; }
  .stat-val { font-size:1.75rem; font-weight:700; color:var(--navy); line-height:1; margin-bottom:.3rem; }
  .stat-val.orange { color:var(--orange); }
  .stat-label { font-size:.72rem; font-weight:500; letter-spacing:.05em; text-transform:uppercase; color:#8a9ab0; }

  /* ── Tier breakdown ── */
  .tier-grid { display:flex; gap:.75rem; margin-bottom:2rem; flex-wrap:wrap; }
  .tier-chip { padding:.35rem 1rem; border-radius:20px; font-size:.82rem; font-weight:600; border:1px solid; }

  /* ── Card ── */
  .card { background:#fff; border:1px solid var(--border); border-radius:12px; overflow:hidden; margin-bottom:2rem; }
  .card-header { padding:1rem 1.5rem; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.75rem; }
  .card-header h2 { margin:0; }

  /* ── Filters ── */
  .filters { display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; }
  .filters input, .filters select {
    font-family:var(--font-ui); font-size:.85rem; padding:.45rem .8rem;
    border:1px solid var(--border); border-radius:6px; outline:none;
    transition:border-color .15s; background:#fff; color:#1a2440;
  }
  .filters input:focus, .filters select:focus { border-color:var(--orange); }
  .filters button {
    background:var(--orange); color:#fff; border:none; border-radius:6px;
    padding:.45rem 1rem; font-size:.85rem; font-weight:600; cursor:pointer;
  }

  /* ── Table ── */
  .data-table { width:100%; border-collapse:collapse; }
  .data-table thead th { background:#f5f7fc; font-size:.72rem; font-weight:700; letter-spacing:.06em; text-transform:uppercase; color:#6a7a9a; padding:.7rem 1rem; text-align:left; border-bottom:1px solid var(--border); white-space:nowrap; }
  .data-table tbody td { padding:.75rem 1rem; border-bottom:1px solid rgba(27,46,94,.07); vertical-align:middle; font-size:.85rem; }
  .data-table tbody tr:last-child td { border-bottom:none; }
  .data-table tbody tr:hover { background:#fafbff; }

  /* ── Tier badge ── */
  .tbadge { display:inline-block; padding:.18rem .6rem; border-radius:20px; font-size:.7rem; font-weight:700; letter-spacing:.04em; text-transform:uppercase; border:1px solid; }

  /* ── Verified badge ── */
  .vbadge { font-size:.72rem; font-weight:600; padding:.15rem .5rem; border-radius:20px; }
  .vbadge.yes { background:#e8f5ee; color:#2e7d4a; border:1px solid #a8dfc0; }
  .vbadge.no  { background:#fff0ee; color:#c04d06; border:1px solid #f5c8c0; }

  /* ── Actions ── */
  .row-actions { display:flex; gap:.35rem; align-items:center; }
  .action-btn {
    font-family:var(--font-ui); font-size:.75rem; font-weight:500;
    padding:.3rem .7rem; border-radius:5px; border:1px solid var(--border);
    background:#fff; cursor:pointer; color:#4a5a7a; transition:all .15s; white-space:nowrap;
  }
  .action-btn:hover { border-color:var(--orange); color:var(--orange); }
  .action-btn.danger:hover { border-color:#c04d06; color:#c04d06; }

  /* ── Tier select in row ── */
  .tier-select { font-size:.8rem; padding:.25rem .5rem; border:1px solid var(--border); border-radius:5px; background:#fff; color:#1a2440; cursor:pointer; }

  /* ── Pagination ── */
  .pagination { display:flex; align-items:center; gap:.4rem; padding:1rem 1.5rem; justify-content:flex-end; }
  .pg-btn { padding:.35rem .75rem; border:1px solid var(--border); border-radius:6px; font-size:.82rem; color:#4a5a7a; text-decoration:none; background:#fff; transition:all .15s; }
  .pg-btn:hover { border-color:var(--orange); color:var(--orange); text-decoration:none; }
  .pg-btn.active { background:var(--navy); color:#fff; border-color:var(--navy); }

  /* ── Action message ── */
  .action-msg { background:#e8f5ee; border:1px solid #a8dfc0; border-radius:8px; color:#2e7d4a; padding:.75rem 1.1rem; margin-bottom:1.5rem; font-weight:500; }

  /* ── Events log ── */
  .event-row { display:flex; align-items:center; gap:1rem; padding:.6rem 1rem; border-bottom:1px solid rgba(27,46,94,.06); font-size:.82rem; }
  .event-row:last-child { border-bottom:none; }
  .event-type { font-family:'Courier New',monospace; background:#f0f2f7; padding:.15rem .5rem; border-radius:4px; color:var(--navy); font-size:.78rem; }
  .event-dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }
  .event-dot.ok  { background:#2e7d4a; }
  .event-dot.pend { background:#e8610a; }

  .action-btn.admin-on  { background:#f3e8ff; border-color:#9a4dd0; color:#6a1fa0; font-weight:600; }
  .action-btn.admin-on:hover  { background:#e8d0ff; border-color:#6a1fa0; }
  .action-btn.admin-off { color:#c0ccd8; border-color:#dde3ee; }
  .action-btn.admin-off:hover { border-color:var(--orange); color:var(--orange); }

  @media (max-width:1100px) { .stats-grid { grid-template-columns:repeat(3,1fr); } }
  @media (max-width:700px)  { .stats-grid { grid-template-columns:repeat(2,1fr); } .admin-main { padding:1rem; } }
</style>
</head>
<body>

<header class="admin-header">
  <div class="admin-logo">
    <img src="../images/FictionIgnitionIcon.png" alt="FI" />
    Fiction Ignition <span style="font-size:.72rem;font-weight:400;color:rgba(255,255,255,.5);margin-left:.35rem">Admin</span>
  </div>
  <div class="admin-user">
    Signed in as <strong style="color:#fff"><?= htmlspecialchars($session['email']) ?></strong>
    <a href="<?= rtrim(env('APP_URL'),'/') ?>/index.html">← Site</a>
    <a href="#" onclick="fetch('../api/auth/?action=logout',{method:'POST',credentials:'include'}).then(()=>location.href='../index.html')">Sign Out</a>
  </div>
</header>

<main class="admin-main">
  <h1>Dashboard</h1>

  <?php if ($actionMsg): ?>
  <div class="action-msg">✓ <?= htmlspecialchars($actionMsg) ?></div>
  <?php endif; ?>

  <!-- Stats -->
  <div class="stats-grid">
    <div class="stat-card"><div class="stat-val"><?= number_format($stats['total_users']) ?></div><div class="stat-label">Total Users</div></div>
    <div class="stat-card"><div class="stat-val"><?= number_format($stats['verified_users']) ?></div><div class="stat-label">Verified</div></div>
    <div class="stat-card"><div class="stat-val orange"><?= number_format($stats['paid_users']) ?></div><div class="stat-label">Paid Users</div></div>
    <div class="stat-card"><div class="stat-val orange"><?= number_format($stats['active_subs']) ?></div><div class="stat-label">Active Subs</div></div>
    <div class="stat-card"><div class="stat-val"><?= number_format($stats['prompts_today']) ?></div><div class="stat-label">Prompts Today</div></div>
    <div class="stat-card"><div class="stat-val"><?= number_format($stats['prompts_month']) ?></div><div class="stat-label">Prompts This Month</div></div>
  </div>

  <!-- Tier breakdown -->
  <div class="tier-grid">
    <?php foreach ($tierCounts as $tc): ?>
    <div class="tier-chip" style="background:<?= $tierBgs[$tc['tier']] ?? '#eee' ?>;color:<?= $tierColors[$tc['tier']] ?? '#555' ?>;border-color:<?= $tierColors[$tc['tier']] ?? '#ccc' ?>">
      <?= htmlspecialchars(TIERS[$tc['tier']]['label'] ?? $tc['tier']) ?>: <strong><?= $tc['cnt'] ?></strong>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- Users table -->
  <div class="card">
    <div class="card-header">
      <h2>Users (<?= number_format($totalRows) ?>)</h2>
      <form method="GET" class="filters">
        <input type="text" name="search" placeholder="Search name or email…" value="<?= htmlspecialchars($search) ?>" />
        <select name="tier">
          <option value="">All tiers</option>
          <?php foreach (TIERS as $tk => $tv): ?>
          <option value="<?= $tk ?>" <?= $tierFilter === $tk ? 'selected' : '' ?>><?= $tv['label'] ?></option>
          <?php endforeach; ?>
        </select>
        <button type="submit">Filter</button>
        <?php if ($search || $tierFilter): ?>
        <a href="?" style="font-size:.82rem;color:#8a9ab0;text-decoration:underline">Clear</a>
        <?php endif; ?>
      </form>
    </div>

    <table class="data-table">
      <thead>
        <tr>
          <th>Name</th><th>Email</th><th>Tier</th><th>Verified</th><th>Admin</th>
          <th>Subscription</th><th>Prompts Today</th><th>Total Prompts</th>
          <th>Joined</th><th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($users as $u): ?>
        <tr>
          <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
          <td style="color:#5a6a8a"><?= htmlspecialchars($u['email']) ?></td>
          <td>
            <span class="tbadge" style="background:<?= $tierBgs[$u['tier']] ?? '#eee' ?>;color:<?= $tierColors[$u['tier']] ?? '#555' ?>;border-color:<?= $tierColors[$u['tier']] ?? '#ccc' ?>">
              <?= htmlspecialchars(TIERS[$u['tier']]['label'] ?? $u['tier']) ?>
            </span>
          </td>
          <td>
            <span class="vbadge <?= $u['email_verified'] ? 'yes' : 'no' ?>">
              <?= $u['email_verified'] ? '✓ Yes' : '✗ No' ?>
            </span>
          </td>
          <td style="text-align:center">
            <?php if ($u['id'] === $session['id']): ?>
              <span class="vbadge yes" title="You — cannot remove your own admin">👑 You</span>
            <?php else: ?>
              <form method="POST" style="display:inline">
                <input type="hidden" name="action" value="toggle_admin" />
                <input type="hidden" name="user_id" value="<?= htmlspecialchars($u['id']) ?>" />
                <button type="submit" class="action-btn <?= $u['isAdmin'] ? 'admin-on' : 'admin-off' ?>"
                  title="<?= $u['isAdmin'] ? 'Remove admin' : 'Grant admin' ?>"
                  onclick="return confirm('<?= $u['isAdmin'] ? 'Remove admin access from ' : 'Grant admin access to ' ?><?= htmlspecialchars(addslashes($u['name'])) ?>?')">
                  <?= $u['isAdmin'] ? '👑 Admin' : '— User' ?>
                </button>
              </form>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($u['plan_key'] !== '—'): ?>
              <span style="font-size:.78rem">
                <?= htmlspecialchars($u['plan_key']) ?><br>
                <span style="color:<?= $u['sub_status'] === 'active' ? '#2e7d4a' : '#c04d06' ?>;font-weight:600"><?= $u['sub_status'] ?></span>
                <?php if ($u['period_end']): ?><br><span style="color:#8a9ab0">until <?= $u['period_end'] ?></span><?php endif; ?>
              </span>
            <?php else: ?>
              <span style="color:#c0ccd8;font-size:.8rem">—</span>
            <?php endif; ?>
          </td>
          <td style="text-align:center"><?= (int)$u['prompts_today'] ?></td>
          <td style="text-align:center"><?= number_format((int)$u['prompts_total']) ?></td>
          <td style="color:#8a9ab0;font-size:.78rem;white-space:nowrap"><?= date('M j, Y', strtotime($u['created_at'])) ?></td>
          <td>
            <div class="row-actions">
              <!-- Quick tier change -->
              <form method="POST" style="display:flex;align-items:center;gap:.3rem">
                <input type="hidden" name="action" value="set_tier" />
                <input type="hidden" name="user_id" value="<?= htmlspecialchars($u['id']) ?>" />
                <select name="tier" class="tier-select" onchange="this.form.submit()" title="Change tier">
                  <?php foreach (TIERS as $tk => $tv): ?>
                  <option value="<?= $tk ?>" <?= $u['tier'] === $tk ? 'selected' : '' ?>><?= $tv['label'] ?></option>
                  <?php endforeach; ?>
                </select>
              </form>

              <?php if (!$u['email_verified']): ?>
              <form method="POST">
                <input type="hidden" name="action" value="resend_verify" />
                <input type="hidden" name="user_id" value="<?= htmlspecialchars($u['id']) ?>" />
                <button type="submit" class="action-btn" title="Resend verification email">📧 Resend</button>
              </form>
              <?php endif; ?>

              <form method="POST" onsubmit="return confirm('Delete this user? This cannot be undone.')">
                <input type="hidden" name="action" value="delete_user" />
                <input type="hidden" name="user_id" value="<?= htmlspecialchars($u['id']) ?>" />
                <button type="submit" class="action-btn danger" title="Delete user">✕</button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($users)): ?>
        <tr><td colspan="10" style="text-align:center;padding:2rem;color:#8a9ab0;font-style:italic">No users found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div class="pagination">
      <span style="font-size:.82rem;color:#8a9ab0;margin-right:.5rem">Page <?= $page ?> of <?= $totalPages ?></span>
      <?php for ($p = 1; $p <= $totalPages; $p++): ?>
        <?php
          $params2 = array_filter(['search' => $search, 'tier' => $tierFilter, 'page' => $p]);
          $qs = http_build_query($params2);
        ?>
        <a href="?<?= $qs ?>" class="pg-btn <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
      <?php endfor; ?>
    </div>
    <?php endif; ?>
  </div>

  <!-- Webhook events -->
  <div class="card">
    <div class="card-header"><h2>Recent Webhook Events</h2></div>
    <?php if (empty($recentEvents)): ?>
    <p style="padding:1.5rem;color:#8a9ab0;font-style:italic">No webhook events yet. Configure your Square webhook URL.</p>
    <?php else: ?>
    <?php foreach ($recentEvents as $ev): ?>
    <div class="event-row">
      <div class="event-dot <?= $ev['processed'] ? 'ok' : 'pend' ?>"></div>
      <div class="event-type"><?= htmlspecialchars($ev['event_type']) ?></div>
      <div style="color:#8a9ab0;font-size:.78rem;margin-left:auto"><?= date('M j g:ia', strtotime($ev['created_at'])) ?></div>
      <div style="font-size:.75rem;font-weight:600;color:<?= $ev['processed'] ? '#2e7d4a' : '#e8610a' ?>"><?= $ev['processed'] ? 'Processed' : 'Pending' ?></div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- Setup notes -->
  <div style="background:#fff;border:1px solid var(--border);border-radius:12px;padding:1.5rem;margin-top:1rem">
    <h2 style="margin-bottom:.75rem">⚙️ Square Webhook Setup Reminder</h2>
    <p style="font-size:.88rem;color:#5a6a8a;line-height:1.7">
      In Square Developer Dashboard → Your App → Webhooks → Add Webhook:<br>
      <code style="background:#f0f2f7;padding:.15rem .4rem;border-radius:4px;font-size:.85em"><?= rtrim(env('APP_URL'),'/') ?>/api/webhook/square.php</code><br><br>
      Subscribe to: <strong>subscription.activated, subscription.updated, subscription.deactivated</strong>
    </p>
  </div>
</main>

</body>
</html>
