<?php
// admin/reports.php - Sistema Completo de Relatórios

// Define BASE_PATH apenas se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

$pageTitle = 'Relatórios de Análise';
$pageHeader = 'Relatórios de Análise';
$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/visitor-tracking.php';

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

/**
 * Funções auxiliares
 */
function getPageTypeIcon($type) {
    $icons = [
        'landing' => 'fa-rocket',
        'step1' => 'fa-play-circle',
        'step2' => 'fa-forward',
        'step3' => 'fa-fast-forward',
        'registration' => 'fa-user-plus',
        'about' => 'fa-info-circle',
        'contact' => 'fa-envelope',
        'blog' => 'fa-newspaper',
        'course' => 'fa-graduation-cap',
        'service' => 'fa-cogs',
        'product' => 'fa-box',
        'home' => 'fa-home'
    ];
    return isset($icons[$type]) ? $icons[$type] : 'fa-file-alt';
}

function getPageTypeName($type) {
    $names = [
        'landing' => 'Landing Page',
        'step1' => 'Etapa 1',
        'step2' => 'Etapa 2',
        'step3' => 'Etapa 3',
        'registration' => 'Registro',
        'about' => 'Sobre',
        'contact' => 'Contato',
        'blog' => 'Blog',
        'course' => 'Curso',
        'service' => 'Serviço',
        'product' => 'Produto',
        'home' => 'Início'
    ];
    return isset($names[$type]) ? $names[$type] : ucfirst($type);
}

function calculateEngagementScore($uniqueVisitors, $totalViews, $avgTimeSpent, $bounceRate) {
    if ($uniqueVisitors == 0) return 0;
    
    $viewsPerVisitor = $totalViews / $uniqueVisitors;
    $timeScore = min($avgTimeSpent / 60, 10) * 10; // Max 10 pontos para tempo
    $engagementScore = min($viewsPerVisitor * 20, 40); // Max 40 pontos para views por visitante
    $bounceScore = (100 - $bounceRate) * 0.5; // Max 50 pontos para baixa taxa de rejeição
    
    return round($timeScore + $engagementScore + $bounceScore, 1);
}

// Parâmetros de filtro
$dateStart = isset($_GET['date_start']) ? $_GET['date_start'] : date('Y-m-d', strtotime('-30 days'));
$dateEnd = isset($_GET['date_end']) ? $_GET['date_end'] : date('Y-m-d');
$pageType = isset($_GET['page_type']) ? $_GET['page_type'] : '';
$pageId = isset($_GET['page_id']) ? intval($_GET['page_id']) : 0;
$reportType = isset($_GET['report_type']) ? $_GET['report_type'] : 'unique';
$sortBy = isset($_GET['sort_by']) ? $_GET['sort_by'] : 'unique_visitors';
$sortOrder = isset($_GET['sort_order']) ? $_GET['sort_order'] : 'DESC';
$exportFormat = isset($_GET['export']) ? $_GET['export'] : '';

// Validar datas
if (strtotime($dateStart) > strtotime($dateEnd)) {
    $temp = $dateStart;
    $dateStart = $dateEnd;
    $dateEnd = $temp;
}

// Inicializar variáveis
$allPages = [];
$summary = [
    'total_pages' => 0,
    'total_unique_visitors' => 0,
    'total_views' => 0,
    'avg_engagement_score' => 0,
    'top_performing_page' => null
];
$chartData = [];
$dailyStats = [];
$typeStats = [];

