<?php
/* Shared "auto-configure Visitor analytics" card for the deliverable pages.
   Vars in scope: $which ('marketing'|'community'), $baseUrl, $analytics, and a
   CSRF token in $csrf or $token.

   The Site ID is chosen from the REGISTERED properties (AnalyticsSites), never
   free-typed — so the id baked into the download is always one the collector
   knows. "Auto-create & link" mints and wires a property in one click. This closes
   the old two-registry gap where a typed/stale id silently 404'd at the collector. */
$daToken = $csrf ?? ($token ?? '');
$daChan  = (($which ?? 'marketing') === 'marketing') ? 'marketing' : 'community';
$daIsMk  = $daChan === 'marketing';
$daSite  = $daIsMk ? ($analytics['marketing_site'] ?? '') : ($analytics['community_site'] ?? '');
$daE     = static fn ($s): string => htmlspecialchars((string) $s, ENT_QUOTES);
$daAgo   = static function (int $ts): string {
    if ($ts <= 0) return 'never';
    $s = time() - $ts;
    if ($s < 60) return 'just now';
    if ($s < 3600) return intdiv($s, 60) . 'm ago';
    if ($s < 86400) return intdiv($s, 3600) . 'h ago';
    return intdiv($s, 86400) . 'd ago';
};
// Registered properties for this channel (+ any 'app' properties are also valid targets).
$daSites = [];
try {
    foreach (\PpPhp\Core\Analytics\AnalyticsSites::all() as $id => $s) {
        if (($s['channel'] ?? '') === $daChan || ($s['channel'] ?? '') === 'app') $daSites[(string) $id] = $s;
    }
} catch (\Throwable $e) { /* no DB yet */ }
$daLinked   = $daSite !== '' ? ($daSites[$daSite] ?? null) : null;
$daOrphan   = $daSite !== '' && $daLinked === null;   // baked id isn't a registered property (the classic mismatch)
?>
<div class="ppb-card mt-3">
  <div class="p-3 p-md-4">
    <h6 class="fw-bold mb-1"><i class="bi bi-graph-up-arrow me-1"></i> Visitor analytics — auto-configure</h6>
    <p class="text-muted small mb-3">Pick this property from your registered
      <a href="<?= $daE(rtrim((string) $baseUrl, '/')) ?>/platform/visitors" target="_blank">Visitors &rarr; Properties</a>,
      or auto-create one. Every download from this page then ships with the analytics beacon
      <strong>already wired</strong> to a valid Site&nbsp;ID &mdash; a fresh install reports in with nothing to configure by hand.</p>
    <div class="row g-2 align-items-end">
      <div class="col-md-4">
        <label class="form-label small mb-1"><?= $daIsMk ? 'Marketing' : 'Community' ?> property</label>
        <select id="daSite" class="form-select form-select-sm">
          <option value=""<?= $daSite === '' ? ' selected' : '' ?>>— not wired (off) —</option>
          <?php foreach ($daSites as $id => $s): ?>
            <option value="<?= $daE($id) ?>"<?= $id === $daSite ? ' selected' : '' ?>><?= $daE($s['label']) ?> (<?= $daE($id) ?>)</option>
          <?php endforeach; ?>
          <?php if ($daOrphan): ?>
            <option value="<?= $daE($daSite) ?>" selected>⚠ <?= $daE($daSite) ?> — not registered</option>
          <?php endif; ?>
          <option value="auto">➕ Auto-create &amp; link a <?= $daChan ?> property</option>
        </select>
      </div>
      <div class="col-md-6">
        <label class="form-label small mb-1">Collector URL <span class="text-muted">(blank = main licence server)</span></label>
        <input type="url" id="daCollector" class="form-control form-control-sm" placeholder="https://ppphp.ppradhan.com/api/analytics/collect" value="<?= $daE($analytics['collector'] ?? '') ?>">
      </div>
      <div class="col-md-2">
        <button id="daSave" class="btn btn-sm btn-outline-primary w-100"><i class="bi bi-check-lg"></i> Save</button>
      </div>
    </div>
    <?php if ($daOrphan): ?>
      <p class="small text-danger mt-2 mb-0"><i class="bi bi-exclamation-triangle-fill me-1"></i>
        <code><?= $daE($daSite) ?></code> isn't a registered property — the collector will reject its events. Pick a property above or choose <em>Auto-create</em>, then Save.</p>
    <?php elseif ($daLinked !== null): ?>
      <p class="small mt-2 mb-0 <?= (int) ($daLinked['last_seen'] ?? 0) > 0 ? 'text-success' : 'text-muted' ?>">
        <i class="bi bi-<?= (int) ($daLinked['last_seen'] ?? 0) > 0 ? 'check-circle-fill' : 'clock-history' ?> me-1"></i>
        Auto-wired to <code><?= $daE($daSite) ?></code> · last report received:
        <strong><?= $daE($daAgo((int) ($daLinked['last_seen'] ?? 0))) ?></strong><?= (int) ($daLinked['last_seen'] ?? 0) === 0 ? ' — publish/deploy this property, then reload' : '' ?>.</p>
    <?php endif; ?>
  </div>
</div>
<script>
(function () {
  var btn = document.getElementById('daSave');
  if (!btn) return;
  btn.addEventListener('click', function () {
    var body = {
      _token: <?= json_encode($daToken) ?>,
      collector: document.getElementById('daCollector').value.trim(),
      <?= $daIsMk ? 'marketing_site' : 'community_site' ?>: document.getElementById('daSite').value
    };
    fetch(<?= json_encode(rtrim((string) $baseUrl, '/') . '/platform/deliverables/analytics') ?>, {
      method: 'POST', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
    }).then(function (r) { return r.json(); }).then(function (j) {
      if (window.Swal) Swal.fire({ icon: j.success ? 'success' : 'error',
        title: j.success ? 'Saved — downloads are now auto-wired' : 'Could not save',
        text: j.success && j.created ? 'A new property was created and linked.' : undefined,
        timer: j.success ? 1700 : undefined, showConfirmButton: !j.success }).then(function () { if (j.success) location.reload(); });
      else { alert(j.success ? 'Saved' : 'Could not save'); if (j.success) location.reload(); }
    }).catch(function () { if (window.Swal) Swal.fire({ icon: 'error', title: 'Could not save' }); else alert('Could not save'); });
  });
})();
</script>
