<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = 'Mi pipeline';
$sellerNav  = 'tenants';

$statusLabel = fn($s) => match($s) {
    'active'   => ['active',   'Activo'],
    'trial'    => ['trial',    'Trial'],
    'past_due' => ['past_due', 'Vencido'],
    'canceled' => ['canceled', 'Cancelado'],
    default    => ['free',     'Free'],
};

ob_start();
?>

<div class="kpi-row">
  <div class="kpi"><div class="kv"><?= count($tenants) ?></div><div class="kl">Negocios totales</div></div>
  <div class="kpi"><div class="kv"><?= $activos ?></div><div class="kl">Activos</div></div>
  <div class="kpi"><div class="kv">$<?= number_format($totalMrr, 0) ?></div><div class="kl">MRR generado</div></div>
  <div class="kpi"><div class="kv">$<?= number_format($pendComm, 2) ?></div><div class="kl">Comisiones pendientes</div></div>
</div>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem">
  <h3 style="font-family:var(--font-headings);margin:0;font-size:1.05rem">Negocios en mi pipeline</h3>
  <button class="btn btn-primary" style="font-size:.82rem;padding:.5rem 1rem" onclick="document.getElementById('modalActivar').classList.add('open')">
    + Activar negocio
  </button>
</div>

<table class="tbl">
  <thead>
    <tr>
      <th>Negocio</th>
      <th>Plan</th>
      <th>Estado</th>
      <th>MRR</th>
      <th>Vence</th>
      <th>Dueño</th>
      <th>Acción</th>
    </tr>
  </thead>
  <tbody>
    <?php if (empty($tenants)): ?>
      <tr><td colspan="7" style="text-align:center;padding:2rem;color:var(--color-text-muted)">Sin negocios todavía.</td></tr>
    <?php else: foreach ($tenants as $t):
        [$cls, $lbl] = $statusLabel($t['billing_status'] ?? 'free');
    ?>
      <tr>
        <td>
          <div style="font-weight:700"><?= htmlspecialchars($t['name']) ?></div>
          <div style="font-size:.75rem;color:var(--color-text-muted)">#<?= (int)$t['id'] ?></div>
        </td>
        <td><span style="font-weight:700;text-transform:uppercase;font-size:.78rem"><?= htmlspecialchars($t['plan'] ?? 'free') ?></span></td>
        <td><span class="badge badge-<?= $cls ?>"><?= $lbl ?></span></td>
        <td><?= $t['mrr'] > 0 ? '$'.number_format($t['mrr'],0) : '—' ?></td>
        <td style="font-size:.8rem"><?= $t['current_period_end'] ? date('d/m/Y', strtotime($t['current_period_end'])) : '—' ?></td>
        <td>
          <div style="font-size:.8rem"><?= htmlspecialchars($t['owner_name'] ?? '—') ?></div>
          <div style="font-size:.72rem;color:var(--color-text-muted)"><?= htmlspecialchars($t['owner_email'] ?? '') ?></div>
        </td>
        <td>
          <?php if (in_array($t['billing_status'] ?? 'free', ['free','past_due','canceled'])): ?>
            <button class="btn btn-primary" style="font-size:.75rem;padding:.35rem .8rem"
              onclick="openActivar(<?= (int)$t['id'] ?>, '<?= htmlspecialchars($t['name'], ENT_QUOTES) ?>')">
              Activar
            </button>
          <?php else: ?>
            <span style="font-size:.75rem;color:var(--color-text-muted)">Activo</span>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; endif; ?>
  </tbody>
</table>

<!-- Modal activar en cash -->
<div class="modal-bg" id="modalActivar">
  <div class="modal">
    <h3>Activar negocio</h3>
    <form method="POST" action="/seller/activate">
      <input type="hidden" name="tenant_id" id="activarTenantId">
      <label>Negocio: <strong id="activarTenantName" style="color:var(--color-barro)"></strong></label>
      <label>Plan
        <select name="plan">
          <option value="basic">Basic — $55/mes</option>
          <option value="premium">Premium — $95/mes</option>
        </select>
      </label>
      <label>Meses pagados
        <input type="number" name="meses" value="1" min="1" max="24">
      </label>
      <div class="actions">
        <button type="submit" class="btn btn-primary">Confirmar activación</button>
        <button type="button" class="btn btn-ghost" onclick="document.getElementById('modalActivar').classList.remove('open')">Cancelar</button>
      </div>
    </form>
  </div>
</div>

<script>
function openActivar(id, name) {
  document.getElementById('activarTenantId').value = id;
  document.getElementById('activarTenantName').textContent = name;
  document.getElementById('modalActivar').classList.add('open');
}
document.getElementById('modalActivar').addEventListener('click', function(e) {
  if (e.target === this) this.classList.remove('open');
});
</script>

<?php
$content = ob_get_clean();
require __DIR__ . '/layout.php';
