<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}
$page_title = 'Vale Admin — ' . ($profile['name'] ?? 'Negocio');
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$slug = $profile['public_slug'] ?? '';
ob_start();
?>
<div class="dashboard-container">
    <?php $adminNav = 'tenants'; require __DIR__ . '/sidebar.php'; ?>

    <main class="main-content">
        <header class="header-bar">
            <div style="display:flex;align-items:center;gap:.75rem;">
                <a href="/admin/tenants" style="color:var(--color-text-muted);">&larr;</a>
                <h2><?php echo htmlspecialchars($profile['name']); ?></h2>
                <span class="badge" style="background:rgba(224,163,62,.15);color:#9a6a14;"><?php echo htmlspecialchars($profile['onboarding_status'] ?? ''); ?></span>
            </div>
            <div style="display:flex;gap:.6rem;">
                <a href="/admin/tenants?edit=<?php echo (int) $profile['id']; ?>" class="btn btn-outline" style="padding:.4rem .9rem;">Editar</a>
                <a href="/admin/impersonate?tenant_id=<?php echo (int) $profile['id']; ?>" class="btn btn-primary" style="padding:.4rem .9rem;">Impersonar</a>
            </div>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;max-width:980px;">
            <!-- Métricas -->
            <div style="display:flex;gap:.75rem;flex-wrap:wrap;margin-bottom:1.5rem;">
                <?php
                $mc = [
                    ['Citas', (int) ($profileMetrics['citas'] ?? 0)],
                    ['Leads', (int) ($profileMetrics['leads'] ?? 0)],
                    ['Contactos', (int) ($profileMetrics['contactos'] ?? 0)],
                    ['Conversaciones', (int) ($profileMetrics['convs'] ?? 0)],
                    ['Mensajes', (int) ($profileMetrics['msgs'] ?? 0)],
                ];
                foreach ($mc as $m): ?>
                    <div style="background:#fff;border:1px solid var(--color-border);border-radius:10px;padding:.8rem 1.1rem;min-width:104px;box-shadow:var(--shadow-soft);">
                        <div style="font-family:var(--font-headings);font-size:1.6rem;font-weight:600;color:var(--color-barro);"><?php echo $m[1]; ?></div>
                        <div style="font-size:.72rem;color:var(--color-text-muted);text-transform:uppercase;letter-spacing:.04em;"><?php echo $m[0]; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;">
                <!-- Negocio -->
                <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem;box-shadow:var(--shadow-soft);">
                    <h3 style="margin-bottom:1rem;">Negocio</h3>
                    <?php
                    $rows = [
                        'Rubro' => $profile['business_type'] ?: '—',
                        'Modo' => $profile['profile_kind'] ?? '—',
                        'WhatsApp' => $profile['whatsapp_number'] ?: '—',
                        'Zona horaria' => $profile['timezone'] ?? '—',
                        'Idioma' => $profile['locale'] ?? '—',
                        'Alta' => $profile['created_at'] ?? '—',
                    ];
                    foreach ($rows as $k => $v): ?>
                        <div style="display:flex;justify-content:space-between;padding:.4rem 0;border-bottom:1px solid var(--color-border);font-size:.88rem;">
                            <span style="color:var(--color-text-muted);"><?php echo $k; ?></span>
                            <span style="font-weight:600;"><?php echo htmlspecialchars((string) $v); ?></span>
                        </div>
                    <?php endforeach; ?>
                    <?php if ($slug !== ''): ?>
                        <div style="margin-top:1rem;display:flex;gap:.5rem;flex-wrap:wrap;">
                            <a href="<?php echo htmlspecialchars($scheme . '://' . $host . '/n/' . rawurlencode($slug)); ?>" target="_blank" class="btn btn-outline" style="padding:.4rem .8rem;font-size:.8rem;">Página pública /n/<?php echo htmlspecialchars($slug); ?></a>
                        </div>
                    <?php endif; ?>
                </section>

                <!-- Dueño -->
                <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem;box-shadow:var(--shadow-soft);">
                    <h3 style="margin-bottom:1rem;">Dueño / usuarios</h3>
                    <?php if (empty($profileUsers)): ?>
                        <p style="color:var(--color-text-muted);font-size:.85rem;">Sin usuarios.</p>
                    <?php else: foreach ($profileUsers as $u): ?>
                        <div style="padding:.5rem 0;border-bottom:1px solid var(--color-border);font-size:.88rem;">
                            <div style="font-weight:600;"><?php echo htmlspecialchars($u['name'] ?: '—'); ?> <span style="font-weight:400;color:var(--color-text-muted);font-size:.78rem;">(<?php echo htmlspecialchars($u['role']); ?> · <?php echo htmlspecialchars($u['auth_provider'] ?? 'password'); ?>)</span></div>
                            <div style="color:var(--color-text-muted);"><?php echo htmlspecialchars($u['email']); ?><?php echo $u['phone'] ? ' · ' . htmlspecialchars($u['phone']) : ''; ?></div>
                        </div>
                    <?php endforeach; endif; ?>
                </section>

                <!-- Servicios -->
                <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem;box-shadow:var(--shadow-soft);">
                    <h3 style="margin-bottom:1rem;">Servicios (<?php echo count($profileServices); ?>)</h3>
                    <?php if (empty($profileServices)): ?>
                        <p style="color:var(--color-text-muted);font-size:.85rem;">Sin servicios cargados.</p>
                    <?php else: foreach ($profileServices as $s): ?>
                        <div style="display:flex;justify-content:space-between;padding:.35rem 0;border-bottom:1px solid var(--color-border);font-size:.85rem;<?php echo $s['active'] ? '' : 'opacity:.5;'; ?>">
                            <span><?php echo htmlspecialchars($s['name']); ?></span>
                            <span style="color:var(--color-text-muted);"><?php echo $s['price_min'] !== null ? '$' . number_format($s['price_min'], 0) : ''; ?></span>
                        </div>
                    <?php endforeach; endif; ?>
                </section>

                <!-- Actividad -->
                <section style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.25rem;box-shadow:var(--shadow-soft);">
                    <h3 style="margin-bottom:1rem;">Actividad reciente (evidencia)</h3>
                    <?php if (empty($profileLogs)): ?>
                        <p style="color:var(--color-text-muted);font-size:.85rem;">Sin actividad.</p>
                    <?php else: foreach ($profileLogs as $g): ?>
                        <div style="display:flex;justify-content:space-between;padding:.3rem 0;border-bottom:1px solid var(--color-border);font-size:.8rem;">
                            <span><?php echo htmlspecialchars($g['type']); ?> <?php echo $g['gemini_call'] ? '· Gemini' : ''; ?></span>
                            <span style="color:var(--color-text-muted);white-space:nowrap;"><?php echo htmlspecialchars(date('d/m H:i', strtotime($g['created_at']))); ?><?php echo $g['tokens'] ? ' · ' . (int) $g['tokens'] . 'tk' : ''; ?></span>
                        </div>
                    <?php endforeach; endif; ?>
                </section>
            </div>
        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/layout.php';
