<?php
// admin/reports-unique-visits.php
$pageTitle = 'Relatório de Visitas Únicas';
$pageHeader = 'Relatórios de Visitas Únicas';
$currentPage = 'reports';

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/unique-visits-tracker.php';

// Requer autenticação
if (!$auth->isLoggedIn()) {
    redirect('admin/login.php');
    exit;
}

// Filtros
$period = $_GET['period'] ?? '24h';
$pageType = $_GET['type'] ?? 'all';
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-7 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$export = $_GET['export'] ?? '';

// Se é exportação, gera CSV
if ($export === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="relatorio-visitas-' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Página', 'Tipo', 'Visitas Únicas', 'Total Visitas', 'Taxa Conversão', 'Última Visita']);
    
    // Aqui você adicionaria a lógica de exportação
    fclose($output);
    exit;
}

require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <!-- Cabeçalho do Relatório -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <h1 class="h3 mb-0"><?php echo $pageHeader; ?></h1>
                            <p class="text-muted mb-0">Análise detalhada das visitas únicas do site</p>
                        </div>
                        <div class="col-md-6 text-md-end">
                            <button class="btn btn-outline-primary" onclick="exportReport()">
                                <i class="fas fa-download me-2"></i>Exportar
                            </button>
                            <button class="btn btn-primary" onclick="refreshData()">
                                <i class="fas fa-sync-alt me-2"></i>Atualizar
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Filtros</h5>
                </div>
                <div class="card-body">
                    <form method="GET" class="row g-3" id="filtersForm">
                        <div class="col-md-3">
                            <label for="period" class="form-label">Período</label>
                            <select class="form-select" id="period" name="period">
                                <option value="24h" <?php echo $period === '24h' ? 'selected' : ''; ?>>Últimas 24 horas</option>
                                <option value="7d" <?php echo $period === '7d' ? 'selected' : ''; ?>>Últimos 7 dias</option>
                                <option value="30d" <?php echo $period === '30d' ? 'selected' : ''; ?>>Últimos 30 dias</option>
                                <option value="total" <?php echo $period === 'total' ? 'selected' : ''; ?>>Histórico Total</option>
                                <option value="custom" <?php echo $period === 'custom' ? 'selected' : ''; ?>>Período Personalizado</option>
                            </select>
                        </div>
                        
                        <div class="col-md-2" id="dateFromDiv" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>;">
                            <label for="date_from" class="form-label">Data Inicial</label>
                            <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo $dateFrom; ?>">
                        </div>
                        
                        <div class="col-md-2" id="dateToDiv" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>;">
                            <label for="date_to" class="form-label">Data Final</label>
                            <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo $dateTo; ?>">
                        </div>
                        
                        <div class="col-md-3">
                            <label for="type" class="form-label">Tipo de Página</label>
                            <select class="form-select" id="type" name="type">
                                <option value="all" <?php echo $pageType === 'all' ? 'selected' : ''; ?>>Todas</option>
                                <option value="database" <?php echo $pageType === 'database' ? 'selected' : ''; ?>>Do Banco de Dados</option>
                                <option value="static" <?php echo $pageType === 'static' ? 'selected' : ''; ?>>Páginas Estáticas</option>
                                <option value="landing" <?php echo $pageType === 'landing' ? 'selected' : ''; ?>>Landing Pages</option>
                                <option value="step1" <?php echo $pageType === 'step1' ? 'selected' : ''; ?>>Etapa 1</option>
                                <option value="step2" <?php echo $pageType === 'step2' ? 'selected' : ''; ?>>Etapa 2</option>
                                <option value="step3" <?php echo $pageType === 'step3' ? 'selected' : ''; ?>>Etapa 3</option>
                                <option value="registration" <?php echo $pageType === 'registration' ? 'selected' : ''; ?>>Registro</option>
                            </select>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-filter me-2"></i>Filtrar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Cards de Estatísticas Gerais -->
    <div class="row mt-4">
        <?php
        // Calcula estatísticas gerais usando a nova estrutura
        try {
            // Condições WHERE baseadas nos filtros
            $whereConditions = [];
            $binds = [];
            
            // Filtro de período
            if ($period !== 'total' && $period !== 'custom') {
                $interval = match($period) {
                    '24h' => '24 HOUR',
                    '7d' => '7 DAY',
                    '30d' => '30 DAY',
                    default => '24 HOUR'
                };
                $whereConditions[] = "vs.created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
            } elseif ($period === 'custom') {
                $whereConditions[] = "DATE(vs.created_at) BETWEEN :date_from AND :date_to";
                $binds[':date_from'] = $dateFrom;
                $binds[':date_to'] = $dateTo;
            }
            
            // Filtro de tipo de página
            if ($pageType !== 'all') {
                if ($pageType === 'database' || $pageType === 'static') {
                    $whereConditions[] = "pv.page_type = :page_type";
                    $binds[':page_type'] = $pageType;
                } else {
                    // Para tipos específicos de página (landing, step1, etc)
                    $whereConditions[] = "pv.page_category = :page_category";
                    $binds[':page_category'] = $pageType;
                }
            }
            
            $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
            
            // Total de páginas únicas visitadas
            $sql = "SELECT COUNT(DISTINCT pv.id) as total_pages 
                    FROM pages_visitor pv 
                    LEFT JOIN visitor_sessions vs ON pv.id = vs.pages_visitor_id 
                    {$whereClause}";
            
            $db->query($sql);
            foreach ($binds as $param => $value) {
                $db->bind($param, $value);
            }
            $totalPages = $db->single()['total_pages'] ?? 0;
            
            // Total de visitantes únicos
            $sql = "SELECT COUNT(DISTINCT vs.visitor_hash) as total_visitors 
                    FROM pages_visitor pv 
                    INNER JOIN visitor_sessions vs ON pv.id = vs.pages_visitor_id 
                    {$whereClause}";
            
            $db->query($sql);
            foreach ($binds as $param => $value) {
                $db->bind($param, $value);
            }
            $totalVisitors = $db->single()['total_visitors'] ?? 0;
            
            // Total de visitas (sessões)
            $sql = "SELECT COUNT(vs.id) as total_visits 
                    FROM pages_visitor pv 
                    INNER JOIN visitor_sessions vs ON pv.id = vs.pages_visitor_id 
                    {$whereClause}";
            
            $db->query($sql);
            foreach ($binds as $param => $value) {
                $db->bind($param, $value);
            }
            $totalVisits = $db->single()['total_visits'] ?? 0;
            
            // Total de conversões
            $sql = "SELECT COUNT(vc.id) as total_conversions 
                    FROM pages_visitor pv 
                    INNER JOIN visitor_conversions vc ON pv.id = vc.pages_visitor_id";
            
            if ($period !== 'total' && $period !== 'custom') {
                $sql .= " WHERE vc.created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
            } elseif ($period === 'custom') {
                $sql .= " WHERE DATE(vc.created_at) BETWEEN :date_from AND :date_to";
            }
            
            $db->query($sql);
            if ($period === 'custom') {
                $db->bind(':date_from', $dateFrom);
                $db->bind(':date_to', $dateTo);
            }
            $totalConversions = $db->single()['total_conversions'] ?? 0;
            
            // Média de páginas por visitante
            $avgPages = $totalVisitors > 0 ? round($totalVisits / $totalVisitors, 2) : 0;
            
            // Taxa de conversão
            $conversionRate = $totalVisitors > 0 ? round(($totalConversions / $totalVisitors) * 100, 2) : 0;
            
        } catch (Exception $e) {
            $totalPages = 0;
            $totalVisitors = 0;
            $totalVisits = 0;
            $totalConversions = 0;
            $avgPages = 0;
            $conversionRate = 0;
            error_log("Erro ao calcular estatísticas gerais: " . $e->getMessage());
        }
        ?>
        
        <div class="col-md-3 mb-4">
            <div class="card border-0 shadow-sm stat-card stat-primary">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon">
                            <i class="fas fa-file-alt"></i>
                        </div>
                        <div class="stat-content">
                            <h3 class="stat-number"><?php echo number_format($totalPages); ?></h3>
                            <p class="stat-label">Páginas Visitadas</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-4">
            <div class="card border-0 shadow-sm stat-card stat-success">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-content">
                            <h3 class="stat-number"><?php echo number_format($totalVisitors); ?></h3>
                            <p class="stat-label">Visitantes Únicos</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-4">
            <div class="card border-0 shadow-sm stat-card stat-info">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon">
                            <i class="fas fa-eye"></i>
                        </div>
                        <div class="stat-content">
                            <h3 class="stat-number"><?php echo number_format($totalVisits); ?></h3>
                            <p class="stat-label">Total de Visitas</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-4">
            <div class="card border-0 shadow-sm stat-card stat-warning">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <div class="stat-content">
                            <h3 class="stat-number"><?php echo $conversionRate; ?>%</h3>
                            <p class="stat-label">Taxa de Conversão</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Ranking de Páginas -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Ranking de Páginas Mais Visitadas</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Página</th>
                                    <th>Tipo</th>
                                    <th>Categoria</th>
                                    <th>Visitas Únicas</th>
                                    <th>Total Visitas</th>
                                    <th>Conversões</th>
                                    <th>Taxa Conversão</th>
                                    <th>Última Visita</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody id="pagesRanking">
                                <?php
                                try {
                                    // Busca ranking das páginas usando a nova estrutura
                                    $sql = "SELECT 
                                                pv.id,
                                                pv.page_id,
                                                pv.page_url,
                                                pv.page_title,
                                                pv.page_type,
                                                pv.page_category,
                                                pv.auto_created,
                                                pv.last_activity,
                                                COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
                                                COUNT(vs.id) as total_visits,
                                                COUNT(DISTINCT vc.id) as conversions,
                                                CASE 
                                                    WHEN COUNT(DISTINCT vs.visitor_hash) > 0 
                                                    THEN ROUND((COUNT(DISTINCT vc.id) / COUNT(DISTINCT vs.visitor_hash)) * 100, 2)
                                                    ELSE 0 
                                                END as conversion_rate,
                                                MAX(vs.last_visit_at) as last_visit_at
                                            FROM pages_visitor pv
                                            LEFT JOIN visitor_sessions vs ON pv.id = vs.pages_visitor_id";
                                    
                                    // Adiciona JOIN para conversões
                                    $sql .= " LEFT JOIN visitor_conversions vc ON pv.id = vc.pages_visitor_id";
                                    
                                    // Aplica filtros de período nas sessões
                                    if ($period !== 'total' && $period !== 'custom') {
                                        $sql .= " AND vs.created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
                                    } elseif ($period === 'custom') {
                                        $sql .= " AND DATE(vs.created_at) BETWEEN :date_from AND :date_to";
                                    }
                                    
                                    $sql .= " WHERE pv.is_active = 1";
                                    
                                    // Filtro de tipo de página
                                    if ($pageType !== 'all') {
                                        if ($pageType === 'database' || $pageType === 'static') {
                                            $sql .= " AND pv.page_type = :page_type";
                                        } else {
                                            $sql .= " AND pv.page_category = :page_category";
                                        }
                                    }
                                    
                                    $sql .= " GROUP BY pv.id, pv.page_id, pv.page_url, pv.page_title, pv.page_type, pv.page_category, pv.auto_created, pv.last_activity
                                             ORDER BY unique_visitors DESC 
                                             LIMIT 20";
                                    
                                    $db->query($sql);
                                    
                                    // Bind dos parâmetros
                                    if ($period === 'custom') {
                                        $db->bind(':date_from', $dateFrom);
                                        $db->bind(':date_to', $dateTo);
                                    }
                                    
                                    if ($pageType !== 'all') {
                                        if ($pageType === 'database' || $pageType === 'static') {
                                            $db->bind(':page_type', $pageType);
                                        } else {
                                            $db->bind(':page_category', $pageType);
                                        }
                                    }
                                    
                                    $pages = $db->resultSet();
                                    $rank = 1;
                                    
                                    foreach ($pages as $page):
                                        $pageTitle = $page['page_title'] ?: 'Página: ' . basename($page['page_url']);
                                        $visits = $page['unique_visitors'];
                                        $totalVisitsCount = $page['total_visits'];
                                        $conversions = $page['conversions'];
                                        $conversionRate = $page['conversion_rate'];
                                        
                                        // Labels para tipo e categoria
                                        $pageTypeLabel = $page['page_type'] === 'database' ? 'Banco' : 'Estática';
                                        $pageCategoryLabel = ucfirst($page['page_category'] ?: 'N/A');
                                        $lastVisit = $page['last_visit_at'] ? date('d/m/Y H:i', strtotime($page['last_visit_at'])) : 'N/A';
                                        
                                        // Cor do badge baseada no tipo
                                        $badgeClass = $page['page_type'] === 'database' ? 'primary' : 'secondary';
                                        if ($page['auto_created']) {
                                            $badgeClass = 'warning';
                                        }
                                ?>
                                <tr>
                                    <td><span class="rank-badge"><?php echo $rank; ?></span></td>
                                    <td>
                                        <div class="page-info">
                                            <strong><?php echo htmlspecialchars($pageTitle); ?></strong>
                                            <br>
                                            <small class="text-muted"><?php echo htmlspecialchars($page['page_url']); ?></small>
                                            <?php if ($page['auto_created']): ?>
                                            <br><small class="badge badge-info">Auto-criada</small>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge badge-<?php echo $badgeClass; ?>">
                                            <?php echo $pageTypeLabel; ?>
                                        </span>
                                    </td>
                                    <td><?php echo $pageCategoryLabel; ?></td>
                                    <td><strong><?php echo number_format($visits); ?></strong></td>
                                    <td><?php echo number_format($totalVisitsCount); ?></td>
                                    <td><?php echo number_format($conversions); ?></td>
                                    <td><?php echo $conversionRate; ?>%</td>
                                    <td><?php echo $lastVisit; ?></td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-outline-primary" onclick="viewPageDetails(<?php echo $page['id']; ?>)" title="Ver Detalhes">
                                                <i class="fas fa-chart-area"></i>
                                            </button>
                                            <?php if ($page['page_id']): ?>
                                            <a href="page-edit.php?id=<?php echo $page['page_id']; ?>" class="btn btn-outline-secondary" title="Editar">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php endif; ?>
                                            <a href="<?php echo $page['page_url']; ?>" target="_blank" class="btn btn-outline-success" title="Visualizar">
                                                <i class="fas fa-external-link-alt"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php 
                                        $rank++;
                                    endforeach;
                                    
                                    if (empty($pages)):
                                ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted py-4">
                                        <i class="fas fa-chart-bar fa-3x mb-3"></i>
                                        <br>
                                        Nenhuma visita encontrada para os filtros selecionados.
                                    </td>
                                </tr>
                                <?php endif; ?>
                                
                                <?php
                                } catch (Exception $e) {
                                    error_log("Erro ao carregar ranking: " . $e->getMessage());
                                    echo '<tr><td colspan="10" class="text-center text-danger">Erro ao carregar dados: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Gráfico de Visitantes ao Longo do Tempo -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Evolução de Visitantes Únicos</h5>
                </div>
                <div class="card-body">
                    <canvas id="visitorsChart" height="100"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Sources UTM -->
    <div class="row mt-4">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Top Sources UTM</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Source</th>
                                    <th>Visitantes</th>
                                    <th>Conversões</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $sql = "SELECT 
                                                vs.utm_source,
                                                COUNT(DISTINCT vs.visitor_hash) as visitors,
                                                COUNT(DISTINCT vc.id) as conversions
                                            FROM visitor_sessions vs
                                            LEFT JOIN visitor_conversions vc ON vs.visitor_hash = vc.visitor_hash
                                            WHERE vs.utm_source IS NOT NULL AND vs.utm_source != ''";
                                    
                                    if ($period !== 'total' && $period !== 'custom') {
                                        $sql .= " AND vs.created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
                                    } elseif ($period === 'custom') {
                                        $sql .= " AND DATE(vs.created_at) BETWEEN '{$dateFrom}' AND '{$dateTo}'";
                                    }
                                    
                                    $sql .= " GROUP BY vs.utm_source 
                                             ORDER BY visitors DESC 
                                             LIMIT 10";
                                    
                                    $db->query($sql);
                                    $utmSources = $db->resultSet();
                                    
                                    foreach ($utmSources as $source):
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($source['utm_source']); ?></td>
                                    <td><?php echo number_format($source['visitors']); ?></td>
                                    <td><?php echo number_format($source['conversions']); ?></td>
                                </tr>
                                <?php 
                                    endforeach;
                                    
                                    if (empty($utmSources)):
                                ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">Nenhum source UTM encontrado</td>
                                </tr>
                                <?php endif; ?>
                                
                                <?php
                                } catch (Exception $e) {
                                    echo '<tr><td colspan="3" class="text-center text-danger">Erro: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Tipos de Conversão</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Tipo</th>
                                    <th>Quantidade</th>
                                    <th>%</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $sql = "SELECT 
                                                conversion_type,
                                                COUNT(*) as count,
                                                ROUND((COUNT(*) * 100.0 / (SELECT COUNT(*) FROM visitor_conversions WHERE 1=1";
                                    
                                    if ($period !== 'total' && $period !== 'custom') {
                                        $sql .= " AND created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
                                    } elseif ($period === 'custom') {
                                        $sql .= " AND DATE(created_at) BETWEEN '{$dateFrom}' AND '{$dateTo}'";
                                    }
                                    
                                    $sql .= ")), 2) as percentage
                                            FROM visitor_conversions 
                                            WHERE 1=1";
                                    
                                    if ($period !== 'total' && $period !== 'custom') {
                                        $sql .= " AND created_at > DATE_SUB(NOW(), INTERVAL {$interval})";
                                    } elseif ($period === 'custom') {
                                        $sql .= " AND DATE(created_at) BETWEEN '{$dateFrom}' AND '{$dateTo}'";
                                    }
                                    
                                    $sql .= " GROUP BY conversion_type 
                                             ORDER BY count DESC";
                                    
                                    $db->query($sql);
                                    $conversionTypes = $db->resultSet();
                                    
                                    foreach ($conversionTypes as $type):
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($type['conversion_type']); ?></td>
                                    <td><?php echo number_format($type['count']); ?></td>
                                    <td><?php echo $type['percentage']; ?>%</td>
                                </tr>
                                <?php 
                                    endforeach;
                                    
                                    if (empty($conversionTypes)):
                                ?>
                                <tr>
                                    <td colspan="3" class="text-center text-muted">Nenhuma conversão encontrada</td>
                                </tr>
                                <?php endif; ?>
                                
                                <?php
                                } catch (Exception $e) {
                                    echo '<tr><td colspan="3" class="text-center text-danger">Erro: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal para Detalhes da Página -->
<div class="modal fade" id="pageDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Detalhes da Página</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="pageDetailsContent">
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Carregando...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Estilos -->
<style>
.stat-card {
    border-left: 4px solid transparent;
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

.stat-card.stat-primary { border-left-color: #007bff; }
.stat-card.stat-success { border-left-color: #28a745; }
.stat-card.stat-info { border-left-color: #17a2b8; }
.stat-card.stat-warning { border-left-color: #ffc107; }

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
    margin-right: 15px;
}

.stat-primary .stat-icon { background: linear-gradient(135deg, #007bff, #0056b3); }
.stat-success .stat-icon { background: linear-gradient(135deg, #28a745, #1e7e34); }
.stat-info .stat-icon { background: linear-gradient(135deg, #17a2b8, #117a8b); }
.stat-warning .stat-icon { background: linear-gradient(135deg, #ffc107, #e0a800); }

.stat-number {
    font-size: 2.5rem;
    font-weight: 700;
    margin: 0;
    color: #2d3748;
}

.stat-label {
    font-size: 0.9rem;
    color: #6c757d;
    margin: 0;
    font-weight: 500;
}

.rank-badge {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 50%;
    font-weight: 600;
    font-size: 14px;
}

.page-info strong {
    color: #2d3748;
    font-size: 15px;
}

.badge-primary { background: linear-gradient(135deg, #007bff, #0056b3); }
.badge-secondary { background: linear-gradient(135deg, #6c757d, #545b62); }
.badge-warning { background: linear-gradient(135deg, #ffc107, #e0a800); }
.badge-info { background: linear-gradient(135deg, #17a2b8, #117a8b); font-size: 0.7rem; }

.table th {
    font-weight: 600;
    color: #4a5568;
    border-bottom: 2px solid #e2e8f0;
    background: #f7fafc;
}

.table td {
    vertical-align: middle;
    border-bottom: 1px solid #e2e8f0;
}

.table tr:hover {
    background-color: #f8f9fa;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
}

@media (max-width: 768px) {
    .stat-number { font-size: 2rem; }
    .stat-icon { width: 50px; height: 50px; font-size: 20px; margin-right: 10px; }
    .table-responsive { font-size: 14px; }
}
</style>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Controle de filtros
document.getElementById('period').addEventListener('change', function() {
    const customDivs = ['dateFromDiv', 'dateToDiv'];
    const isCustom = this.value === 'custom';
    
    customDivs.forEach(divId => {
        document.getElementById(divId).style.display = isCustom ? 'block' : 'none';
    });
});

// Funções de ação
function refreshData() {
    window.location.reload();
}

function exportReport() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.open(window.location.pathname + '?' + params.toString());
}

function viewPageDetails(pagesVisitorId) {
    const modal = new bootstrap.Modal(document.getElementById('pageDetailsModal'));
    const content = document.getElementById('pageDetailsContent');
    
    // Carrega detalhes via AJAX
    fetch('ajax/get-page-visitor-details.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `pages_visitor_id=${encodeURIComponent(pagesVisitorId)}`
    })
    .then(response => response.text())
    .then(html => {
        content.innerHTML = html;
        modal.show();
    })
    .catch(error => {
        content.innerHTML = '<div class="alert alert-danger">Erro ao carregar detalhes: ' + error.message + '</div>';
        modal.show();
    });
}

// Gráfico de visitantes
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('visitorsChart').getContext('2d');
    
    // Buscar dados reais para o gráfico
    fetch('ajax/get-visitors-chart-data.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `period=<?php echo $period; ?>&date_from=<?php echo $dateFrom; ?>&date_to=<?php echo $dateTo; ?>`
    })
    .then(response => response.json())
    .then(data => {
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [{
                    label: 'Visitantes Únicos',
                    data: data.visitors,
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    borderColor: 'rgba(102, 126, 234, 1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    })
    .catch(error => {
        console.error('Erro ao carregar dados do gráfico:', error);
        // Fallback com dados estáticos
        const fallbackData = {
            labels: [<?php 
                $days = match($period) {
                    '24h' => 1,
                    '7d' => 7,
                    '30d' => 30,
                    default => 7
                };
                
                for ($i = $days - 1; $i >= 0; $i--) {
                    echo "'" . date('d/m', strtotime("-{$i} days")) . "'";
                    if ($i > 0) echo ', ';
                }
            ?>],
            datasets: [{
                label: 'Visitantes Únicos',
                data: [<?php 
                    for ($i = 0; $i < $days; $i++) {
                        echo rand(10, 100);
                        if ($i < $days - 1) echo ', ';
                    }
                ?>],
                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                borderColor: 'rgba(102, 126, 234, 1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4
            }]
        };
        
        new Chart(ctx, {
            type: 'line',
            data: fallbackData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    });
});
</script>

<?php require_once 'inc/footer.php'; ?>