<?php
// admin/pixel-reports.php

$pageTitle = 'Relatórios do Pixel IntegraOn';
$pageHeader = 'Relatórios do Pixel';
$currentPage = 'pixel-reports';

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

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/pixel-config.php';
require_once '../includes/pixel-helper.php';

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

// Obtém estatísticas
$pixelStats = getPixelStatsForAdmin();

// Filtros
$startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-7 days'));
$endDate = $_GET['end_date'] ?? date('Y-m-d');
$campaign = $_GET['campaign'] ?? '';

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

<div class="container-fluid px-4">
    <div class="page-header mb-4">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h1 class="page-title"><?php echo $pageTitle; ?></h1>
                <p class="text-muted">Acompanhe o desempenho do pixel IntegraOn e campanhas UTM.</p>
            </div>
            <div class="col-md-6 text-md-end">
                <div class="btn-group">
                    <button class="btn btn-outline-primary" onclick="exportPixelData()">
                        <i class="fas fa-download me-2"></i>Exportar Dados
                    </button>
                    <button class="btn btn-outline-secondary" onclick="refreshStats()">
                        <i class="fas fa-sync-alt me-2"></i>Atualizar
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Cards de Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="card-title mb-1"><?php echo number_format($pixelStats['summary']['total_events'] ?? 0); ?></h3>
                            <p class="text-muted mb-0">Total de Eventos</p>
                        </div>
                        <div class="text-primary">
                            <i class="fas fa-chart-line fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="card-title mb-1"><?php echo number_format($pixelStats['summary']['unique_visitors'] ?? 0); ?></h3>
                            <p class="text-muted mb-0">Visitantes Únicos</p>
                        </div>
                        <div class="text-success">
                            <i class="fas fa-users fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="card-title mb-1"><?php echo number_format($pixelStats['summary']['total_campaigns'] ?? 0); ?></h3>
                            <p class="text-muted mb-0">Campanhas Ativas</p>
                        </div>
                        <div class="text-warning">
                            <i class="fas fa-bullhorn fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <div class="d-flex align-items-center justify-content-between">
                        <div>
                            <h3 class="card-title mb-1">
                                <?php 
                                $lastEvent = $pixelStats['summary']['last_event'] ?? null;
                                echo $lastEvent ? formatTimeAgo($lastEvent) : 'Nunca';
                                ?>
                            </h3>
                            <p class="text-muted mb-0">Último Evento</p>
                        </div>
                        <div class="text-info">
                            <i class="fas fa-clock fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white">
            <h5 class="card-title mb-0">Filtros</h5>
        </div>
        <div class="card-body">
            <form method="get" action="" class="row g-3">
                <div class="col-md-3">
                    <label for="start_date" class="form-label">Data Inicial</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                </div>
                <div class="col-md-3">
                    <label for="end_date" class="form-label">Data Final</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                </div>
                <div class="col-md-4">
                    <label for="campaign" class="form-label">Campanha</label>
                    <select class="form-select" id="campaign" name="campaign">
                        <option value="">Todas as campanhas</option>
                        <?php foreach ($pixelStats['top_campaigns'] ?? [] as $camp): ?>
                        <option value="<?php echo htmlspecialchars($camp['utm_campaign']); ?>" 
                                <?php echo $campaign == $camp['utm_campaign'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($camp['utm_campaign']); ?> 
                            (<?php echo $camp['events']; ?> eventos)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                </div>
            </form>
        </div>
    </div>

    <div class="row">
        <!-- Gráfico de Eventos por Dia -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Eventos por Dia</h5>
                </div>
                <div class="card-body">
                    <canvas id="eventsChart" height="300"></canvas>
                </div>
            </div>
        </div>

        <!-- Top Campanhas -->
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white">
                    <h5 class="card-title mb-0">Top Campanhas</h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($pixelStats['top_campaigns'])): ?>
                    <div class="list-group list-group-flush">
                        <?php foreach (array_slice($pixelStats['top_campaigns'], 0, 5) as $camp): ?>
                        <div class="list-group-item border-0 px-0">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1"><?php echo htmlspecialchars($camp['utm_campaign']); ?></h6>
                                    <small class="text-muted"><?php echo $camp['unique_visitors']; ?> visitantes únicos</small>
                                </div>
                                <span class="badge bg-primary rounded-pill"><?php echo $camp['events']; ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <p class="text-muted text-center">Nenhuma campanha encontrada.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabela de Eventos Recentes -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">
            <h5 class="card-title mb-0">Eventos Recentes</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="eventsTable">
                    <thead>
                        <tr>
                            <th>Data/Hora</th>
                            <th>Campanha</th>
                            <th>Fonte</th>
                            <th>Meio</th>
                            <th>Página</th>
                            <th>IP</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Os dados serão carregados via AJAX -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Status do Pixel -->
