<?php
/**
 * Super Admin Dashboard - BarberFlow SaaS
 * Visão do CEO: MRR, Lojas, Churn, Impersonation
 */
require_once __DIR__ . '/../../includes/config.php';

// Verifica se é Super Admin
if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

// Buscar métricas
$totalStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE deleted_at IS NULL")->fetchColumn();
$activeStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE status = 'active' AND deleted_at IS NULL")->fetchColumn();
$trialStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE status = 'trial' AND deleted_at IS NULL")->fetchColumn();
$newStoresThisMonth = $pdo->query("SELECT COUNT(*) FROM stores WHERE MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())")->fetchColumn();

// MRR (Monthly Recurring Revenue)
$mrrResult = $pdo->query("
    SELECT COALESCE(SUM(p.price_monthly), 0) as mrr
    FROM subscriptions s
    JOIN plans p ON s.plan_id = p.id
    WHERE s.status = 'active'
")->fetch();
$mrr = $mrrResult['mrr'] ?? 0;

// Pedidos do mês
$ordersThisMonth = $pdo->query("SELECT COUNT(*) FROM orders WHERE MONTH(created_at) = MONTH(CURRENT_DATE())")->fetchColumn();
$revenueThisMonth = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE MONTH(created_at) = MONTH(CURRENT_DATE())")->fetchColumn();

// Listar lojas recentes (otimizado: JOIN ao invés de subqueries correlatas)
$recentStores = $pdo->query("
    SELECT s.*,
           COALESCE(o_stats.orders_count, 0) as orders_count,
           COALESCE(o_stats.total_revenue, 0) as total_revenue
    FROM stores s
    LEFT JOIN (
        SELECT store_id, COUNT(*) as orders_count, COALESCE(SUM(total_amount), 0) as total_revenue
        FROM orders
        GROUP BY store_id
    ) o_stats ON o_stats.store_id = s.id
    WHERE s.deleted_at IS NULL
    ORDER BY s.created_at DESC
    LIMIT 10
")->fetchAll();

$pageTitle = 'Dashboard do SaaS';
$currentPage = 'dashboard';

include __DIR__ . '/includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/includes/sidebar.php'; ?>

        <!-- Main Content -->
        <main class="main-content">
            <?php include __DIR__ . '/includes/topbar.php'; ?>

            <div class="content-area">
                <!-- KPIs -->
                <div class="kpi-grid">
                    <div class="kpi-card highlight">
                        <div class="kpi-label">MRR (Receita Recorrente)</div>
                        <div class="kpi-value gold"><?= formatMoney($mrr) ?></div>
                        <div class="kpi-trend up">
                            <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                            +12% vs mês anterior
                        </div>
                    </div>

                    <div class="kpi-card">
                        <div class="kpi-label">Total de Lojas</div>
                        <div class="kpi-value"><?= $totalStores ?></div>
                        <div class="kpi-trend up">
                            +<?= $newStoresThisMonth ?> este mês
                        </div>
                    </div>

                    <div class="kpi-card">
                        <div class="kpi-label">Lojas Ativas</div>
                        <div class="kpi-value"><?= $activeStores ?></div>
                    </div>

                    <div class="kpi-card">
                        <div class="kpi-label">Em Trial</div>
                        <div class="kpi-value"><?= $trialStores ?></div>
                    </div>

                    <div class="kpi-card">
                        <div class="kpi-label">Pedidos do Mês</div>
                        <div class="kpi-value"><?= $ordersThisMonth ?></div>
                    </div>

                    <div class="kpi-card">
                        <div class="kpi-label">Faturamento das Lojas</div>
                        <div class="kpi-value"><?= formatMoney($revenueThisMonth) ?></div>
                    </div>
                </div>

                <!-- Lista de Lojas -->
                <div class="panel">
                    <div class="section-header">
                        <h3 class="section-title">Lojas Recentes</h3>
                        <a href="/pages/superadmin/stores.php" class="btn btn-secondary btn-sm">Ver todas →</a>
                    </div>

                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Loja</th>
                                <th>Status</th>
                                <th>Plano</th>
                                <th>Pedidos</th>
                                <th>Faturamento</th>
                                <th>Criada em</th>
                                <th>Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentStores as $store): ?>
                            <tr>
                                <td>
                                    <div class="font-medium"><?= htmlspecialchars($store['name'] ?? $store['nome'] ?? 'Sem nome') ?></div>
                                    <div class="text-muted text-sm"><?= htmlspecialchars($store['slug'] ?? $store['subdomain'] ?? '-') ?></div>
                                </td>
                                <td>
                                    <span class="status-badge status-<?= $store['status'] ?? 'active' ?>">
                                        <?= ucfirst($store['status'] ?? 'Ativo') ?>
                                    </span>
                                </td>
                                <td><?= ucfirst($store['plan_id'] ?? 'free') ?></td>
                                <td><?= $store['orders_count'] ?></td>
                                <td><?= formatMoney($store['total_revenue']) ?></td>
                                <td><?= date('d/m/Y', strtotime($store['created_at'])) ?></td>
                                <td>
                                    <form action="/pages/superadmin/impersonate.php" method="POST" style="display: inline;">
                                        <input type="hidden" name="store_id" value="<?= $store['id'] ?>">
                                        <button type="submit" class="btn btn-outline btn-sm">
                                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                            Acessar
                                        </button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>
<?php include __DIR__ . '/includes/footer.php'; ?>
