<?php
/**
 * Relatórios - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

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

// Período selecionado
$period = $_GET['period'] ?? '30';
$startDate = date('Y-m-d', strtotime("-{$period} days"));

// Métricas gerais
$totalStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE deleted_at IS NULL")->fetchColumn();
$newStores = $pdo->prepare("SELECT COUNT(*) FROM stores WHERE created_at >= ? AND deleted_at IS NULL");
$newStores->execute([$startDate]);
$newStoresCount = $newStores->fetchColumn();

$totalOrders = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE created_at >= ?");
$totalOrders->execute([$startDate]);
$totalOrdersCount = $totalOrders->fetchColumn();

$totalRevenue = $pdo->prepare("SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE created_at >= ?");
$totalRevenue->execute([$startDate]);
$totalRevenueValue = $totalRevenue->fetchColumn();

// MRR atual
$mrrResult = $pdo->query("SELECT COALESCE(SUM(p.price_monthly), 0) FROM subscriptions s JOIN plans p ON s.plan_id = p.id WHERE s.status = 'active'")->fetchColumn();

// Top lojas por faturamento
$topStores = $pdo->prepare("
    SELECT s.name, s.slug, 
           COUNT(o.id) as orders_count, 
           COALESCE(SUM(o.total_amount), 0) as revenue
    FROM stores s
    LEFT JOIN orders o ON o.store_id = s.id AND o.created_at >= ?
    WHERE s.deleted_at IS NULL
    GROUP BY s.id
    ORDER BY revenue DESC
    LIMIT 10
");
$topStores->execute([$startDate]);
$topStoresData = $topStores->fetchAll(PDO::FETCH_ASSOC);

// Assinaturas por plano
$planStats = $pdo->query("
    SELECT p.name, COUNT(s.id) as count, SUM(p.price_monthly) as mrr
    FROM plans p
    LEFT JOIN subscriptions s ON s.plan_id = p.id AND s.status = 'active'
    GROUP BY p.id
    ORDER BY count DESC
")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Relatórios';
$currentPage = 'reports';

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

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

            <div class="content-area">
                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <h2>Relatórios</h2>
                        <p>Análise de performance do SaaS</p>
                    </div>
                    <div class="flex gap-2">
                        <a href="?period=7" class="btn <?= $period == '7' ? 'btn-primary' : 'btn-secondary' ?> btn-sm">7 dias</a>
                        <a href="?period=30" class="btn <?= $period == '30' ? 'btn-primary' : 'btn-secondary' ?> btn-sm">30 dias</a>
                        <a href="?period=90" class="btn <?= $period == '90' ? 'btn-primary' : 'btn-secondary' ?> btn-sm">90 dias</a>
                        <a href="?period=365" class="btn <?= $period == '365' ? 'btn-primary' : 'btn-secondary' ?> btn-sm">1 ano</a>
                    </div>
                </div>

                <!-- KPIs -->
                <div class="kpi-grid" style="grid-template-columns: repeat(4, 1fr);">
                    <div class="kpi-card highlight">
                        <div class="kpi-label">MRR Atual</div>
                        <div class="kpi-value gold"><?= formatMoney($mrrResult) ?></div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Novas Lojas</div>
                        <div class="kpi-value"><?= $newStoresCount ?></div>
                        <div class="text-muted text-sm mt-2">últimos <?= $period ?> dias</div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Pedidos</div>
                        <div class="kpi-value"><?= $totalOrdersCount ?></div>
                        <div class="text-muted text-sm mt-2">últimos <?= $period ?> dias</div>
                    </div>
                    <div class="kpi-card">
                        <div class="kpi-label">Faturamento Lojas</div>
                        <div class="kpi-value"><?= formatMoney($totalRevenueValue) ?></div>
                        <div class="text-muted text-sm mt-2">últimos <?= $period ?> dias</div>
                    </div>
                </div>

                <div class="grid-2">
                    <!-- Top Lojas -->
                    <div class="panel">
                        <h3 class="section-title mb-4">Top 10 Lojas por Faturamento</h3>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Loja</th>
                                    <th>Pedidos</th>
                                    <th>Faturamento</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($topStoresData as $i => $store): ?>
                                <tr>
                                    <td class="text-muted"><?= $i + 1 ?></td>
                                    <td>
                                        <div class="font-medium"><?= htmlspecialchars($store['name'] ?? 'N/A') ?></div>
                                        <div class="text-muted text-sm"><?= htmlspecialchars($store['slug'] ?? '-') ?></div>
                                    </td>
                                    <td><?= $store['orders_count'] ?></td>
                                    <td class="text-gold font-medium"><?= formatMoney($store['revenue']) ?></td>
                                </tr>
                                <?php endforeach; ?>
                                
                                <?php if (empty($topStoresData)): ?>
                                <tr>
                                    <td colspan="4" class="text-muted" style="text-align: center; padding: 2rem;">
                                        Nenhum dado disponível
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Distribuição por Plano -->
                    <div class="panel">
                        <h3 class="section-title mb-4">Assinaturas por Plano</h3>
                        
                        <?php if (!empty($planStats)): ?>
                        <div style="display: grid; gap: 1rem;">
                            <?php foreach ($planStats as $plan): ?>
                            <div style="padding: 1rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-md);">
                                <div class="flex justify-between items-center mb-2">
                                    <span class="font-medium"><?= htmlspecialchars($plan['name']) ?></span>
                                    <span class="text-gold"><?= formatMoney($plan['mrr'] ?? 0) ?>/mês</span>
                                </div>
                                <div class="flex justify-between items-center text-sm">
                                    <span class="text-muted"><?= $plan['count'] ?? 0 ?> assinantes</span>
                                    <div style="flex: 1; margin: 0 1rem; height: 4px; background: rgba(255,255,255,0.1); border-radius: 2px; overflow: hidden;">
                                        <?php 
                                        $maxCount = max(array_column($planStats, 'count') ?: [1]);
                                        $percentage = $maxCount > 0 ? (($plan['count'] ?? 0) / $maxCount) * 100 : 0;
                                        ?>
                                        <div style="width: <?= $percentage ?>%; height: 100%; background: var(--gold);"></div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <p class="text-muted" style="text-align: center; padding: 2rem;">
                            Nenhum plano cadastrado
                        </p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Métricas Adicionais -->
                <div class="panel">
                    <h3 class="section-title mb-4">Resumo Geral</h3>
                    <div class="grid-4">
                        <div style="text-align: center; padding: 1.5rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-md);">
                            <iconify-icon icon="solar:shop-bold" style="font-size: 2rem; color: var(--gold); margin-bottom: 0.5rem;"></iconify-icon>
                            <div class="kpi-value" style="font-size: 1.5rem;"><?= $totalStores ?></div>
                            <div class="text-muted text-sm">Total de Lojas</div>
                        </div>
                        <div style="text-align: center; padding: 1.5rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-md);">
                            <iconify-icon icon="solar:users-group-rounded-bold" style="font-size: 2rem; color: var(--gold); margin-bottom: 0.5rem;"></iconify-icon>
                            <div class="kpi-value" style="font-size: 1.5rem;"><?= $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() ?></div>
                            <div class="text-muted text-sm">Total de Usuários</div>
                        </div>
                        <div style="text-align: center; padding: 1.5rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-md);">
                            <iconify-icon icon="solar:cart-bold" style="font-size: 2rem; color: var(--gold); margin-bottom: 0.5rem;"></iconify-icon>
                            <div class="kpi-value" style="font-size: 1.5rem;"><?= $pdo->query("SELECT COUNT(*) FROM orders")->fetchColumn() ?></div>
                            <div class="text-muted text-sm">Total de Pedidos</div>
                        </div>
                        <div style="text-align: center; padding: 1.5rem; background: rgba(255,255,255,0.02); border-radius: var(--radius-md);">
                            <iconify-icon icon="solar:box-bold" style="font-size: 2rem; color: var(--gold); margin-bottom: 0.5rem;"></iconify-icon>
                            <div class="kpi-value" style="font-size: 1.5rem;"><?= $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn() ?></div>
                            <div class="text-muted text-sm">Total de Produtos</div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
