<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}
$page_title = 'Vale Admin — Negocios';

/** Salud del tenant a partir de su actividad/errores. */
function tenant_health(array $t): array {
    if ((int) ($t['recent_errors'] ?? 0) > 0) {
        return ['dot' => '#C0392B', 'label' => 'Con errores'];
    }
    if (($t['onboarding_status'] ?? '') !== 'live') {
        return ['dot' => '#E0A33E', 'label' => 'Configurando'];
    }
    $last = $t['last_activity'] ?? null;
    if ($last && strtotime($last) > (time() - 3 * 86400)) {
        return ['dot' => '#1E7A4D', 'label' => 'Activa'];
    }
    return ['dot' => '#b9b1a6', 'label' => 'Sin actividad'];
}

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

    <main class="main-content">
        <header class="header-bar">
            <h2>Negocios</h2>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;">
            <?php if (!empty($notice)): ?>
                <div class="alert" style="background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);word-break:break-all;"><?php echo htmlspecialchars($notice); ?></div>
            <?php endif; ?>
            <?php if (!empty($error)): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <!-- Resumen -->
            <div style="display:flex;gap:.75rem;flex-wrap:wrap;margin-bottom:1.5rem;">
                <?php
                $cards = [
                    ['Negocios', (int) ($summary['total'] ?? 0)],
                    ['Activos (live)', (int) ($summary['live'] ?? 0)],
                    ['Citas totales', (int) ($summary['citas'] ?? 0)],
                    ['Leads totales', (int) ($summary['leads'] ?? 0)],
                ];
                foreach ($cards as $c): ?>
                    <div style="background:#fff;border:1px solid var(--color-border);border-radius:10px;padding:.85rem 1.2rem;min-width:120px;box-shadow:var(--shadow-soft);">
                        <div style="font-family:var(--font-headings);font-size:1.7rem;font-weight:600;color:var(--color-barro);"><?php echo $c[1]; ?></div>
                        <div style="font-size:.75rem;color:var(--color-text-muted);text-transform:uppercase;letter-spacing:.04em;"><?php echo $c[0]; ?></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <details style="background:#fff;border:1px solid var(--color-border);border-radius:10px;padding:1rem 1.25rem;margin-bottom:1.5rem;">
                <summary style="cursor:pointer;font-weight:600;color:var(--color-barro);">+ Dar de alta un negocio</summary>
                <form method="POST" action="/admin/tenants" style="margin-top:1rem;display:grid;grid-template-columns:1fr 1fr;gap:.8rem;">
                    <label style="font-size:.8rem;">Nombre del negocio*
                        <input type="text" name="name" required class="form-control">
                    </label>
                    <label style="font-size:.8rem;">WhatsApp (whatsapp:+1...)
                        <input type="text" name="whatsapp_number" placeholder="whatsapp:+14155238886" class="form-control">
                    </label>
                    <label style="font-size:.8rem;">Email del dueño*
                        <input type="email" name="owner_email" required class="form-control">
                    </label>
                    <label style="font-size:.8rem;">Contraseña del dueño*
                        <input type="password" name="owner_password" required class="form-control">
                    </label>
                    <div style="grid-column:1/3;"><button type="submit" class="btn btn-primary">Crear negocio</button></div>
                </form>
            </details>

            <?php if (!empty($editTenant)): ?>
            <section style="background:#fff;border:1px solid var(--color-oro);border-radius:10px;padding:1rem 1.25rem;margin-bottom:1.5rem;">
                <h3 style="color:var(--color-barro);margin:0 0 1rem;font-size:1.05rem;">Editar: <?php echo htmlspecialchars($editTenant['name']); ?></h3>
                <form method="POST" action="/admin/tenants" style="display:grid;grid-template-columns:1fr 1fr;gap:.8rem;">
                    <input type="hidden" name="action" value="update_tenant">
                    <input type="hidden" name="tenant_id" value="<?php echo (int) $editTenant['id']; ?>">
                    <label style="font-size:.8rem;">Nombre*<input type="text" name="name" required value="<?php echo htmlspecialchars($editTenant['name']); ?>" class="form-control"></label>
                    <label style="font-size:.8rem;">WhatsApp<input type="text" name="whatsapp_number" value="<?php echo htmlspecialchars($editTenant['whatsapp_number'] ?? ''); ?>" class="form-control"></label>
                    <label style="font-size:.8rem;">Zona horaria<input type="text" name="timezone" value="<?php echo htmlspecialchars($editTenant['timezone'] ?? 'America/New_York'); ?>" class="form-control"></label>
                    <label style="font-size:.8rem;">Idioma
                        <select name="locale" class="form-control">
                            <option value="es" <?php echo ($editTenant['locale'] ?? 'es') === 'es' ? 'selected' : ''; ?>>Español</option>
                            <option value="en" <?php echo ($editTenant['locale'] ?? 'es') === 'en' ? 'selected' : ''; ?>>Inglés</option>
                        </select>
                    </label>
                    <div style="grid-column:1/3;display:flex;gap:.6rem;align-items:center;">
                        <button type="submit" class="btn btn-primary">Guardar cambios</button>
                        <a href="/admin/tenants" style="color:var(--color-text-muted);">Cancelar</a>
                    </div>
                </form>
            </section>
            <?php endif; ?>

            <table style="width:100%;border-collapse:collapse;background:#fff;border-radius:12px;overflow:hidden;font-size:.85rem;box-shadow:var(--shadow-soft);">
                <thead>
                    <tr style="background:var(--color-tierra);color:#FBF6EE;text-align:left;">
                        <th style="padding:.7rem 1rem;">Negocio</th>
                        <th style="padding:.7rem 1rem;">Salud</th>
                        <th style="padding:.7rem 1rem;">Citas</th>
                        <th style="padding:.7rem 1rem;">Leads</th>
                        <th style="padding:.7rem 1rem;">Última actividad</th>
                        <th style="padding:.7rem 1rem;">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($tenants)): ?>
                        <tr><td colspan="6" style="padding:1.5rem;text-align:center;color:var(--color-text-muted);">Sin negocios todavía.</td></tr>
                    <?php else: ?>
                        <?php foreach ($tenants as $t): ?>
                            <?php $h = tenant_health($t); ?>
                            <tr style="border-top:1px solid var(--color-border);">
                                <td style="padding:.7rem 1rem;">
                                    <a href="/admin/tenant?id=<?php echo (int) $t['id']; ?>" style="font-weight:600;color:var(--color-tinta);">#<?php echo (int) $t['id']; ?> · <?php echo htmlspecialchars($t['name']); ?></a>
                                    <div style="font-size:.72rem;color:var(--color-text-muted);"><?php echo htmlspecialchars($t['owner_email'] ?? ''); ?></div>
                                </td>
                                <td style="padding:.7rem 1rem;white-space:nowrap;">
                                    <span style="display:inline-block;width:9px;height:9px;border-radius:50%;background:<?php echo $h['dot']; ?>;margin-right:6px;"></span><?php echo $h['label']; ?>
                                </td>
                                <td style="padding:.7rem 1rem;"><?php echo (int) $t['citas']; ?></td>
                                <td style="padding:.7rem 1rem;"><?php echo (int) $t['leads']; ?></td>
                                <td style="padding:.7rem 1rem;white-space:nowrap;color:var(--color-text-muted);"><?php echo $t['last_activity'] ? htmlspecialchars(date('d/m H:i', strtotime($t['last_activity']))) : '—'; ?></td>
                                <td style="padding:.7rem 1rem;display:flex;gap:.6rem;flex-wrap:wrap;">
                                    <a href="/admin/tenant?id=<?php echo (int) $t['id']; ?>" style="color:var(--color-barro);font-weight:600;">Perfil</a>
                                    <a href="/admin/impersonate?tenant_id=<?php echo (int) $t['id']; ?>" style="color:var(--color-barro);">Impersonar</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/layout.php';
