<?php
/**
 * Página de Relatórios - MontaLoja SaaS
 * Versão Responsiva (Loja e Barbearia)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// FILTRO DE PERÍODO
$period = $_GET['period'] ?? 'month';
$dateFrom = $_GET['from'] ?? date('Y-m-01');
$dateTo = $_GET['to'] ?? date('Y-m-t');

if ($period === 'today') {
    $dateFrom = $dateTo = date('Y-m-d');
    $periodLabel = 'Hoje';
} elseif ($period === 'yesterday') {
    $dateFrom = $dateTo = date('Y-m-d', strtotime('-1 day'));
    $periodLabel = 'Ontem';
} elseif ($period === 'week') {
    $dateFrom = date('Y-m-d', strtotime('monday this week'));
    $dateTo = date('Y-m-d');
    $periodLabel = 'Esta Semana';
} elseif ($period === 'month') {
    $dateFrom = date('Y-m-01');
    $dateTo = date('Y-m-t');
    $periodLabel = 'Este Mês';
} elseif ($period === 'last_month') {
    $dateFrom = date('Y-m-01', strtotime('first day of last month'));
    $dateTo = date('Y-m-t', strtotime('last day of last month'));
    $periodLabel = 'Mês Passado';
} elseif ($period === 'year') {
    $dateFrom = date('Y-01-01');
    $dateTo = date('Y-12-31');
    $periodLabel = 'Este Ano';
} elseif ($period === 'custom') {
    $periodLabel = date('d/m', strtotime($dateFrom)) . ' - ' . date('d/m', strtotime($dateTo));
} else {
    $dateFrom = date('Y-m-01');
    $dateTo = date('Y-m-t');
    $periodLabel = 'Este Mês';
}

$storeType = $store['type'] ?? 'retail';
$isBarbershop = in_array($storeType, ['barbershop', 'salon', 'barbearia', 'salao']);

// Status válidos para contabilizar receita (pedidos concluídos/pagos)
$validStatuses = ['paid', 'confirmed', 'preparing', 'shipped', 'delivered'];

// Inicializar variáveis
$serviceRevenue = 0;
$salesRevenue = 0;
$totalAppointments = 0;
$completedAppointments = 0;
$cancelledAppointments = 0;
$totalOrders = 0;
$completedOrders = 0;
$cancelledOrders = 0;
$topServices = [];
$topTeam = [];
$topProducts = [];
$topCategories = [];
$newCustomers = 0;
$totalIncome = 0;
$totalExpense = 0;

// Buscar dados para os relatórios
try {
    if ($isBarbershop) {
        // Relatórios de Barbearia/Salão

        // Verificar se tabela appointments existe
        $checkTable = $pdo->query("SHOW TABLES LIKE 'appointments'");
        if ($checkTable->rowCount() > 0) {
            // Agendamentos
            $aptStmt = $pdo->prepare("SELECT COUNT(*) as total, status FROM appointments WHERE store_id = ? AND appointment_date BETWEEN ? AND ? GROUP BY status");
            $aptStmt->execute([$storeId, $dateFrom, $dateTo]);
            $appointmentStats = $aptStmt->fetchAll(PDO::FETCH_ASSOC);

            $totalAppointments = array_sum(array_column($appointmentStats, 'total'));
            foreach ($appointmentStats as $stat) {
                if ($stat['status'] === 'completed') $completedAppointments = $stat['total'];
                if ($stat['status'] === 'cancelled') $cancelledAppointments = $stat['total'];
            }

            // Receita de serviços
            try {
                $revenueStmt = $pdo->prepare("SELECT SUM(s.price) as revenue FROM appointments a JOIN services s ON a.service_id = s.id WHERE a.store_id = ? AND a.appointment_date BETWEEN ? AND ? AND a.status = 'completed'");
                $revenueStmt->execute([$storeId, $dateFrom, $dateTo]);
                $serviceRevenue = $revenueStmt->fetchColumn() ?: 0;
            } catch (Exception $e) {}

            // Top serviços
            try {
                $topServicesStmt = $pdo->prepare("SELECT s.name, COUNT(a.id) as count, SUM(s.price) as revenue FROM appointments a JOIN services s ON a.service_id = s.id WHERE a.store_id = ? AND a.appointment_date BETWEEN ? AND ? AND a.status = 'completed' GROUP BY s.id ORDER BY count DESC LIMIT 5");
                $topServicesStmt->execute([$storeId, $dateFrom, $dateTo]);
                $topServices = $topServicesStmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {}

            // Top profissionais
            try {
                $topTeamStmt = $pdo->prepare("SELECT t.name, COUNT(a.id) as count, SUM(s.price) as revenue FROM appointments a JOIN team_members t ON a.professional_id = t.id JOIN services s ON a.service_id = s.id WHERE a.store_id = ? AND a.appointment_date BETWEEN ? AND ? AND a.status = 'completed' GROUP BY t.id ORDER BY revenue DESC LIMIT 5");
                $topTeamStmt->execute([$storeId, $dateFrom, $dateTo]);
                $topTeam = $topTeamStmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {}
        }

    } else {
        // Relatórios de Loja/Varejo

        // Verificar se tabela orders existe
        $checkTable = $pdo->query("SHOW TABLES LIKE 'orders'");
        if ($checkTable->rowCount() > 0) {
            // Pedidos - contar todos os status
            $orderStmt = $pdo->prepare("SELECT COUNT(*) as total, status FROM orders WHERE store_id = ? AND DATE(created_at) BETWEEN ? AND ? GROUP BY status");
            $orderStmt->execute([$storeId, $dateFrom, $dateTo]);
            $orderStats = $orderStmt->fetchAll(PDO::FETCH_ASSOC);

            $totalOrders = array_sum(array_column($orderStats, 'total'));
            foreach ($orderStats as $stat) {
                if (in_array($stat['status'], ['delivered', 'paid', 'confirmed'])) {
                    $completedOrders += $stat['total'];
                }
                if (in_array($stat['status'], ['cancelled', 'canceled'])) {
                    $cancelledOrders += $stat['total'];
                }
            }

            // Receita de vendas - pedidos pagos/entregues
            try {
                $revenueStmt = $pdo->prepare("SELECT SUM(total_amount) as revenue FROM orders WHERE store_id = ? AND DATE(created_at) BETWEEN ? AND ? AND status IN ('paid', 'confirmed', 'preparing', 'shipped', 'delivered')");
                $revenueStmt->execute([$storeId, $dateFrom, $dateTo]);
                $salesRevenue = $revenueStmt->fetchColumn() ?: 0;
            } catch (Exception $e) {}

            // Top produtos - com base em order_items
            try {
                $topProductsStmt = $pdo->prepare("
                    SELECT 
                        p.name, 
                        SUM(oi.quantity) as quantity, 
                        SUM(oi.quantity * oi.unit_price) as revenue 
                    FROM order_items oi 
                    JOIN products p ON oi.product_id = p.id 
                    JOIN orders o ON oi.order_id = o.id 
                    WHERE o.store_id = ? 
                    AND DATE(o.created_at) BETWEEN ? AND ? 
                    AND o.status NOT IN ('cancelled', 'canceled', 'expired')
                    GROUP BY p.id, p.name
                    ORDER BY quantity DESC 
                    LIMIT 5
                ");
                $topProductsStmt->execute([$storeId, $dateFrom, $dateTo]);
                $topProducts = $topProductsStmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
                // Fallback se a coluna unit_price não existir
                try {
                    $topProductsStmt = $pdo->prepare("
                        SELECT 
                            p.name, 
                            SUM(oi.quantity) as quantity, 
                            SUM(oi.quantity * p.price) as revenue 
                        FROM order_items oi 
                        JOIN products p ON oi.product_id = p.id 
                        JOIN orders o ON oi.order_id = o.id 
                        WHERE o.store_id = ? 
                        AND DATE(o.created_at) BETWEEN ? AND ? 
                        AND o.status NOT IN ('cancelled', 'canceled', 'expired')
                        GROUP BY p.id, p.name
                        ORDER BY quantity DESC 
                        LIMIT 5
                    ");
                    $topProductsStmt->execute([$storeId, $dateFrom, $dateTo]);
                    $topProducts = $topProductsStmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e2) {}
            }

            // Top categorias
            try {
                $topCategoriesStmt = $pdo->prepare("
                    SELECT 
                        COALESCE(c.name, 'Sem Categoria') as name, 
                        COUNT(DISTINCT o.id) as order_count,
                        SUM(oi.quantity) as quantity,
                        SUM(oi.quantity * oi.unit_price) as revenue 
                    FROM order_items oi 
                    JOIN products p ON oi.product_id = p.id 
                    LEFT JOIN categories c ON p.category_id = c.id 
                    JOIN orders o ON oi.order_id = o.id 
                    WHERE o.store_id = ? 
                    AND DATE(o.created_at) BETWEEN ? AND ? 
                    AND o.status NOT IN ('cancelled', 'canceled', 'expired')
                    GROUP BY c.id
                    ORDER BY revenue DESC 
                    LIMIT 5
                ");
                $topCategoriesStmt->execute([$storeId, $dateFrom, $dateTo]);
                $topCategories = $topCategoriesStmt->fetchAll(PDO::FETCH_ASSOC);
            } catch (Exception $e) {
                // Fallback
                try {
                    $topCategoriesStmt = $pdo->prepare("
                        SELECT 
                            COALESCE(c.name, 'Sem Categoria') as name, 
                            COUNT(DISTINCT o.id) as order_count,
                            SUM(oi.quantity) as quantity,
                            SUM(oi.quantity * p.price) as revenue 
                        FROM order_items oi 
                        JOIN products p ON oi.product_id = p.id 
                        LEFT JOIN categories c ON p.category_id = c.id 
                        JOIN orders o ON oi.order_id = o.id 
                        WHERE o.store_id = ? 
                        AND DATE(o.created_at) BETWEEN ? AND ? 
                        AND o.status NOT IN ('cancelled', 'canceled', 'expired')
                        GROUP BY c.id
                        ORDER BY revenue DESC 
                        LIMIT 5
                    ");
                    $topCategoriesStmt->execute([$storeId, $dateFrom, $dateTo]);
                    $topCategories = $topCategoriesStmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (Exception $e2) {}
            }
        }
    }

    // Novos clientes
    try {
        $checkTable = $pdo->query("SHOW TABLES LIKE 'customers'");
        if ($checkTable->rowCount() > 0) {
            $newCustomersStmt = $pdo->prepare("SELECT COUNT(*) FROM customers WHERE store_id = ? AND DATE(created_at) BETWEEN ? AND ?");
            $newCustomersStmt->execute([$storeId, $dateFrom, $dateTo]);
            $newCustomers = $newCustomersStmt->fetchColumn() ?: 0;
        }
    } catch (Exception $e) {}

    // Transações financeiras
    try {
        $checkTable = $pdo->query("SHOW TABLES LIKE 'transactions'");
        if ($checkTable->rowCount() > 0) {
            $incomeStmt = $pdo->prepare("SELECT SUM(amount) FROM transactions WHERE store_id = ? AND type = 'income' AND transaction_date BETWEEN ? AND ?");
            $incomeStmt->execute([$storeId, $dateFrom, $dateTo]);
            $totalIncome = $incomeStmt->fetchColumn() ?: 0;

            $expenseStmt = $pdo->prepare("SELECT SUM(amount) FROM transactions WHERE store_id = ? AND type = 'expense' AND transaction_date BETWEEN ? AND ?");
            $expenseStmt->execute([$storeId, $dateFrom, $dateTo]);
            $totalExpense = $expenseStmt->fetchColumn() ?: 0;
        }
    } catch (Exception $e) {}

    // Se não houver transações, usar a receita de vendas como receita
    if ($totalIncome == 0 && $salesRevenue > 0) {
        $totalIncome = $salesRevenue;
    }

} catch (Exception $e) {
    // Se houver erro geral, mantém os valores padrão
}

$pageTitle = 'Relatórios';
include __DIR__ . '/../includes/dashboard-header.php';
?>

<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>


<style>
.report-section {
    margin-bottom: 2rem;
}

.report-section h2 {
    font-size: 1.1rem;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.ranking-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.ranking-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border);
}

.ranking-item:last-child {
    border-bottom: none;
}

.ranking-position {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: var(--primary);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 0.85rem;
}

.ranking-position.gold { background: #F59E0B; }
.ranking-position.silver { background: #9CA3AF; }
.ranking-position.bronze { background: #CD7F32; }

.ranking-info {
    flex: 1;
    min-width: 0;
}

.ranking-name {
    font-weight: 600;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.ranking-stats {
    font-size: 0.85rem;
    color: var(--text-muted);
}

.ranking-value {
    font-weight: 700;
    color: var(--success);
    white-space: nowrap;
}

/* FILTRO - DESIGN RESPONSIVO */
.filter-section{border-radius:var(--radius-lg);padding:1rem;margin-bottom:1.5rem;overflow:hidden}
.filter-header{display:flex;align-items:center;justify-content:space-between;gap:.5rem}
.filter-title{display:flex;align-items:center;gap:.5rem;font-size:.85rem;font-weight:600;color:var(--text-secondary);margin:0}
.filter-title iconify-icon{font-size:1rem;color:var(--primary)}
.filter-period-badge{display:none;align-items:center;gap:.25rem;padding:.25rem .6rem;background:var(--primary);border-radius:50px;font-size:.7rem;font-weight:600;color:#000}
.filter-toggle-btn{display:none;align-items:center;justify-content:center;width:32px;height:32px;background:var(--bg-dark);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-secondary);cursor:pointer}
.filter-toggle-btn:hover,.filter-toggle-btn.active{border-color:var(--primary);color:var(--primary)}
.filter-toggle-btn iconify-icon{font-size:1rem}
.filter-body{display:flex;align-items:center;gap:1rem;margin-top:.75rem}
.filter-scroll{flex:1;overflow:hidden}
.filter-pills{display:flex;gap:.5rem;flex-wrap:wrap}
.filter-pill{display:inline-flex;align-items:center;gap:.3rem;padding:.45rem .9rem;background:var(--bg-card);border:1px solid var(--border);border-radius:50px;font-size:.8rem;font-weight:500;color:var(--text-secondary);cursor:pointer;transition:all .2s;text-decoration:none;white-space:nowrap}
.filter-pill:hover{border-color:var(--primary);color:var(--primary)}
.filter-pill.active{background:linear-gradient(135deg, var(--primary) 0%, #FFD700 100%);border-color:var(--primary);color:#000}
.filter-pill iconify-icon{font-size:.9rem}
.filter-sep{width:1px;height:28px;background:var(--border);flex-shrink:0}
.filter-dates{display:flex;align-items:center;gap:.5rem;flex-shrink:0}
.filter-dates input[type=date]{padding:.4rem .5rem;background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--text-primary);font-size:.8rem;width:130px}
.filter-dates input[type=date]:focus{outline:none;border-color:var(--primary)}
.filter-dates .sep{color:var(--text-muted);font-size:.75rem}
.filter-dates .btn-apply{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;background:var(--primary);border:none;border-radius:var(--radius-md);color:#000;cursor:pointer}
.filter-dates .btn-apply:hover{transform:scale(1.05)}

/* TABLET */
@media(max-width:992px){
.filter-body{flex-direction:column;align-items:stretch;gap:.75rem}
.filter-scroll{width:100%}
.filter-pills{flex-wrap:wrap;justify-content:flex-start}
.filter-sep{display:none}
.filter-dates{width:100%;justify-content:space-between;padding-top:.5rem;border-top:1px solid var(--border)}
.filter-dates input[type=date]{flex:1;width:auto}
}

/* MOBILE */
@media(max-width:768px){
.filter-period-badge{display:inline-flex;align-items:center;gap:.25rem;padding:.25rem .6rem;background:var(--primary);border-radius:50px;font-size:.7rem;font-weight:600;color:#000}
.filter-section{padding:.75rem}
.filter-header{margin-bottom:0}
.filter-toggle-btn{display:flex}
.filter-body{display:none;margin-top:.75rem;padding-top:.75rem;border-top:1px solid var(--border)}
.filter-body.show{display:flex}
.filter-pills{gap:.3rem}
.filter-pill{padding:.35rem .6rem;font-size:.75rem}
.filter-pill iconify-icon{font-size:.8rem}
.filter-dates{gap:.3rem}
.filter-dates input[type=date]{padding:.35rem .4rem;font-size:.75rem}
.filter-dates .btn-apply{width:28px;height:28px}
}

/* MOBILE SMALL */
@media(max-width:480px){
.filter-section{padding:.6rem}
.filter-pill{padding:.3rem .5rem;font-size:.7rem}
.filter-pill iconify-icon{display:none}
.filter-period-badge{font-size:.65rem;padding:.2rem .45rem}
.filter-dates input[type=date]{font-size:.7rem;padding:.3rem}
}

.report-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
}

@media (max-width: 600px) {
    .report-grid {
        grid-template-columns: 1fr;
    }
}

.empty-report {
    color: var(--text-muted);
    text-align: center;
    padding: 2rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
}

.empty-report iconify-icon {
    font-size: 2.5rem;
    opacity: 0.5;
}
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:chart-bold"></iconify-icon> Relatórios</h1>
                <p>Análise de desempenho do seu negócio</p>
            </div>
        </div>

        <!-- Período -->
        <section class="filter-section glass-card">
                <div class="filter-header">
                    <div style="display:flex;align-items:center;gap:.75rem;flex-wrap:wrap">
                        <h3 class="filter-title">
                            <iconify-icon icon="solar:calendar-bold"></iconify-icon>
                            Período
                        </h3>
                        <span class="filter-period-badge"><?= $periodLabel ?></span>
                    </div>
                    <button type="button" class="filter-toggle-btn" onclick="toggleFilter(this)" aria-label="Expandir filtro">
                        <iconify-icon icon="solar:alt-arrow-down-linear"></iconify-icon>
                    </button>
                </div>

                <div class="filter-body">
                    <div class="filter-scroll">
                        <div class="filter-pills">
                            <a href="?period=today" class="filter-pill <?= $period == 'today' ? 'active' : '' ?>">
                                <iconify-icon icon="solar:sun-bold"></iconify-icon> Hoje
                            </a>
                            <a href="?period=yesterday" class="filter-pill <?= $period == 'yesterday' ? 'active' : '' ?>">
                                <iconify-icon icon="solar:calendar-minimalistic-bold"></iconify-icon> Ontem
                            </a>
                            <a href="?period=week" class="filter-pill <?= $period == 'week' ? 'active' : '' ?>">
                                <iconify-icon icon="solar:calendar-bold"></iconify-icon> 7 dias
                            </a>
                            <a href="?period=month" class="filter-pill <?= $period == 'month' ? 'active' : '' ?>">
                                <iconify-icon icon="solar:calendar-date-bold"></iconify-icon> Este mês
                            </a>
                            <a href="?period=last_month" class="filter-pill <?= $period == 'last_month' ? 'active' : '' ?>">
                                <iconify-icon icon="solar:calendar-mark-bold"></iconify-icon> Mês passado
                            </a>
                        </div>
                    </div>

                    <div class="filter-sep"></div>

                    <form method="get" class="filter-dates">
                        <input type="hidden" name="period" value="custom">
                        <input type="date" name="from" value="<?= $dateFrom ?>" max="<?= date('Y-m-d') ?>">
                        <span class="sep">até</span>
                        <input type="date" name="to" value="<?= $dateTo ?>" max="<?= date('Y-m-d') ?>">
                        <button type="submit" class="btn-apply" title="Aplicar período">
                            <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
                        </button>
                    </form>
                </div>
            </section>

            <script>
            function toggleFilter(btn) {
                const body = btn.closest('.filter-section').querySelector('.filter-body');
                const icon = btn.querySelector('iconify-icon');
                body.classList.toggle('show');
                btn.classList.toggle('active');
                icon.setAttribute('icon', body.classList.contains('show') ? 'solar:alt-arrow-up-linear' : 'solar:alt-arrow-down-linear');
            }
            </script>

        <!-- Cards de Resumo Rápido -->
        <div class="stats-grid" style="margin-bottom: 1.5rem;">
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(59, 130, 246, 0.1); color: #3B82F6;">
                    <iconify-icon icon="solar:bag-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= $totalOrders ?></span>
                    <span class="stat-label">Total Pedidos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= $completedOrders ?></span>
                    <span class="stat-label">Concluídos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(245, 158, 11, 0.1); color: #F59E0B;">
                    <iconify-icon icon="solar:dollar-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value">R$ <?= number_format($salesRevenue, 2, ',', '.') ?></span>
                    <span class="stat-label">Receita Vendas</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(239, 68, 68, 0.1); color: #EF4444;">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?= $cancelledOrders ?></span>
                    <span class="stat-label">Cancelados</span>
                </div>
            </div>
        </div>

        <!-- Relatórios Detalhados -->
        <div class="report-grid">
            <?php if ($isBarbershop): ?>
            <!-- Top Serviços -->
            <div class="card report-section">
                <h2><iconify-icon icon="solar:scissors-bold"></iconify-icon> Top Serviços</h2>
                <?php if (empty($topServices)): ?>
                <div class="empty-report">
                    <iconify-icon icon="solar:scissors-bold"></iconify-icon>
                    <p>Sem dados no período</p>
                </div>
                <?php else: ?>
                <ul class="ranking-list">
                    <?php foreach ($topServices as $i => $service): ?>
                    <li class="ranking-item">
                        <span class="ranking-position <?php echo $i === 0 ? 'gold' : ($i === 1 ? 'silver' : ($i === 2 ? 'bronze' : '')); ?>">
                            <?php echo $i + 1; ?>
                        </span>
                        <div class="ranking-info">
                            <div class="ranking-name"><?php echo htmlspecialchars($service['name']); ?></div>
                            <div class="ranking-stats"><?php echo $service['count']; ?> atendimentos</div>
                        </div>
                        <span class="ranking-value">R$ <?php echo number_format($service['revenue'], 0, ',', '.'); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>

            <!-- Top Profissionais -->
            <div class="card report-section">
                <h2><iconify-icon icon="solar:user-bold"></iconify-icon> Top Profissionais</h2>
                <?php if (empty($topTeam)): ?>
                <div class="empty-report">
                    <iconify-icon icon="solar:user-bold"></iconify-icon>
                    <p>Sem dados no período</p>
                </div>
                <?php else: ?>
                <ul class="ranking-list">
                    <?php foreach ($topTeam as $i => $member): ?>
                    <li class="ranking-item">
                        <span class="ranking-position <?php echo $i === 0 ? 'gold' : ($i === 1 ? 'silver' : ($i === 2 ? 'bronze' : '')); ?>">
                            <?php echo $i + 1; ?>
                        </span>
                        <div class="ranking-info">
                            <div class="ranking-name"><?php echo htmlspecialchars($member['name']); ?></div>
                            <div class="ranking-stats"><?php echo $member['count']; ?> atendimentos</div>
                        </div>
                        <span class="ranking-value">R$ <?php echo number_format($member['revenue'], 0, ',', '.'); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>

            <?php else: ?>
            <!-- Top Produtos -->
            <div class="card report-section">
                <h2><iconify-icon icon="solar:box-bold"></iconify-icon> Top Produtos</h2>
                <?php if (empty($topProducts)): ?>
                <div class="empty-report">
                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                    <p>Sem vendas no período selecionado</p>
                </div>
                <?php else: ?>
                <ul class="ranking-list">
                    <?php foreach ($topProducts as $i => $product): ?>
                    <li class="ranking-item">
                        <span class="ranking-position <?php echo $i === 0 ? 'gold' : ($i === 1 ? 'silver' : ($i === 2 ? 'bronze' : '')); ?>">
                            <?php echo $i + 1; ?>
                        </span>
                        <div class="ranking-info">
                            <div class="ranking-name"><?php echo htmlspecialchars($product['name']); ?></div>
                            <div class="ranking-stats"><?php echo intval($product['quantity']); ?> vendidos</div>
                        </div>
                        <span class="ranking-value">R$ <?php echo number_format($product['revenue'] ?? 0, 0, ',', '.'); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>

            <!-- Top Categorias -->
            <div class="card report-section">
                <h2><iconify-icon icon="solar:folder-bold"></iconify-icon> Top Categorias</h2>
                <?php if (empty($topCategories)): ?>
                <div class="empty-report">
                    <iconify-icon icon="solar:folder-bold"></iconify-icon>
                    <p>Sem vendas no período selecionado</p>
                </div>
                <?php else: ?>
                <ul class="ranking-list">
                    <?php foreach ($topCategories as $i => $category): ?>
                    <li class="ranking-item">
                        <span class="ranking-position <?php echo $i === 0 ? 'gold' : ($i === 1 ? 'silver' : ($i === 2 ? 'bronze' : '')); ?>">
                            <?php echo $i + 1; ?>
                        </span>
                        <div class="ranking-info">
                            <div class="ranking-name"><?php echo htmlspecialchars($category['name']); ?></div>
                            <div class="ranking-stats"><?php echo intval($category['quantity'] ?? 0); ?> itens vendidos</div>
                        </div>
                        <span class="ranking-value">R$ <?php echo number_format($category['revenue'] ?? 0, 0, ',', '.'); ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Resumo Financeiro -->
            <div class="card report-section" style="grid-column: 1 / -1;">
                <h2><iconify-icon icon="solar:wallet-bold"></iconify-icon> Resumo Financeiro</h2>
                <div class="stats-grid" style="margin-top: 1rem;">
                    <div class="stat-card">
                        <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                            <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                        </div>
                        <div class="stat-content">
                            <span class="stat-value" style="color: #22C55E;">R$ <?php echo number_format($totalIncome, 2, ',', '.'); ?></span>
                            <span class="stat-label">Total Receitas</span>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon" style="background: rgba(239, 68, 68, 0.1); color: #EF4444;">
                            <iconify-icon icon="solar:arrow-down-bold"></iconify-icon>
                        </div>
                        <div class="stat-content">
                            <span class="stat-value" style="color: #EF4444;">R$ <?php echo number_format($totalExpense, 2, ',', '.'); ?></span>
                            <span class="stat-label">Total Despesas</span>
                        </div>
                    </div>
                    <div class="stat-card" style="grid-column: span 2;">
                        <div class="stat-icon" style="background: rgba(<?php echo ($totalIncome - $totalExpense) >= 0 ? '34, 197, 94' : '239, 68, 68'; ?>, 0.1); color: <?php echo ($totalIncome - $totalExpense) >= 0 ? '#22C55E' : '#EF4444'; ?>;">
                            <iconify-icon icon="solar:chart-bold"></iconify-icon>
                        </div>
                        <div class="stat-content">
                            <span class="stat-value" style="color: <?php echo ($totalIncome - $totalExpense) >= 0 ? '#22C55E' : '#EF4444'; ?>;">
                                <?php echo ($totalIncome - $totalExpense) >= 0 ? '+' : ''; ?>R$ <?php echo number_format($totalIncome - $totalExpense, 2, ',', '.'); ?>
                            </span>
                            <span class="stat-label">Lucro/Prejuízo</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
