<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = 'Vale Admin — Dashboard';
ob_start();
?>
<style>
/* ── Design tokens (dashboard-scope) ───────────────────────── */
.dash {
  --dk-bg:       #F6F0E6;
  --dk-surface:  #FFFFFF;
  --dk-terra:    #A23D2C;
  --dk-ink:      #211C16;
  --dk-muted:    #8C8275;
  --dk-hairline: #E6DDCE;
  --dk-green:    #1E7A4D;
  --dk-amber:    #B8760A;
}

/* Hero metrics */
.kpi-hero {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0;
  background: var(--dk-surface);
  border: 1px solid var(--dk-hairline);
  border-radius: 14px;
  margin-bottom: 1.75rem;
  overflow: hidden;
}
.kpi-hero-cell {
  padding: 1.5rem 1.75rem;
  border-right: 1px solid var(--dk-hairline);
}
.kpi-hero-cell:last-child { border-right: none; }
.kpi-label {
  font-size: .72rem;
  font-weight: 600;
  letter-spacing: .06em;
  color: var(--dk-muted);
  text-transform: none;
  margin-bottom: .35rem;
}
.kpi-number {
  font-family: 'Fraunces', Georgia, serif;
  font-weight: 400;
  font-size: 2.6rem;
  line-height: 1;
  color: var(--dk-ink);
}
.kpi-number.accent  { color: var(--dk-terra); }
.kpi-number.muted   { color: var(--dk-muted); }
.kpi-sub {
  font-size: .72rem;
  color: var(--dk-muted);
  margin-top: .3rem;
}

/* Secondary strip */
.kpi-strip {
  display: flex;
  gap: 0;
  background: var(--dk-surface);
  border: 1px solid var(--dk-hairline);
  border-radius: 10px;
  margin-bottom: 1.75rem;
  overflow: hidden;
}
.kpi-strip-cell {
  flex: 1;
  padding: .85rem 1.25rem;
  border-right: 1px solid var(--dk-hairline);
  min-width: 0;
}
.kpi-strip-cell:last-child { border-right: none; }
.kpi-strip-label {
  font-size: .68rem;
  color: var(--dk-muted);
  font-weight: 600;
  margin-bottom: .2rem;
}
.kpi-strip-val {
  font-size: 1.1rem;
  font-family: 'Fraunces', Georgia, serif;
  font-weight: 400;
  color: var(--dk-ink);
}

/* Panels */
.dash-grid-2 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.25rem;
  margin-bottom: 1.25rem;
}
.dash-panel {
  background: var(--dk-surface);
  border: 1px solid var(--dk-hairline);
  border-radius: 12px;
  padding: 1.4rem 1.5rem;
}
.dash-panel-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: .75rem;
  border-bottom: 1px solid var(--dk-hairline);
}
.dash-panel-title {
  font-size: .88rem;
  font-weight: 700;
  color: var(--dk-ink);
}
.dash-panel-link {
  font-size: .75rem;
  color: var(--dk-terra);
  font-weight: 600;
  text-decoration: none;
}
.dash-panel-link:hover { text-decoration: underline; }