<div class="position-fixed bottom-0 end-0 p-3">
    <div class="card border-0 shadow">
        <div class="card-body p-2">
            <div class="d-flex align-items-center">
                <div class="me-2">
                    <span class="badge bg-success">Pixel Ativo</span>
                </div>
                <small class="text-muted">IntegraOn conectado</small>
            </div>
        </div>
    </div>
</div>

<style>
.page-header {
    margin-bottom: 2rem;
}

.page-title {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    color: var(--dark-color);
}

.card {
    border-radius: 0.75rem;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.card-title {
    font-weight: 600;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: var(--dark-color);
}

.badge {
    font-weight: 500;
}

#eventsChart {
    max-height: 300px;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Dados do gráfico
    const chartData = {
        labels: [<?php 
            if (!empty($pixelStats['daily_stats'])) {
                foreach ($pixelStats['daily_stats'] as $stat) {
                    echo "'" . date('d/m', strtotime($stat['event_date'])) . "', ";
                }
            }
        ?>],
        datasets: [{
            label: 'Eventos',
            data: [<?php 
                if (!empty($pixelStats['daily_stats'])) {
                    foreach ($pixelStats['daily_stats'] as $stat) {
                        echo $stat['total_events'] . ", ";
                    }
                }
            ?>],
            backgroundColor: 'rgba(79, 70, 229, 0.1)',
            borderColor: 'rgba(79, 70, 229, 1)',
            borderWidth: 2,
            tension: 0.3,
            fill: true
        }, {
            label: 'Visitantes Únicos',
            data: [<?php 
                if (!empty($pixelStats['daily_stats'])) {
                    foreach ($pixelStats['daily_stats'] as $stat) {
                        echo $stat['unique_visitors'] . ", ";
                    }
                }
            ?>],
            backgroundColor: 'rgba(16, 185, 129, 0.1)',
            borderColor: 'rgba(16, 185, 129, 1)',
            borderWidth: 2,
            tension: 0.3,
            fill: true
        }]
    };

    // Configuração do gráfico
    const ctx = document.getElementById('eventsChart').getContext('2d');
    const chart = new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // Carrega eventos recentes
    loadRecentEvents();
});

function loadRecentEvents() {
    fetch('pixel-events-ajax.php?action=recent&start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>&campaign=<?php echo urlencode($campaign); ?>')
        .then(response => response.json())
        .then(data => {
            const tbody = document.querySelector('#eventsTable tbody');
            tbody.innerHTML = '';
            
            if (data.events && data.events.length > 0) {
                data.events.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${formatDateTime(event.created_at)}</td>
                        <td><span class="badge bg-primary">${event.utm_campaign || '-'}</span></td>
                        <td>${event.utm_source || '-'}</td>
                        <td>${event.utm_medium || '-'}</td>
                        <td>${event.page_title || 'Página externa'}</td>
                        <td><small class="text-muted">${event.visitor_ip}</small></td>
                        <td><span class="badge bg-success">Enviado</span></td>
                    `;
                    tbody.appendChild(row);
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">Nenhum evento encontrado</td></tr>';
            }
        })
        .catch(error => {
            console.error('Erro ao carregar eventos:', error);
        });
}

function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('pt-BR');
}

function refreshStats() {
    location.reload();
}

function exportPixelData() {
    const params = new URLSearchParams({
        action: 'export',
        start_date: '<?php echo $startDate; ?>',
        end_date: '<?php echo $endDate; ?>',
        campaign: '<?php echo $campaign; ?>'
    });
    
    window.open(`pixel-events-ajax.php?${params}`, '_blank');
}
</script>

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