<?php
// admin/reports.php - Versão atualizada com visitantes únicos

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

$pageTitle = 'Relatórios e Estatísticas';
$pageHeader = 'Relatórios e Estatísticas';
$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'; // Novo arquivo

// Requer autenticação
$auth->requireAuth();

// Processamento dos filtros
$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'; // 'unique' ou 'all'

// Arrays para armazenar dados
$viewsStats = [
    'total_unique' => 0,
    'total_views' => 0,
    'by_date' => [],
    'by_page' => [],
    'by_type' => []
];

// Obter estatísticas baseadas no tipo de relatório
try {
    if ($reportType === 'unique') {
        // === ESTATÍSTICAS DE VISITANTES ÚNICOS ===
        
        // Total de visitantes únicos no período
        $db->query("SELECT COUNT(DISTINCT visitor_hash) as total_unique
                    FROM unique_page_visitors 
                    WHERE visit_date BETWEEN :start AND :end" . 
                    ($pageType ? " AND page_id IN (SELECT id FROM pages WHERE type = :page_type)" : "") . 
                    ($pageId ? " AND page_id = :page_id" : ""));
        
        $db->bind(':start', $dateStart);
        $db->bind(':end', $dateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $result = $db->single();
        $viewsStats['total_unique'] = $result ? $result['total_unique'] : 0;
        
        // Visitantes únicos por data
        $db->query("SELECT 
                    visit_date as date,
                    COUNT(DISTINCT visitor_hash) as unique_count,
                    COUNT(*) as page_visits
                    FROM unique_page_visitors 
                    WHERE visit_date BETWEEN :start AND :end" . 
                    ($pageType ? " AND page_id IN (SELECT id FROM pages WHERE type = :page_type)" : "") . 
                    ($pageId ? " AND page_id = :page_id" : "") . "
                    GROUP BY visit_date
                    ORDER BY visit_date");
        
        $db->bind(':start', $dateStart);
        $db->bind(':end', $dateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $viewsStats['by_date'] = $db->resultSet();
        
        // Visitantes únicos por página
        $db->query("SELECT 
                    p.id, p.title, p.type,
                    COUNT(DISTINCT upv.visitor_hash) as unique_visitors,
                    COUNT(upv.visitor_hash) as total_visits
                    FROM pages p
                    LEFT JOIN unique_page_visitors upv ON p.id = upv.page_id AND upv.visit_date BETWEEN :start AND :end" . 
                    ($pageType ? " WHERE p.type = :page_type" : "") . 
                    ($pageId ? " AND p.id = :page_id" : "") . "
                    GROUP BY p.id
                    ORDER BY unique_visitors DESC
                    LIMIT 10");
        
        $db->bind(':start', $dateStart);
        $db->bind(':end', $dateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $viewsStats['by_page'] = $db->resultSet();
        
        // Visitantes únicos por tipo de página
        $db->query("SELECT 
                    p.type,
                    COUNT(DISTINCT upv.visitor_hash) as unique_visitors,
                    COUNT(upv.visitor_hash) as total_visits
                    FROM pages p
                    LEFT JOIN unique_page_visitors upv ON p.id = upv.page_id AND upv.visit_date BETWEEN :start AND :end
                    GROUP BY p.type
                    ORDER BY unique_visitors DESC");
        
        $db->bind(':start', $dateStart);
        $db->bind(':end', $dateEnd);
        $viewsStats['by_type'] = $db->resultSet();
        
    } else {
        // === ESTATÍSTICAS DE TODAS AS VISUALIZAÇÕES (MODO LEGADO) ===
        
        $dbDateStart = date('Y-m-d 00:00:00', strtotime($dateStart));
        $dbDateEnd = date('Y-m-d 23:59:59', strtotime($dateEnd));
        
        // Total de visualizações no período
        $db->query("SELECT COUNT(*) as total FROM page_views 
                    WHERE viewed_at BETWEEN :start AND :end" . 
                    ($pageType ? " AND page_id IN (SELECT id FROM pages WHERE type = :page_type)" : "") . 
                    ($pageId ? " AND page_id = :page_id" : ""));
        
        $db->bind(':start', $dbDateStart);
        $db->bind(':end', $dbDateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $result = $db->single();
        $viewsStats['total_views'] = $result ? $result['total'] : 0;
        
        // Visualizações por data
        $db->query("SELECT 
                    DATE_FORMAT(viewed_at, '%Y-%m-%d') as date,
                    COUNT(*) as count
                    FROM page_views 
                    WHERE viewed_at BETWEEN :start AND :end" . 
                    ($pageType ? " AND page_id IN (SELECT id FROM pages WHERE type = :page_type)" : "") . 
                    ($pageId ? " AND page_id = :page_id" : "") . "
                    GROUP BY DATE_FORMAT(viewed_at, '%Y-%m-%d')
                    ORDER BY date");
        
        $db->bind(':start', $dbDateStart);
        $db->bind(':end', $dbDateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $viewsStats['by_date'] = $db->resultSet();
        
        // Visualizações por página
        $db->query("SELECT 
                    p.id, p.title, p.type,
                    COUNT(pv.id) as views
                    FROM pages p
                    LEFT JOIN page_views pv ON p.id = pv.page_id AND pv.viewed_at BETWEEN :start AND :end" . 
                    ($pageType ? " WHERE p.type = :page_type" : "") . 
                    ($pageId ? " AND p.id = :page_id" : "") . "
                    GROUP BY p.id
                    ORDER BY views DESC
                    LIMIT 10");
        
        $db->bind(':start', $dbDateStart);
        $db->bind(':end', $dbDateEnd);
        if ($pageType) {
            $db->bind(':page_type', $pageType);
        }
        if ($pageId) {
            $db->bind(':page_id', $pageId);
        }
        
        $viewsStats['by_page'] = $db->resultSet();
        
        // Visualizações por tipo de página
        $db->query("SELECT 
                    p.type,
                    COUNT(pv.id) as views
                    FROM pages p
                    LEFT JOIN page_views pv ON p.id = pv.page_id AND pv.viewed_at BETWEEN :start AND :end
                    GROUP BY p.type
                    ORDER BY views DESC");
        
        $db->bind(':start', $dbDateStart);
        $db->bind(':end', $dbDateEnd);
        $viewsStats['by_type'] = $db->resultSet();
    }
    
    // Obter lista de páginas para filtro
    $db->query("SELECT id, title, type FROM pages ORDER BY type, title");
    $pages = $db->resultSet();
    
    // === ESTATÍSTICAS DE CONVERSÃO USANDO VISITANTES ÚNICOS ===
    $conversion_stats = [
        'landing' => 0,
        'step1' => 0,
        'step2' => 0,
        'step3' => 0,
        'registration' => 0
    ];

    $conversion_rates = [
        'landing_to_step1' => 0,
        'step1_to_registration' => 0,
        'overall' => 0
    ];
    
    $landingPageTitle = '';
    $targetLandingId = 0;
    
    if ($pageId) {
        // Se uma página específica foi selecionada
        $db->query("SELECT id, title, type, landing_page_id FROM pages WHERE id = :page_id");
        $db->bind(':page_id', $pageId);
        $pageInfo = $db->single();
        
        if ($pageInfo) {
            $landingPageTitle = $pageInfo['title'];
            
            if ($pageInfo['type'] === 'landing') {
                $targetLandingId = $pageInfo['id'];
            } else {
                $targetLandingId = $pageInfo['landing_page_id'];
                
                if ($targetLandingId > 0) {
                    $db->query("SELECT title FROM pages WHERE id = :landing_id");
                    $db->bind(':landing_id', $targetLandingId);
                    $landingInfo = $db->single();
                    if ($landingInfo) {
                        $landingPageTitle = $landingInfo['title'] . ' (' . $pageInfo['title'] . ')';
                    }
                }
            }
            
            if ($targetLandingId > 0) {
                // Usar o sistema de visitantes únicos para conversão
                $conversion_stats = $visitorTracking->getUniqueConversionStats($targetLandingId, $dateStart, $dateEnd);
                
                // Calcular taxas de conversão
                if ($conversion_stats['landing'] > 0) {
                    $conversion_rates['landing_to_step1'] = $conversion_stats['step1'] > 0 
                        ? round(($conversion_stats['step1'] / $conversion_stats['landing']) * 100) 
                        : 0;
                    
                    $conversion_rates['step1_to_registration'] = $conversion_stats['step1'] > 0 
                        ? round(($conversion_stats['registration'] / $conversion_stats['step1']) * 100) 
                        : 0;
                    
                    $conversion_rates['overall'] = round(($conversion_stats['registration'] / $conversion_stats['landing']) * 100);
                }
            }
        }
    } elseif ($pageType) {
        $landingPageTitle = 'Tipo: ' . ucfirst($pageType);
        
        // Lógica similar mas agrupada por tipo
        if ($pageType === 'landing') {
            $db->query("SELECT COUNT(DISTINCT upv.visitor_hash) as unique_visitors
                       FROM unique_page_visitors upv
                       JOIN pages p ON upv.page_id = p.id
                       WHERE p.type = 'landing'
                       AND upv.visit_date BETWEEN :start AND :end");
            $db->bind(':start', $dateStart);
            $db->bind(':end', $dateEnd);
            $landingViews = $db->single();
            $conversion_stats['landing'] = $landingViews ? $landingViews['unique_visitors'] : 0;
            
            foreach (['step1', 'step2', 'step3', 'registration'] as $step) {
                $db->query("SELECT COUNT(DISTINCT upv.visitor_hash) as unique_visitors
                           FROM unique_page_visitors upv
                           JOIN pages p ON upv.page_id = p.id
                           WHERE p.type = :step_type AND p.landing_page_id > 0
                           AND upv.visit_date BETWEEN :start AND :end");
                $db->bind(':step_type', $step);
                $db->bind(':start', $dateStart);
                $db->bind(':end', $dateEnd);
                $stepViews = $db->single();
                $conversion_stats[$step] = $stepViews ? $stepViews['unique_visitors'] : 0;
            }
        }
        
        // Calcular taxas de conversão
        if ($conversion_stats['landing'] > 0) {
            $conversion_rates['landing_to_step1'] = $conversion_stats['step1'] > 0 
                ? round(($conversion_stats['step1'] / $conversion_stats['landing']) * 100) 
                : 0;
                
            $conversion_rates['step1_to_registration'] = $conversion_stats['step1'] > 0 
                ? round(($conversion_stats['registration'] / $conversion_stats['step1']) * 100) 
                : 0;
                
            $conversion_rates['overall'] = round(($conversion_stats['registration'] / $conversion_stats['landing']) * 100);
        }
    } else {
        $landingPageTitle = 'Todas as Páginas';
        
        // Estatísticas gerais usando visitantes únicos
        $generalStats = $visitorTracking->getGeneralUniqueStats($dateStart, $dateEnd);
        
        foreach (['landing', 'step1', 'step2', 'step3', 'registration'] as $type) {
            $conversion_stats[$type] = 0;
            foreach ($generalStats['by_type'] as $typeData) {
                if ($typeData['type'] === $type) {
                    $conversion_stats[$type] = $typeData['unique_visitors'];
                    break;
                }
            }
        }
        
        if ($conversion_stats['landing'] > 0) {
            $conversion_rates['landing_to_step1'] = $conversion_stats['step1'] > 0 
                ? round(($conversion_stats['step1'] / $conversion_stats['landing']) * 100) 
                : 0;
                
            $conversion_rates['step1_to_registration'] = $conversion_stats['step1'] > 0 
                ? round(($conversion_stats['registration'] / $conversion_stats['step1']) * 100) 
                : 0;
                
            $conversion_rates['overall'] = round(($conversion_stats['registration'] / $conversion_stats['landing']) * 100);
        }
    }
    
} catch (Exception $e) {
    setAlert("Erro ao obter estatísticas: " . $e->getMessage(), ALERT_ERROR);
    logError("Erro em reports.php: " . $e->getMessage());
}

// Converter para JSON para uso nos gráficos
if ($reportType === 'unique') {
    $viewsByDateJSON = json_encode(array_map(function($item) {
        return [
            'date' => $item['date'],
            'views' => $item['unique_count'],
            'total_visits' => $item['page_visits'] ?? $item['unique_count']
        ];
    }, $viewsStats['by_date']));
    
    $viewsByTypeJSON = json_encode(array_map(function($item) {
        return [
            'type' => $item['type'],
            'views' => $item['unique_visitors']
        ];
    }, $viewsStats['by_type']));
} else {
    $viewsByDateJSON = json_encode(array_map(function($item) {
        return [
            'date' => $item['date'],
            'views' => $item['count']
        ];
    }, $viewsStats['by_date']));
    
    $viewsByTypeJSON = json_encode(array_map(function($item) {
        return [
            'type' => $item['type'],
            'views' => $item['views']
        ];
    }, $viewsStats['by_type']));
}

// Incluir o header
require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <!-- Filtros -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <h5 class="card-title">Filtros e Configurações</h5>
            <form method="get" action="" id="filterForm" class="row g-3">
                <div class="col-md-2">
                    <label for="report_type" class="form-label">Tipo de Relatório</label>
                    <select class="form-select" id="report_type" name="report_type">
                        <option value="unique" <?php echo $reportType == 'unique' ? 'selected' : ''; ?>>Visitantes Únicos</option>
                        <option value="all" <?php echo $reportType == 'all' ? 'selected' : ''; ?>>Todas as Visualizações</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="date_start" class="form-label">Data inicial</label>
                    <input type="date" class="form-control" id="date_start" name="date_start" value="<?php echo $dateStart; ?>">
                </div>
                <div class="col-md-2">
                    <label for="date_end" class="form-label">Data final</label>
                    <input type="date" class="form-control" id="date_end" name="date_end" value="<?php echo $dateEnd; ?>">
                </div>
                <div class="col-md-2">
                    <label for="page_type" class="form-label">Tipo de página</label>
                    <select class="form-select" id="page_type" name="page_type">
                        <option value="">Todos</option>
                        <option value="landing" <?php echo $pageType == 'landing' ? 'selected' : ''; ?>>Landing</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-3">
                    <label for="page_id" class="form-label">Página específica</label>
                    <select class="form-select" id="page_id" name="page_id">
                        <option value="">Todas</option>
                        <?php foreach ($pages as $page): ?>
                        <option value="<?php echo $page['id']; ?>" <?php echo $pageId == $page['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($page['title']) . ' (' . ucfirst($page['type']) . ')'; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-1 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i>
                    </button>
                </div>
            </form>
            
            <div class="row mt-3">
                <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="report-info">
                            <span class="badge bg-<?php echo $reportType === 'unique' ? 'success' : 'info'; ?> me-2">
                                <?php echo $reportType === 'unique' ? 'Visitantes Únicos (24h)' : 'Todas as Visualizações'; ?>
                            </span>
                            <?php if ($reportType === 'unique'): ?>
                            <small class="text-muted">Cada visitante é contado apenas uma vez por página a cada 24 horas</small>
                            <?php else: ?>
                            <small class="text-muted">Todas as visualizações são contadas, incluindo recarregamentos</small>
                            <?php endif; ?>
                        </div>
                        <button type="button" id="exportBtn" class="btn btn-outline-success">
                            <i class="fas fa-file-export me-2"></i>Exportar CSV
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Resumo de Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="display-4 mb-2">
                        <?php 
                        if ($reportType === 'unique') {
                            echo number_format($viewsStats['total_unique']); 
                        } else {
                            echo number_format($viewsStats['total_views']); 
                        }
                        ?>
                    </div>
                    <div class="text-muted">
                        <?php echo $reportType === 'unique' ? 'Visitantes Únicos' : 'Total de Visualizações'; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="display-4 mb-2"><?php 
                        $dayCount = count($viewsStats['by_date']);
                        if ($reportType === 'unique') {
                            echo $dayCount > 0 ? number_format($viewsStats['total_unique'] / $dayCount, 1) : '0'; 
                        } else {
                            echo $dayCount > 0 ? number_format($viewsStats['total_views'] / $dayCount, 1) : '0'; 
                        }
                    ?></div>
                    <div class="text-muted">Média Diária</div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="display-4 mb-2"><?php 
                        if (!empty($viewsStats['by_page'])) {
                            if ($reportType === 'unique') {
                                echo number_format($viewsStats['by_page'][0]['unique_visitors'] ?? 0);
                            } else {
                                echo number_format($viewsStats['by_page'][0]['views'] ?? 0);
                            }
                        } else {
                            echo '0';
                        }
                    ?></div>
                    <div class="text-muted">Página Mais Visitada</div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body text-center">
                    <div class="display-4 mb-2"><?php 
                        if (!empty($viewsStats['by_type'])) {
                            echo ucfirst($viewsStats['by_type'][0]['type']); 
                        } else {
                            echo '-';
                        }
                    ?></div>
                    <div class="text-muted">Tipo Mais Visitado</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Gráficos -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">
                        <?php echo $reportType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?> por Data
                    </h5>
                </div>
                <div class="card-body">
                    <canvas id="viewsByDateChart" height="300"></canvas>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">
                        <?php echo $reportType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?> por Tipo
                    </h5>
                </div>
                <div class="card-body">
                    <canvas id="viewsByTypeChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabela de dados detalhados -->
    <div class="row mb-4">
        <div class="col-12">
            <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">
                        <?php echo $reportType === 'unique' ? 'Visitantes Únicos' : 'Visualizações'; ?> por Página
                    </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>
                                    <?php if ($reportType === 'unique'): ?>
                                    <th class="text-center">Visitantes Únicos</th>
                                    <th class="text-center">Total de Visitas</th>
                                    <th class="text-center">Visitas/Visitante</th>
                                    <?php else: ?>
                                    <th class="text-center">Visualizações</th>
                                    <th class="text-center">% do Total</th>
                                    <?php endif; ?>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($viewsStats['by_page'])): ?>
                                    <?php foreach ($viewsStats['by_page'] as $index => $page): ?>
                                    <tr>
                                        <td><?php echo $index + 1; ?></td>
                                        <td><?php echo htmlspecialchars($page['title']); ?></td>
                                        <td><span class="badge bg-<?php echo getTypeColor($page['type']); ?>"><?php echo ucfirst($page['type']); ?></span></td>
                                        <?php if ($reportType === 'unique'): ?>
                                        <td class="text-center"><?php echo number_format($page['unique_visitors'] ?? 0); ?></td>
                                        <td class="text-center"><?php echo number_format($page['total_visits'] ?? 0); ?></td>
                                        <td class="text-center">
                                            <?php 
                                            $ratio = ($page['unique_visitors'] ?? 0) > 0 ? ($page['total_visits'] ?? 0) / ($page['unique_visitors'] ?? 1) : 0;
                                            echo number_format($ratio, 1);
                                            ?>
                                        </td>
                                        <?php else: ?>
                                        <td class="text-center"><?php echo number_format($page['views'] ?? 0); ?></td>
                                        <td class="text-center">
                                            <?php 
                                            $total = $viewsStats['total_views'];
                                            echo $total > 0 ? number_format((($page['views'] ?? 0) / $total) * 100, 1) . '%' : '0%'; 
                                            ?>
                                        </td>
                                        <?php endif; ?>
                                        <td>
                                            <a href="page-edit.php?id=<?php echo $page['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="?page_id=<?php echo $page['id']; ?>&date_start=<?php echo $dateStart; ?>&date_end=<?php echo $dateEnd; ?>&report_type=<?php echo $reportType; ?>" class="btn btn-sm btn-outline-info">
                                                <i class="fas fa-filter"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                <tr>
                                    <td colspan="<?php echo $reportType === 'unique' ? '7' : '6'; ?>" class="text-center py-4">
                                        <p class="text-muted mb-0">Nenhum dado encontrado para o período selecionado.</p>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Análise de Conversão (sempre baseada em visitantes únicos) -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">
                        Análise de Conversão (Visitantes Únicos)
                        <?php echo !empty($landingPageTitle) ? ' - ' . htmlspecialchars($landingPageTitle) : ''; ?>
                    </h5>
                    <small class="text-muted">Baseado em visitantes únicos independente do tipo de relatório acima</small>
                </div>
                <div class="card-body">
                    <div class="conversion-funnel mb-4">
                        <div class="funnel-step" style="width: 100%">
                            <div class="funnel-label">Landing</div>
                            <div class="funnel-bar landing"></div>
                            <div class="funnel-value"><?php echo number_format($conversion_stats['landing']); ?> (100%)</div>
                        </div>
                        <div class="funnel-step" style="width: <?php echo max(10, $conversion_rates['landing_to_step1']); ?>%">
                            <div class="funnel-label">Etapa 1</div>
                            <div class="funnel-bar step1"></div>
                            <div class="funnel-value"><?php echo number_format($conversion_stats['step1']); ?> (<?php echo $conversion_rates['landing_to_step1']; ?>%)</div>
                        </div>
                        <div class="funnel-step" style="width: <?php echo max(5, $conversion_rates['overall']); ?>%">
                            <div class="funnel-label">Registro</div>
                            <div class="funnel-bar registration"></div>
                            <div class="funnel-value"><?php echo number_format($conversion_stats['registration']); ?> (<?php echo $conversion_rates['overall']; ?>%)</div>
                        </div>
                    </div>
                    
                    <h6 class="mt-4">Taxas de Conversão</h6>
                    <div class="row mt-3">
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Landing → Etapa 1</h6>
                                    <div class="display-6 text-primary"><?php echo $conversion_rates['landing_to_step1']; ?>%</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Etapa 1 → Registro</h6>
                                    <div class="display-6 text-primary"><?php echo $conversion_rates['step1_to_registration']; ?>%</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6 class="card-title">Taxa de Registro</h6>
                                    <div class="display-6 text-success"><?php echo $conversion_rates['overall']; ?>%</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Estilos para o funil de conversão */
    .conversion-funnel {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: center;
    }
    
    .funnel-step {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-left: auto;
        margin-right: auto;
        transition: all 0.3s ease;
        min-width: 220px;
    }
    
    .funnel-label {
        width: 100px;
        text-align: right;
        font-weight: 500;
    }
    
    .funnel-bar {
        height: 40px;
        border-radius: 8px;
        flex-grow: 1;
    }
    
    .funnel-value {
        width: 120px;
        text-align: left;
        font-weight: 500;
    }
    
    .funnel-bar.landing {
        background: linear-gradient(135deg, #4F46E5, #7C3AED);
    }
    
    .funnel-bar.step1 {
        background: linear-gradient(135deg, #3B82F6, #1D4ED8);
    }
    
    .funnel-bar.registration {
        background: linear-gradient(135deg, #10B981, #059669);
    }
    
    /* Cores para badges de tipo */
    .bg-landing {
        background-color: #4F46E5 !important;
    }
    
    .bg-step1 {
        background-color: #3B82F6 !important;
    }
    
    .bg-step2 {
        background-color: #8B5CF6 !important;
    }
    
    .bg-step3 {
        background-color: #EC4899 !important;
    }
    
    .bg-registration {
        background-color: #10B981 !important;
    }
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Preparar dados para os gráficos
    const viewsByDate = <?php echo $viewsByDateJSON; ?>;
    const viewsByType = <?php echo $viewsByTypeJSON; ?>;
    
    // Função para formatar datas
    function formatDate(dateStr) {
        const date = new Date(dateStr);
        return date.toLocaleDateString('pt-BR', {
            day: '2-digit',
            month: '2-digit'
        });
    }
    
    // Gráfico de visualizações por data
    const dateLabels = viewsByDate.map(item => formatDate(item.date));
    const dateValues = viewsByDate.map(item => item.views);
    
    const dateCtx = document.getElementById('viewsByDateChart').getContext('2d');
    new Chart(dateCtx, {
        type: 'line',
        data: {
            labels: dateLabels,
            datasets: [{
                label: '<?php echo $reportType === "unique" ? "Visitantes Únicos" : "Visualizações"; ?>',
                data: dateValues,
                backgroundColor: 'rgba(79, 70, 229, 0.2)',
                borderColor: 'rgba(79, 70, 229, 1)',
                borderWidth: 2,
                tension: 0.3,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        display: true,
                        drawBorder: false,
                        color: 'rgba(200, 200, 200, 0.15)'
                    }
                },
                x: {
                    grid: {
                        display: false,
                        drawBorder: false
                    }
                }
            }
        }
    });
    
    // Gráfico de visualizações por tipo
    const typeLabels = viewsByType.map(item => {
        const types = {
            'landing': 'Landing',
            'step1': 'Etapa 1',
            'step2': 'Etapa 2',
            'step3': 'Etapa 3',
            'registration': 'Registro'
        };
        return types[item.type] || item.type;
    });
    
    const typeValues = viewsByType.map(item => item.views);
    const typeColors = [
        'rgba(79, 70, 229, 0.8)',
        'rgba(59, 130, 246, 0.8)',
        'rgba(139, 92, 246, 0.8)',
        'rgba(236, 72, 153, 0.8)',
        'rgba(16, 185, 129, 0.8)'
    ];
    
    const typeCtx = document.getElementById('viewsByTypeChart').getContext('2d');
    new Chart(typeCtx, {
        type: 'doughnut',
        data: {
            labels: typeLabels,
            datasets: [{
                data: typeValues,
                backgroundColor: typeColors,
                borderWidth: 0,
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                }
            },
            cutout: '70%'
        }
    });
    
    // Exportação para CSV
    document.getElementById('exportBtn').addEventListener('click', function() {
        const table = document.querySelector('table');
        let csv = [];
        const rows = table.querySelectorAll('tr');
        
        for (const row of rows) {
            const rowData = [];
            const cols = row.querySelectorAll('td, th');
            
            for (const col of cols) {
                let text = col.textContent.trim();
                text = text.replace(/\s\s+/g, ' ');
                if (text.includes(',')) {
                    text = `"${text}"`;
                }
                rowData.push(text);
            }
            
            csv.push(rowData.join(','));
        }
        
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        
        link.setAttribute('href', url);
        link.setAttribute('download', `relatorio_<?php echo $reportType; ?>_${new Date().toISOString().slice(0,10)}.csv`);
        link.style.visibility = 'hidden';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
});
</script>

<?php
// Função para auxiliar na obtenção de cores para os tipos de página
function getTypeColor($type) {
    $colors = [
        'landing' => 'landing',
        'step1' => 'step1',
        'step2' => 'step2',
        'step3' => 'step3',
        'registration' => 'registration'
    ];
    
    return $colors[$type] ?? 'primary';
}

// Incluir o footer
require_once 'inc/footer.php';
?>