/* List rows */
.biz-row {
  display: flex;
  align-items: center;
  gap: .75rem;
  padding: .6rem 0;
  border-bottom: 1px solid var(--dk-hairline);
}
.biz-row:last-child { border-bottom: none; }
.biz-dot {
  width: 6px; height: 6px;
  border-radius: 50%;
  flex-shrink: 0;
  background: var(--dk-hairline);
}
.biz-dot.live   { background: var(--dk-green); }
.biz-dot.config { background: var(--dk-amber); }
.biz-name {
  flex: 1;
  font-size: .84rem;
  font-weight: 600;
  color: var(--dk-ink);
  text-decoration: none;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.biz-name:hover { color: var(--dk-terra); }
.biz-meta {
  font-size: .72rem;
  color: var(--dk-muted);
}
.plan-badge {
  font-size: .68rem;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 99px;
  background: #F0EAE2;
  color: var(--dk-muted);
  flex-shrink: 0;
}
.plan-badge.active {
  background: rgba(30,122,77,.1);
  color: var(--dk-green);
}

/* Empty state */
.empty-state {
  padding: 1.5rem 0;
  text-align: center;
  color: var(--dk-muted);
  font-size: .85rem;
}
.empty-cta {
  display: inline-block;
  margin-top: .6rem;
  font-size: .8rem;
  font-weight: 700;
  color: var(--dk-terra);
  text-decoration: none;
}
.empty-cta:hover { text-decoration: underline; }

/* Bar chart */
.bar-row { margin-bottom: .75rem; }
.bar-row:last-child { margin-bottom: 0; }
.bar-labels {
  display: flex;
  justify-content: space-between;
  font-size: .78rem;
  margin-bottom: .25rem;
}
.bar-track {
  background: #F0EAE2;
  border-radius: 99px;
  height: 5px;
}
.bar-fill {
  border-radius: 99px;
  height: 5px;
  background: var(--dk-terra);
}

/* Error badge */
.err-badge {
  background: rgba(162,61,44,.08);
  color: var(--dk-terra);
  border-radius: 6px;
  padding: 2px 7px;
  font-size: .68rem;
  font-weight: 700;
}

/* Alert strip */
.alert-strip {
  display: flex;
  align-items: center;
  gap: .6rem;
  background: rgba(184,118,10,.07);
  border: 1px solid rgba(184,118,10,.25);
  border-radius: 8px;
  padding: .65rem 1rem;
  font-size: .82rem;
  color: var(--dk-amber);
  margin-bottom: 1.75rem;
}
</style>

<div class="dashboard-container dash">
    <?php $adminNav = 'dashboard'; require __DIR__ . '/sidebar.php'; ?>

    <main class="main-content">
        <header class="header-bar">
            <h2>Dashboard</h2>
            <span style="font-size:.78rem;color:var(--dk-muted);">Actualizado <?= date('d M Y · H:i') ?></span>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;">

            <?php if ((int)($kpi['sin_rubro'] ?? 0) > 0): ?>
            <div class="alert-strip">
                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01" stroke-linecap="round"/></svg>
                <span><strong><?= (int)$kpi['sin_rubro'] ?> negocio<?= $kpi['sin_rubro'] > 1 ? 's' : '' ?> sin rubro</strong> — sin rubro el agente trabaja sin contexto.</span>
                <a href="/admin/tenants" style="margin-left:auto;font-weight:700;color:var(--dk-amber);font-size:.78rem;text-decoration:none;">Asignar →</a>
            </div>
            <?php endif; ?>

            <!-- Hero KPIs -->
            <div class="kpi-hero">
                <div class="kpi-hero-cell">
                    <div class="kpi-label">Operativos · Live</div>
                    <div class="kpi-number <?= (int)$kpi['live_count'] > 0 ? 'accent' : 'muted' ?>"><?= (int)$kpi['live_count'] ?></div>
                    <div class="kpi-sub">de <?= (int)$kpi['total'] ?> negocios totales</div>
                </div>
                <div class="kpi-hero-cell">
                    <div class="kpi-label">Nuevos este mes</div>
                    <div class="kpi-number"><?= (int)$kpi['nuevos_mes'] ?></div>
                    <div class="kpi-sub">registros en <?= date('F') ?></div>
                </div>
                <div class="kpi-hero-cell">
                    <div class="kpi-label">MRR total</div>
                    <div class="kpi-number <?= (float)$kpi['mrr'] > 0 ? 'accent' : 'muted' ?>">$<?= number_format((float)$kpi['mrr'], 0) ?></div>
                    <div class="kpi-sub"><?= (int)$kpi['activos'] ?> de pago · <?= (int)$kpi['past_due'] ?> vencido<?= $kpi['past_due'] != 1 ? 's' : '' ?></div>
                </div>
            </div>

            <!-- Secondary strip -->
            <div class="kpi-strip">
                <?php
                $strip = [
                    ['De pago',      (int)$kpi['activos']],
                    ['Trial',        (int)$kpi['trial']],
                    ['Free',         (int)$kpi['free_count']],
                    ['Past due',     (int)$kpi['past_due']],
                    ['Convos/mes',   number_format((int)$kpi['convos_mes'])],
                    ['Tokens/mes',   number_format((int)$kpi['tokens_mes'])],
                ];
                foreach ($strip as [$lbl, $val]):
                ?>
                <div class="kpi-strip-cell">
                    <div class="kpi-strip-label"><?= $lbl ?></div>
                    <div class="kpi-strip-val"><?= $val ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Distribución -->
            <div class="dash-grid-2">

                <div class="dash-panel">
                    <div class="dash-panel-head">
                        <span class="dash-panel-title">Por plan</span>
                    </div>
                    <?php if (empty($byPlan)): ?>
                    <div class="empty-state">Sin datos aún.</div>
                    <?php else: foreach ($byPlan as $row):
                        $pct = $kpi['total'] > 0 ? round($row['cnt'] / $kpi['total'] * 100) : 0; ?>
                    <div class="bar-row">
                        <div class="bar-labels">
                            <span style="font-weight:600;font-size:.8rem;text-transform:capitalize;"><?= htmlspecialchars($row['plan']) ?></span>
                            <span style="color:var(--dk-muted);font-size:.78rem;"><?= $row['cnt'] ?> · $<?= number_format($row['mrr'], 0) ?>/mes</span>
                        </div>
                        <div class="bar-track"><div class="bar-fill" style="width:<?= $pct ?>%"></div></div>
                    </div>
                    <?php endforeach; endif; ?>
                </div>

                <div class="dash-panel">
                    <div class="dash-panel-head">
                        <span class="dash-panel-title">Por rubro</span>
                    </div>
                    <?php if (empty($byRubro)): ?>
                    <div class="empty-state">Sin datos aún.</div>
                    <?php else: foreach ($byRubro as $row):
                        $pct = $kpi['total'] > 0 ? round($row['cnt'] / $kpi['total'] * 100) : 0; ?>
                    <div class="bar-row">
                        <div class="bar-labels">
                            <span style="font-weight:600;font-size:.8rem;text-transform:capitalize;"><?= htmlspecialchars($row['rubro'] ?: 'Sin rubro') ?></span>
                            <span style="color:var(--dk-muted);font-size:.78rem;"><?= $row['cnt'] ?></span>
                        </div>
                        <div class="bar-track"><div class="bar-fill" style="width:<?= $pct ?>%;background:#8C8275;"></div></div>
                    </div>
                    <?php endforeach; endif; ?>
                </div>

            </div>

            <!-- Últimos negocios + Top vendedores -->
            <div class="dash-grid-2">

                <div class="dash-panel">
                    <div class="dash-panel-head">
                        <span class="dash-panel-title">Últimos negocios</span>
                        <a href="/admin/tenants" class="dash-panel-link">Ver todos →</a>
                    </div>
                    <?php if (empty($recentTenants)): ?>
                    <div class="empty-state">
                        Sin negocios aún.
                        <br><a href="/admin/tenants" class="empty-cta">Crear primer negocio →</a>
                    </div>
                    <?php else: foreach ($recentTenants as $t):
                        $isLive = ($t['billing_status'] === 'active' || ($t['onboarding_status'] ?? '') === 'live');
                        $isConf = !$isLive && !empty($t['onboarding_status']);
                    ?>
                    <div class="biz-row">
                        <div class="biz-dot <?= $isLive ? 'live' : ($isConf ? 'config' : '') ?>"></div>
                        <a href="/admin/tenant?id=<?= $t['id'] ?>" class="biz-name"><?= htmlspecialchars($t['name']) ?></a>
                        <span class="biz-meta"><?= htmlspecialchars($t['rubro'] ?: 'Sin rubro') ?></span>
                        <span class="plan-badge <?= $t['billing_status'] === 'active' ? 'active' : '' ?>"><?= htmlspecialchars($t['plan']) ?></span>
                    </div>
                    <?php endforeach; endif; ?>
                </div>

                <div class="dash-panel">
                    <div class="dash-panel-head">
                        <span class="dash-panel-title">Top vendedores</span>
                        <a href="/admin/sellers" class="dash-panel-link">Ver todos →</a>
                    </div>
                    <?php if (empty($topSellers)): ?>
                    <div class="empty-state">
                        Sin vendedores aún.
                        <br><a href="/admin/sellers" class="empty-cta">Agregar primer vendedor →</a>
                    </div>
                    <?php else: foreach ($topSellers as $s): ?>
                    <div class="biz-row">
                        <div class="biz-dot live"></div>
                        <span class="biz-name" style="text-decoration:none;cursor:default;"><?= htmlspecialchars($s['nombre']) ?></span>
                        <span class="biz-meta"><?= $s['activos'] ?> activos</span>
                        <span style="font-size:.84rem;font-weight:700;font-family:'Fraunces',serif;color:var(--dk-terra);">$<?= number_format($s['mrr'], 0) ?></span>
                    </div>
                    <?php endforeach; endif; ?>
                </div>

            </div>

            <!-- WhatsApp Test -->
            <div class="dash-panel" id="wa-test" style="margin-bottom:1.25rem;">
                <div class="dash-panel-head">
                    <span class="dash-panel-title">Probar WhatsApp Business</span>
                    <?php if (!empty($dashWaTenants)): ?>
                    <span style="font-size:.72rem;color:var(--dk-green);font-weight:600;">
                        <?= count($dashWaTenants) ?> número<?= count($dashWaTenants) > 1 ? 's' : '' ?> configurado<?= count($dashWaTenants) > 1 ? 's' : '' ?>
                    </span>
                    <?php endif; ?>
                </div>

                <?php if ($dashWaResult !== null): ?>
                <?php if (!empty($dashWaResult['ok'])): ?>
                <div style="background:rgba(30,122,77,.07);border:1px solid rgba(30,122,77,.2);border-radius:8px;padding:.75rem 1rem;margin-bottom:1rem;font-size:.84rem;color:var(--dk-green);">
                    Mensaje enviado · ID: <code style="font-size:.78rem;"><?= htmlspecialchars($dashWaResult['message_id'] ?? '–') ?></code>
                </div>
                <?php else: ?>
                <div style="background:rgba(162,61,44,.07);border:1px solid rgba(162,61,44,.2);border-radius:8px;padding:.75rem 1rem;margin-bottom:1rem;font-size:.84rem;color:var(--dk-terra);">
                    Error: <?= htmlspecialchars($dashWaResult['error'] ?? 'Desconocido') ?>
                </div>
                <?php endif; ?>
                <?php endif; ?>

                <?php if (empty($dashWaTenants)): ?>
                <div style="padding:.75rem 1rem;background:#F6F0E6;border-radius:8px;font-size:.84rem;color:var(--dk-muted);">
                    Sin números configurados en la DB. Ejecutá el seed en el servidor primero.
                </div>
                <?php else: ?>
                <form method="POST" action="/admin/dashboard#wa-test" style="display:flex;flex-wrap:wrap;gap:.75rem;align-items:flex-end;">
                    <input type="hidden" name="action" value="dash_test_whatsapp">

                    <div style="flex:1.5;min-width:180px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:var(--dk-muted);margin-bottom:.3rem;">Número (tenant)</label>
                        <select name="tw_id" style="width:100%;padding:7px 10px;border:1px solid var(--dk-hairline);border-radius:8px;font-size:.84rem;background:#fff;">
                            <?php foreach ($dashWaTenants as $tw): ?>
                            <option value="<?= $tw['id'] ?>" <?= ($dashWaInput['twId'] ?? 0) == $tw['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($tw['tenant_name']) ?> · <?= htmlspecialchars($tw['phone_number_id']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="flex:1;min-width:150px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:var(--dk-muted);margin-bottom:.3rem;">Destino (código de país)</label>
                        <input type="text" name="destino" inputmode="numeric"
                            placeholder="50587654321"
                            value="<?= htmlspecialchars($dashWaInput['destino'] ?? '') ?>"
                            style="width:100%;padding:7px 10px;border:1px solid var(--dk-hairline);border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="min-width:130px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:var(--dk-muted);margin-bottom:.3rem;">Plantilla</label>
                        <input type="text" name="template"
                            value="<?= htmlspecialchars($dashWaInput['tplName'] ?? 'hello_world') ?>"
                            style="width:100%;padding:7px 10px;border:1px solid var(--dk-hairline);border-radius:8px;font-size:.84rem;box-sizing:border-box;">
                    </div>

                    <div style="min-width:120px;">
                        <label style="display:block;font-size:.72rem;font-weight:600;color:var(--dk-muted);margin-bottom:.3rem;">Idioma</label>
                        <select name="lang" style="width:100%;padding:7px 10px;border:1px solid var(--dk-hairline);border-radius:8px;font-size:.84rem;background:#fff;">
                            <?php foreach (['en_US' => 'English (US)', 'es_MX' => 'Español (MX)', 'es' => 'Español'] as $lv => $lt): ?>
                            <option value="<?= $lv ?>" <?= ($dashWaInput['tplLang'] ?? 'en_US') === $lv ? 'selected' : '' ?>><?= $lt ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <button type="submit" style="padding:8px 18px;background:var(--dk-terra);color:#fff;border:none;border-radius:8px;font-size:.84rem;font-weight:700;cursor:pointer;">
                            Enviar plantilla
                        </button>
                    </div>
                </form>
                <?php endif; ?>
            </div>

            <!-- Errores recientes -->
            <div class="dash-panel" style="margin-bottom:2rem;">
                <div class="dash-panel-head">
                    <span class="dash-panel-title">Errores recientes</span>
                    <a href="/admin/logs?type=error" class="dash-panel-link">Ver todos →</a>
                </div>
                <?php if (empty($recentErrors)): ?>
                <div class="empty-state" style="color:var(--dk-green);font-weight:600;">Sin errores recientes — todo funciona bien.</div>
                <?php else: ?>
                <?php foreach ($recentErrors as $e):
                    $payload = json_decode($e['payload'] ?? '{}', true);
                    $summary = $payload['error'] ?? $payload['message'] ?? substr($e['payload'] ?? '', 0, 90);
                ?>
                <div class="biz-row" style="gap:.5rem;">
                    <span class="err-badge"><?= htmlspecialchars($e['type']) ?></span>
                    <span style="font-size:.8rem;font-weight:600;flex-shrink:0;max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= htmlspecialchars($e['tenant_name'] ?? 'Global') ?></span>
                    <span style="flex:1;font-size:.78rem;color:var(--dk-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= htmlspecialchars((string)$summary) ?></span>
                    <span style="font-size:.72rem;color:var(--dk-muted);flex-shrink:0;"><?= date('d/m H:i', strtotime($e['created_at'])) ?></span>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>

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