try {
    // === CONSULTA PRINCIPAL PARA TODAS AS PÁGINAS ===
    
    $whereClause = "WHERE 1=1";
    $params = [];
    
    if (!empty($pageType)) {
        $whereClause .= " AND p.type = :page_type";
        $params[':page_type'] = $pageType;
    }
    
    if ($pageId > 0) {
        $whereClause .= " AND p.id = :page_id";
        $params[':page_id'] = $pageId;
    }
    
    // Query principal com todas as estatísticas
    $query = "SELECT 
                p.id,
                p.title,
                p.slug,
                p.type,
                p.published,
                p.created_at,
                p.updated_at,
                
                -- Visitantes únicos no período
                (SELECT COUNT(DISTINCT upv.visitor_hash) 
                 FROM unique_page_visitors upv 
                 WHERE upv.page_id = p.id 
                 AND upv.visit_date BETWEEN :date_start AND :date_end) as unique_visitors,
                
                -- Total de visualizações no período
                (SELECT COUNT(*) 
                 FROM page_views pv 
                 WHERE pv.page_id = p.id 
                 AND DATE(pv.viewed_at) BETWEEN :date_start AND :date_end) as total_views,
                
                -- Visitantes únicos hoje
                (SELECT COUNT(DISTINCT upv.visitor_hash) 
                 FROM unique_page_visitors upv 
                 WHERE upv.page_id = p.id 
                 AND upv.visit_date = CURDATE()) as unique_today,
                
                -- Visualizações hoje
                (SELECT COUNT(*) 
                 FROM page_views pv 
                 WHERE pv.page_id = p.id 
                 AND DATE(pv.viewed_at) = CURDATE()) as views_today,
                
                -- Tempo médio na página (em segundos)
                COALESCE((SELECT AVG(pe.time_spent) 
                         FROM page_engagement pe 
                         WHERE pe.page_id = p.id 
                         AND DATE(pe.created_at) BETWEEN :date_start AND :date_end), 0) as avg_time_spent,
                
                -- Scroll médio
                COALESCE((SELECT AVG(pe.max_scroll) 
                         FROM page_engagement pe 
                         WHERE pe.page_id = p.id 
                         AND DATE(pe.created_at) BETWEEN :date_start AND :date_end), 0) as avg_scroll,
                
                -- Ações/cliques na página
                (SELECT COUNT(*) 
                 FROM page_actions pa 
                 WHERE pa.page_id = p.id 
                 AND DATE(pa.created_at) BETWEEN :date_start AND :date_end) as total_actions,
                
                -- Conversões (cliques em CTA)
                (SELECT COUNT(*) 
                 FROM page_actions pa 
                 WHERE pa.page_id = p.id 
                 AND pa.action_type IN ('cta-click', 'next-step') 
                 AND DATE(pa.created_at) BETWEEN :date_start AND :date_end) as conversions
                
              FROM pages p 
              {$whereClause} 
              ORDER BY {$sortBy} {$sortOrder}";
    
    $params[':date_start'] = $dateStart;
    $params[':date_end'] = $dateEnd;
    
    $db->query($query);
    foreach ($params as $key => $value) {
        $db->bind($key, $value);
    }
    
    $allPages = $db->resultSet();
    
    // Calcular métricas adicionais para cada página
    foreach ($allPages as &$page) {
        // Taxa de conversão
        $page['conversion_rate'] = $page['unique_visitors'] > 0 ? 
            round(($page['conversions'] / $page['unique_visitors']) * 100, 2) : 0;
        
        // Taxa de rejeição (visitantes que saíram sem interagir)
        $page['bounce_rate'] = $page['unique_visitors'] > 0 ? 
            round((($page['unique_visitors'] - $page['total_actions']) / $page['unique_visitors']) * 100, 2) : 0;
        
        // Views por visitante
        $page['views_per_visitor'] = $page['unique_visitors'] > 0 ? 
            round($page['total_views'] / $page['unique_visitors'], 2) : 0;
        
        // Score de engajamento
        $page['engagement_score'] = calculateEngagementScore(
            $page['unique_visitors'], 
            $page['total_views'], 
            $page['avg_time_spent'], 
            $page['bounce_rate']
        );
        
        // Crescimento (comparar com período anterior)
        $previousPeriod = date('Y-m-d', strtotime($dateStart . ' -' . (strtotime($dateEnd) - strtotime($dateStart)) . ' seconds'));
        $previousStart = date('Y-m-d', strtotime($previousPeriod . ' -' . (strtotime($dateEnd) - strtotime($dateStart)) . ' seconds'));
        
        $db->query("SELECT COUNT(DISTINCT visitor_hash) as previous_unique 
                   FROM unique_page_visitors 
                   WHERE page_id = :page_id 
                   AND visit_date BETWEEN :prev_start AND :prev_end");
        $db->bind(':page_id', $page['id']);
        $db->bind(':prev_start', $previousStart);
        $db->bind(':prev_end', $previousPeriod);
        $prevResult = $db->single();
        
        $previousUnique = $prevResult ? $prevResult['previous_unique'] : 0;
        $page['growth_rate'] = $previousUnique > 0 ? 
            round((($page['unique_visitors'] - $previousUnique) / $previousUnique) * 100, 1) : 0;
    }
    
    // === ESTATÍSTICAS RESUMO ===
    
    $summary['total_pages'] = count($allPages);
    $summary['total_unique_visitors'] = array_sum(array_column($allPages, 'unique_visitors'));
    $summary['total_views'] = array_sum(array_column($allPages, 'total_views'));
    
    if ($summary['total_pages'] > 0) {
        $summary['avg_engagement_score'] = round(array_sum(array_column($allPages, 'engagement_score')) / $summary['total_pages'], 1);
        
        // Página com melhor performance
        $topPage = array_reduce($allPages, function($carry, $page) {
            return (!$carry || $page['engagement_score'] > $carry['engagement_score']) ? $page : $carry;
        });
        $summary['top_performing_page'] = $topPage;
    }
    
    // === DADOS PARA GRÁFICOS ===
    
    // Estatísticas diárias
    $db->query("SELECT 
                    visit_date,
                    DATE_FORMAT(visit_date, '%d/%m') as formatted_date,
                    COUNT(DISTINCT visitor_hash) as unique_visitors,
                    (SELECT COUNT(*) FROM page_views WHERE DATE(viewed_at) = visit_date) as total_views
                FROM unique_page_visitors upv
                WHERE visit_date BETWEEN :date_start AND :date_end
                GROUP BY visit_date
                ORDER BY visit_date");
    $db->bind(':date_start', $dateStart);
    $db->bind(':date_end', $dateEnd);
    $dailyStats = $db->resultSet();
    
    // Estatísticas por tipo de página
    $db->query("SELECT 
                    p.type,
                    COUNT(DISTINCT p.id) as page_count,
                    COUNT(DISTINCT upv.visitor_hash) as unique_visitors,
                    COUNT(pv.id) as total_views,
                    AVG(pe.time_spent) as avg_time_spent
                FROM pages p
                LEFT JOIN unique_page_visitors upv ON p.id = upv.page_id 
                    AND upv.visit_date BETWEEN :date_start AND :date_end
                LEFT JOIN page_views pv ON p.id = pv.page_id 
                    AND DATE(pv.viewed_at) BETWEEN :date_start AND :date_end
                LEFT JOIN page_engagement pe ON p.id = pe.page_id 
                    AND DATE(pe.created_at) BETWEEN :date_start AND :date_end
                WHERE p.published = 1
                GROUP BY p.type
                HAVING unique_visitors > 0
                ORDER BY unique_visitors DESC");
    $db->bind(':date_start', $dateStart);
    $db->bind(':date_end', $dateEnd);
    $typeStats = $db->resultSet();
    
    // === EXPORTAÇÃO DE DADOS ===
    
    if (!empty($exportFormat)) {
        $filename = "relatorio_paginas_" . $dateStart . "_" . $dateEnd;
        
        if ($exportFormat === 'csv') {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
            
            $output = fopen('php://output', 'w');
            
            // Cabeçalhos CSV
            fputcsv($output, [
                'ID', 'Título', 'Tipo', 'Status', 'Visitantes Únicos', 'Total de Views', 
                'Views por Visitante', 'Tempo Médio (min)', 'Taxa Conversão (%)', 
                'Taxa Rejeição (%)', 'Score Engajamento', 'Crescimento (%)'
            ]);
            
            // Dados
            foreach ($allPages as $page) {
                fputcsv($output, [
                    $page['id'],
                    $page['title'],
                    getPageTypeName($page['type']),
                    $page['published'] ? 'Publicada' : 'Rascunho',
                    $page['unique_visitors'],
                    $page['total_views'],
                    $page['views_per_visitor'],
                    round($page['avg_time_spent'] / 60, 2),
                    $page['conversion_rate'],
                    $page['bounce_rate'],
                    $page['engagement_score'],
                    $page['growth_rate']
                ]);
            }
            
            fclose($output);
            exit;
        }
        
        if ($exportFormat === 'json') {
            header('Content-Type: application/json; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '.json"');
            
            $exportData = [
                'report_period' => [
                    'start' => $dateStart,
                    'end' => $dateEnd
                ],
                'summary' => $summary,
                'pages' => $allPages,
                'daily_stats' => $dailyStats,
                'type_stats' => $typeStats,
                'generated_at' => date('Y-m-d H:i:s')
            ];
            
            echo json_encode($exportData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
    
} catch (Exception $e) {
    logError("Erro no relatório: " . $e->getMessage());
    $error = $e->getMessage();
}

require_once 'inc/header.php';
?>

<div class="reports-container">
    <!-- Header do Relatório -->
    <div class="reports-header">
        <div class="header-content">
            <div class="header-title">
                <h1><i class="fas fa-chart-line me-3"></i>Relatórios de Análise</h1>
                <p class="subtitle">Análise completa de performance de todas as páginas</p>
            </div>
            <div class="header-actions">
                <div class="period-display">
                    <i class="fas fa-calendar-alt"></i>
                    <span><?php echo date('d/m/Y', strtotime($dateStart)); ?> - <?php echo date('d/m/Y', strtotime($dateEnd)); ?></span>
                </div>
                <div class="export-buttons">
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['export' => 'csv'])); ?>" class="btn btn-outline-success btn-sm">
                        <i class="fas fa-file-csv me-2"></i>CSV
                    </a>
                    <a href="?<?php echo http_build_query(array_merge($_GET, ['export' => 'json'])); ?>" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-file-code me-2"></i>JSON
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros Avançados -->
    <div class="filters-section">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="card-title mb-0">
                    <i class="fas fa-filter me-2"></i>Filtros Avançados
                </h5>
            </div>
            <div class="card-body">
                <form method="GET" action="" class="filters-form">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Data Início</label>
                            <input type="date" class="form-control" name="date_start" value="<?php echo $dateStart; ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Data Fim</label>
                            <input type="date" class="form-control" name="date_end" value="<?php echo $dateEnd; ?>">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Tipo de Página</label>
                            <select class="form-select" name="page_type">
                                <option value="">Todos os tipos</option>
                                <?php 
                                $types = ['landing', 'step1', 'step2', 'step3', 'registration', 'blog', 'about', 'contact', 'course', 'service', 'product', 'home'];
                                foreach ($types as $type): ?>
                                <option value="<?php echo $type; ?>" <?php echo $pageType === $type ? 'selected' : ''; ?>>
                                    <?php echo getPageTypeName($type); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Ordenar por</label>
                            <select class="form-select" name="sort_by">
                                <option value="unique_visitors" <?php echo $sortBy === 'unique_visitors' ? 'selected' : ''; ?>>Visitantes Únicos</option>
                                <option value="total_views" <?php echo $sortBy === 'total_views' ? 'selected' : ''; ?>>Total de Views</option>
                                <option value="conversion_rate" <?php echo $sortBy === 'conversion_rate' ? 'selected' : ''; ?>>Taxa de Conversão</option>
                                <option value="engagement_score" <?php echo $sortBy === 'engagement_score' ? 'selected' : ''; ?>>Score de Engajamento</option>
                                <option value="created_at" <?php echo $sortBy === 'created_at' ? 'selected' : ''; ?>>Data de Criação</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Ordem</label>
                            <select class="form-select" name="sort_order">
                                <option value="DESC" <?php echo $sortOrder === 'DESC' ? 'selected' : ''; ?>>Decrescente</option>
                                <option value="ASC" <?php echo $sortOrder === 'ASC' ? 'selected' : ''; ?>>Crescente</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search me-2"></i>Aplicar Filtros
                            </button>
                            <a href="reports.php" class="btn btn-outline-secondary ms-2">
                                <i class="fas fa-times me-2"></i>Limpar
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Cards de Resumo -->
    <div class="summary-cards">
        <div class="summary-card total-pages">
            <div class="card-icon">
                <i class="fas fa-file-alt"></i>
            </div>
            <div class="card-content">
                <div class="card-value"><?php echo number_format($summary['total_pages']); ?></div>
                <div class="card-label">Total de Páginas</div>
            </div>
        </div>
        
        <div class="summary-card unique-visitors">
            <div class="card-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="card-content">
                <div class="card-value"><?php echo number_format($summary['total_unique_visitors']); ?></div>
                <div class="card-label">Visitantes Únicos</div>
            </div>
        </div>
        
        <div class="summary-card total-views">
            <div class="card-icon">
                <i class="fas fa-eye"></i>
            </div>
            <div class="card-content">
                <div class="card-value"><?php echo number_format($summary['total_views']); ?></div>
                <div class="card-label">Total de Views</div>
            </div>
        </div>
        
        <div class="summary-card engagement">
            <div class="card-icon">
                <i class="fas fa-chart-pie"></i>
            </div>
            <div class="card-content">
                <div class="card-value"><?php echo $summary['avg_engagement_score']; ?></div>
                <div class="card-label">Score Médio de Engajamento</div>
            </div>
        </div>
    </div>

    <!-- Gráficos -->
    <div class="charts-section">
        <div class="row g-4">
            <!-- Gráfico de Visitantes por Dia -->
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">Visitantes Únicos por Dia</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="dailyVisitorsChart" height="300"></canvas>
                    </div>
                </div>
            </div>
            
            <!-- Gráfico por Tipo de Página -->
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">Visitantes por Tipo</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="pageTypeChart" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabela Detalhada -->
    <div class="detailed-table-section">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-table me-2"></i>Análise Detalhada por Página
                </h5>
                <div class="table-controls">
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary active" data-view="detailed">Detalhada</button>
                        <button class="btn btn-outline-primary" data-view="summary">Resumida</button>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="pagesTable">
                        <thead class="table-light">
                            <tr>
                                <th class="sticky-column">Página</th>
                                <th class="text-center">Tipo</th>
                                <th class="text-center">Status</th>
                                <th class="text-center">Visitantes Únicos</th>
                                <th class="text-center">Total Views</th>
                                <th class="text-center">Views/Visitante</th>
                                <th class="text-center">Tempo Médio</th>
                                <th class="text-center">Taxa Conversão</th>
                                <th class="text-center">Taxa Rejeição</th>
                                <th class="text-center">Score Engajamento</th>
                                <th class="text-center">Crescimento</th>
                                <th class="text-center">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($allPages)): ?>
                            <?php foreach ($allPages as $page): ?>
                            <tr>
                                <td class="sticky-column">
                                    <div class="page-info">
                                        <div class="page-title"><?php echo htmlspecialchars($page['title']); ?></div>
                                        <small class="text-muted"><?php echo htmlspecialchars($page['slug']); ?></small>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark">
                                        <i class="fas <?php echo getPageTypeIcon($page['type']); ?> me-1"></i>
                                        <?php echo getPageTypeName($page['type']); ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <span class="badge <?php echo $page['published'] ? 'bg-success' : 'bg-warning'; ?>">
                                        <?php echo $page['published'] ? 'Publicada' : 'Rascunho'; ?>
                                    </span>
                                </td>
                                <td class="text-center metric-value">
                                    <strong><?php echo number_format($page['unique_visitors']); ?></strong>
                                    <?php if ($page['unique_today'] > 0): ?>
                                    <small class="text-primary d-block">+<?php echo $page['unique_today']; ?> hoje</small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center metric-value">
                                    <strong><?php echo number_format($page['total_views']); ?></strong>
                                    <?php if ($page['views_today'] > 0): ?>
                                    <small class="text-primary d-block">+<?php echo $page['views_today']; ?> hoje</small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <span class="metric-highlight"><?php echo $page['views_per_visitor']; ?></span>
                                </td>
                                <td class="text-center">
                                    <?php $minutes = round($page['avg_time_spent'] / 60, 1); ?>
                                    <span class="<?php echo $minutes >= 2 ? 'text-success' : ($minutes >= 1 ? 'text-warning' : 'text-danger'); ?>">
                                        <?php echo $minutes; ?>m
                                    </span>
                                </td>
                                <td class="text-center">
                                    <span class="<?php echo $page['conversion_rate'] >= 10 ? 'text-success' : ($page['conversion_rate'] >= 5 ? 'text-warning' : 'text-danger'); ?>">
                                        <?php echo $page['conversion_rate']; ?>%
                                    </span>
                                </td>
                                <td class="text-center">
                                    <span class="<?php echo $page['bounce_rate'] <= 50 ? 'text-success' : ($page['bounce_rate'] <= 70 ? 'text-warning' : 'text-danger'); ?>">
                                        <?php echo $page['bounce_rate']; ?>%
                                    </span>
                                </td>
                                <td class="text-center">
                                    <div class="engagement-score">
                                        <span class="score-value <?php echo $page['engagement_score'] >= 70 ? 'high' : ($page['engagement_score'] >= 40 ? 'medium' : 'low'); ?>">
                                            <?php echo $page['engagement_score']; ?>
                                        </span>
                                        <div class="score-bar">
                                            <div class="score-fill" style="width: <?php echo $page['engagement_score']; ?>%"></div>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <span class="growth-indicator <?php echo $page['growth_rate'] > 0 ? 'positive' : ($page['growth_rate'] < 0 ? 'negative' : 'neutral'); ?>">
                                        <?php if ($page['growth_rate'] > 0): ?>
                                        <i class="fas fa-arrow-up"></i> +<?php echo $page['growth_rate']; ?>%
                                        <?php elseif ($page['growth_rate'] < 0): ?>
                                        <i class="fas fa-arrow-down"></i> <?php echo $page['growth_rate']; ?>%
                                        <?php else: ?>
                                        <i class="fas fa-minus"></i> 0%
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm">
                                        <a href="page-edit.php?id=<?php echo $page['id']; ?>" class="btn btn-outline-primary btn-sm" title="Editar">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="reports.php?page_id=<?php echo $page['id']; ?>&date_start=<?php echo $dateStart; ?>&date_end=<?php echo $dateEnd; ?>" class="btn btn-outline-success btn-sm" title="Detalhes">
                                            <i class="fas fa-chart-line"></i>
                                        </a>
                                        <a href="#" class="btn btn-outline-info btn-sm" title="Preview" onclick="previewPage(<?php echo $page['id']; ?>)">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php else: ?>
                            <tr>
                                <td colspan="12" class="text-center py-5">
                                    <div class="empty-state">
                                        <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                                        <h5>Nenhum dado encontrado</h5>
                                        <p class="text-muted">Ajuste os filtros ou o período para ver os dados.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Performing Pages -->
    <?php if (!empty($allPages)): ?>
    <div class="top-pages-section">
        <div class="row g-4">
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-trophy me-2 text-warning"></i>Top 5 - Mais Visitadas
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php 
                        $topByVisitors = $allPages;
                        usort($topByVisitors, function($a, $b) { return $b['unique_visitors'] - $a['unique_visitors']; });
                        $topByVisitors = array_slice($topByVisitors, 0, 5);
                        ?>
                        <?php foreach ($topByVisitors as $index => $page): ?>
                        <div class="top-page-item">
                            <div class="rank-badge rank-<?php echo $index + 1; ?>"><?php echo $index + 1; ?></div>
                            <div class="page-details">
                                <h6><?php echo htmlspecialchars($page['title']); ?></h6>
                                <small class="text-muted"><?php echo getPageTypeName($page['type']); ?></small>
                            </div>
                            <div class="page-metrics">
                                <strong><?php echo number_format($page['unique_visitors']); ?></strong> visitantes
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-fire me-2 text-danger"></i>Top 5 - Maior Engajamento
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php 
                        $topByEngagement = $allPages;
                        usort($topByEngagement, function($a, $b) { return $b['engagement_score'] <=> $a['engagement_score']; });
                        $topByEngagement = array_slice($topByEngagement, 0, 5);
                        ?>
                        <?php foreach ($topByEngagement as $index => $page): ?>
                        <div class="top-page-item">
                            <div class="rank-badge rank-<?php echo $index + 1; ?>"><?php echo $index + 1; ?></div>
                            <div class="page-details">
                                <h6><?php echo htmlspecialchars($page['title']); ?></h6>
                                <small class="text-muted"><?php echo getPageTypeName($page['type']); ?></small>
                            </div>
                            <div class="page-metrics">
                                <strong><?php echo $page['engagement_score']; ?></strong> score
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Estilos CSS -->
<style>
    :root {
        --primary-color: #4F46E5;
        --secondary-color: #7C3AED;
        --success-color: #10B981;
        --warning-color: #F59E0B;
        --danger-color: #EF4444;
        --info-color: #3B82F6;
        --light-bg: #F8FAFC;
        --card-bg: #FFFFFF;
        --text-primary: #1F2937;
        --text-secondary: #6B7280;
        --text-muted: #9CA3AF;
        --border-color: #E5E7EB;
        --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    }

    body {
        background: var(--light-bg);
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    }

    .reports-container {
        padding: 20px;
        max-width: 1400px;
        margin: 0 auto;
    }

    /* Header */
    .reports-header {
        background: var(--card-bg);
        border-radius: 16px;
        padding: 32px;
        margin-bottom: 24px;
        box-shadow: var(--shadow);
        border: 1px solid var(--border-color);
    }

    .header-content {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 24px;
    }

    .header-title h1 {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 8px;
        color: var(--text-primary);
    }

    .subtitle {
        color: var(--text-secondary);
        font-size: 1rem;
        margin: 0;
    }

    .header-actions {
        display: flex;
        align-items: center;
        gap: 16px;
    }

    .period-display {
        background: var(--light-bg);
        padding: 12px 16px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        color: var(--text-primary);
        border: 1px solid var(--border-color);
    }

    .export-buttons {
        display: flex;
        gap: 8px;
    }

    /* Filtros */
    .filters-section {
        margin-bottom: 24px;
    }

    .filters-form .form-label {
        font-weight: 500;
        color: var(--text-primary);
        margin-bottom: 6px;
    }

    .form-control, .form-select {
        border-radius: 8px;
        border: 1px solid var(--border-color);
        padding: 8px 12px;
        transition: all 0.2s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    /* Cards de Resumo */
    .summary-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin-bottom: 32px;
    }

    .summary-card {
        background: var(--card-bg);
        border-radius: 16px;
        padding: 24px;
        box-shadow: var(--shadow);
        border: 1px solid var(--border-color);
        display: flex;
        align-items: center;
        gap: 20px;
        transition: all 0.3s ease;
    }

    .summary-card:hover {
        transform: translateY(-4px);
        box-shadow: var(--shadow-lg);
    }

    .summary-card .card-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
    }

    .total-pages .card-icon { background: linear-gradient(135deg, #667eea, #764ba2); }
    .unique-visitors .card-icon { background: linear-gradient(135deg, #4facfe, #00f2fe); }
    .total-views .card-icon { background: linear-gradient(135deg, #43e97b, #38f9d7); }
    .engagement .card-icon { background: linear-gradient(135deg, #fa709a, #fee140); }

    .card-value {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 4px;
        color: var(--text-primary);
    }

    .card-label {
        color: var(--text-secondary);
        font-weight: 500;
    }

    /* Charts */
    .charts-section {
        margin-bottom: 32px;
    }

    .card {
        border-radius: 16px;
        border: 1px solid var(--border-color);
        box-shadow: var(--shadow);
    }

    .card-header {
        border-bottom: 1px solid var(--border-color);
        padding: 20px 24px;
    }

    .card-title {
        font-weight: 600;
        color: var(--text-primary);
    }

    /* Tabela */
    .detailed-table-section {
        margin-bottom: 32px;
    }

    .table-responsive {
        max-height: 600px;
        overflow-y: auto;
    }

    .table {
        margin-bottom: 0;
    }

    .table th {
        background: var(--light-bg);
        border-bottom: 2px solid var(--border-color);
        font-weight: 600;
        color: var(--text-primary);
        white-space: nowrap;
        position: sticky;
        top: 0;
        z-index: 10;
    }

    .sticky-column {
        position: sticky;
        left: 0;
        background: var(--card-bg);
        z-index: 11;
        min-width: 200px;
    }

    .table th.sticky-column {
        background: var(--light-bg);
    }

    .page-info .page-title {
        font-weight: 600;
        margin-bottom: 2px;
        color: var(--text-primary);
    }

    .metric-value {
        font-weight: 600;
    }

    .metric-highlight {
        background: var(--light-bg);
        padding: 4px 8px;
        border-radius: 6px;
        font-weight: 600;
    }

    .engagement-score {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
    }

    .score-value {
        font-weight: 700;
        font-size: 1.1rem;
    }

    .score-value.high { color: var(--success-color); }
    .score-value.medium { color: var(--warning-color); }
    .score-value.low { color: var(--danger-color); }

    .score-bar {
        width: 40px;
        height: 4px;
        background: var(--border-color);
        border-radius: 2px;
        overflow: hidden;
    }

    .score-fill {
        height: 100%;
        background: var(--success-color);
        transition: width 0.3s ease;
    }

    .growth-indicator.positive { color: var(--success-color); }
    .growth-indicator.negative { color: var(--danger-color); }
    .growth-indicator.neutral { color: var(--text-muted); }

    /* Top Pages */
    .top-pages-section {
        margin-bottom: 32px;
    }

    .top-page-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px 0;
        border-bottom: 1px solid var(--border-color);
    }

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

    .rank-badge {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        color: white;
        font-size: 14px;
    }

    .rank-1 { background: #FFD700; }
    .rank-2 { background: #C0C0C0; }
    .rank-3 { background: #CD7F32; }
    .rank-4, .rank-5 { background: var(--text-muted); }

    .page-details {
        flex: 1;
    }

    .page-details h6 {
        margin-bottom: 2px;
        font-weight: 600;
    }

    .page-metrics {
        text-align: right;
        font-weight: 600;
        color: var(--text-primary);
    }

    /* Empty State */
    .empty-state {
        padding: 60px 40px;
        text-align: center;
    }

    .empty-state h5 {
        color: var(--text-primary);
        margin-bottom: 8px;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .reports-container {
            padding: 16px;
        }

        .header-content {
            flex-direction: column;
            gap: 16px;
        }

        .summary-cards {
            grid-template-columns: 1fr;
            gap: 16px;
        }

        .table-responsive {
            font-size: 0.875rem;
        }

        .sticky-column {
            min-width: 150px;
        }
    }
</style>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Gráfico de visitantes diários
    const dailyCtx = document.getElementById('dailyVisitorsChart').getContext('2d');
    new Chart(dailyCtx, {
        type: 'line',
        data: {
            labels: [<?php 
                if (!empty($dailyStats)) {
                    foreach ($dailyStats as $stat) {
                        echo "'" . $stat['formatted_date'] . "', ";
                    }
                }
            ?>],
            datasets: [{
                label: 'Visitantes Únicos',
                data: [<?php 
                    if (!empty($dailyStats)) {
                        foreach ($dailyStats as $stat) {
                            echo $stat['unique_visitors'] . ", ";
                        }
                    }
                ?>],
                borderColor: '#4F46E5',
                backgroundColor: 'rgba(79, 70, 229, 0.1)',
                borderWidth: 3,
                tension: 0.4,
                fill: true,
                pointBackgroundColor: '#4F46E5',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 6
            }, {
                label: 'Total de Views',
                data: [<?php 
                    if (!empty($dailyStats)) {
                        foreach ($dailyStats as $stat) {
                            echo $stat['total_views'] . ", ";
                        }
                    }
                ?>],
                borderColor: '#10B981',
                backgroundColor: 'rgba(16, 185, 129, 0.1)',
                borderWidth: 2,
                tension: 0.4,
                fill: false,
                pointBackgroundColor: '#10B981',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // Gráfico de tipos de página
    const typeCtx = document.getElementById('pageTypeChart').getContext('2d');
    new Chart(typeCtx, {
        type: 'doughnut',
        data: {
            labels: [<?php 
                if (!empty($typeStats)) {
                    foreach ($typeStats as $stat) {
                        echo "'" . getPageTypeName($stat['type']) . "', ";
                    }
                }
            ?>],
            datasets: [{
                data: [<?php 
                    if (!empty($typeStats)) {
                        foreach ($typeStats as $stat) {
                            echo $stat['unique_visitors'] . ", ";
                        }
                    }
                ?>],
                backgroundColor: [
                    '#4F46E5', '#10B981', '#F59E0B', '#EF4444', 
                    '#8B5CF6', '#06B6D4', '#84CC16', '#F97316'
                ],
                borderWidth: 0,
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        usePointStyle: true,
                        padding: 15
                    }
                }
            }
        }
    });

    // Controles da tabela
    document.querySelectorAll('[data-view]').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('[data-view]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            const view = this.getAttribute('data-view');
            const table = document.getElementById('pagesTable');
            
            if (view === 'summary') {
                // Esconder colunas menos importantes
                table.classList.add('summary-view');
            } else {
                table.classList.remove('summary-view');
            }
        });
    });
});

// Função para preview da página
function previewPage(pageId) {
    // Implementar modal ou nova janela para preview
    console.log('Preview da página:', pageId);
}

// Função para exportar dados personalizados
function exportCustomData() {
    // Implementar exportação personalizada
    console.log('Exportação personalizada');
}
</script>

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