<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../includes/config.php';

// Forçar login para teste
$_SESSION['is_super_admin'] = true;
$_SESSION['super_admin_id'] = 1;

$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();

// MRR
$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
$recentStores = $pdo->query("
    SELECT s.*,
           (SELECT COUNT(*) FROM orders o WHERE o.store_id = s.id) as orders_count,
           (SELECT COALESCE(SUM(total_amount), 0) FROM orders o WHERE o.store_id = s.id) as total_revenue
    FROM stores s
    WHERE s.deleted_at IS NULL
    ORDER BY s.created_at DESC
    LIMIT 10
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Super Admin Dashboard - BarberFlow</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background: #1A1A1A; }
        .gold-accent { color: #CCA43B; }
        .gold-bg { background: #CCA43B; }
        .card { background: #252525; border-radius: 12px; }
        .sidebar { background: #252525; }
    </style>
</head>
<body class="text-white min-h-screen">
    <div class="flex">
        <!-- Sidebar -->
        <aside class="sidebar w-64 min-h-screen p-6 fixed">
            <div class="mb-8">
                <h1 class="text-2xl font-bold gold-accent">BarberFlow</h1>
                <p class="text-gray-400 text-sm">Super Admin</p>
            </div>
            <nav class="space-y-2">
                <a href="/pages/superadmin/dashboard.php" class="flex items-center gap-3 px-4 py-3 rounded-lg gold-bg text-black font-medium">Dashboard</a>
                <a href="/pages/superadmin/stores.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-300 hover:bg-white/5">Lojas</a>
                <a href="/pages/superadmin/subscriptions.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-300 hover:bg-white/5">Assinaturas</a>
                <a href="/pages/superadmin/plans.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-300 hover:bg-white/5">Planos</a>
                <a href="/pages/superadmin/users.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-300 hover:bg-white/5">Usuários</a>
                <a href="/pages/superadmin/settings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-300 hover:bg-white/5">Configurações</a>
            </nav>
            <div class="absolute bottom-6 left-6 right-6">
                <a href="/pages/superadmin/logout.php" class="flex items-center gap-3 px-4 py-3 rounded-lg text-red-400 hover:bg-red-500/10">Sair</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="ml-64 flex-1 p-8">
            <div class="mb-8">
                <h2 class="text-2xl font-bold">Dashboard</h2>
                <p class="text-gray-400">Bem-vindo, <?= htmlspecialchars($superAdmin['name'] ?? 'Admin') ?>!</p>
            </div>

            <!-- KPI Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">MRR</p>
                    <p class="text-3xl font-bold gold-accent">R$ <?= number_format($mrr, 2, ',', '.') ?></p>
                </div>
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">Total de Lojas</p>
                    <p class="text-3xl font-bold"><?= $totalStores ?></p>
                </div>
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">Lojas Ativas</p>
                    <p class="text-3xl font-bold text-green-400"><?= $activeStores ?></p>
                </div>
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">Em Trial</p>
                    <p class="text-3xl font-bold text-yellow-400"><?= $trialStores ?></p>
                </div>
            </div>

            <!-- Segunda linha de KPIs -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">Pedidos este mês</p>
                    <p class="text-3xl font-bold"><?= $ordersThisMonth ?></p>
                </div>
                <div class="card p-6">
                    <p class="text-gray-400 text-sm mb-1">Receita este mês</p>
                    <p class="text-3xl font-bold gold-accent">R$ <?= number_format($revenueThisMonth, 2, ',', '.') ?></p>
                </div>
            </div>

            <!-- Lojas Recentes -->
            <div class="card">
                <div class="p-6 border-b border-white/10">
                    <h3 class="text-lg font-bold">Lojas Recentes</h3>
                </div>
                <table class="w-full">
                    <thead class="bg-white/5">
                        <tr>
                            <th class="text-left px-6 py-4 text-gray-400 font-medium">Loja</th>
                            <th class="text-left px-6 py-4 text-gray-400 font-medium">Status</th>
                            <th class="text-left px-6 py-4 text-gray-400 font-medium">Pedidos</th>
                            <th class="text-left px-6 py-4 text-gray-400 font-medium">Receita</th>
                            <th class="text-right px-6 py-4 text-gray-400 font-medium">Ações</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-white/5">
                        <?php foreach ($recentStores as $store): ?>
                        <tr class="hover:bg-white/5">
                            <td class="px-6 py-4 font-medium"><?= htmlspecialchars($store['nome'] ?? 'Sem nome') ?></td>
                            <td class="px-6 py-4">
                                <span class="bg-green-500/20 text-green-400 px-3 py-1 rounded-full text-sm">
                                    <?= ucfirst($store['status'] ?? 'active') ?>
                                </span>
                            </td>
                            <td class="px-6 py-4"><?= $store['orders_count'] ?></td>
                            <td class="px-6 py-4 gold-accent">R$ <?= number_format($store['total_revenue'], 2, ',', '.') ?></td>
                            <td class="px-6 py-4 text-right">
                                <a href="/pages/superadmin/impersonate.php?store_id=<?= $store['id'] ?>" class="text-blue-400 hover:underline">
                                    Acessar
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($recentStores)): ?>
                        <tr>
                            <td colspan="5" class="px-6 py-12 text-center text-gray-400">
                                Nenhuma loja cadastrada
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>
</body>
</html>
