<?php
// admin/ajax/get-page-visitor-details.php

require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Verifica autenticação
if (!$auth->isLoggedIn()) {
    http_response_code(403);
    echo '<div class="alert alert-danger">Acesso negado</div>';
    exit;
}

$pagesVisitorId = $_POST['pages_visitor_id'] ?? 0;

if (!$pagesVisitorId) {
    echo '<div class="alert alert-danger">ID da página não fornecido</div>';
    exit;
}

try {
    // Busca informações da página
    $db->query("SELECT * FROM pages_visitor WHERE id = :id");
    $db->bind(':id', $pagesVisitorId);
    $pageVisitor = $db->single();
    
    if (!$pageVisitor) {
        echo '<div class="alert alert-warning">Página não encontrada</div>';
        exit;
    }
    
    // Estatísticas de visitantes nos últimos 7 dias
    $db->query("
        SELECT 
            DATE(vs.created_at) as visit_date,
            COUNT(DISTINCT vs.visitor_hash) as unique_visitors,
            COUNT(vs.id) as total_visits,
            COUNT(DISTINCT vc.id) as conversions
        FROM visitor_sessions vs
        LEFT JOIN visitor_conversions vc ON vs.visitor_hash = vc.visitor_hash 
            AND vc.pages_visitor_id = vs.pages_visitor_id
        WHERE vs.pages_visitor_id = :pages_visitor_id 
        AND vs.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY DATE(vs.created_at)
        ORDER BY visit_date DESC
    ");
    $db->bind(':pages_visitor_id', $pagesVisitorId);
    $dailyStats = $db->resultSet();
    
    // Top Sources UTM para esta página
    $db->query("
        SELECT 
            utm_source,
            utm_medium,
            utm_campaign,
            COUNT(DISTINCT visitor_hash) as visitors,
            MAX(created_at) as last_visit
        FROM visitor_sessions 
        WHERE pages_visitor_id = :pages_visitor_id 
        AND utm_source IS NOT NULL 
        AND utm_source != ''
        AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY utm_source, utm_medium, utm_campaign
        ORDER BY visitors DESC
        LIMIT 10
    ");
    $db->bind(':pages_visitor_id', $pagesVisitorId);
    $utmSources = $db->resultSet();
    
    // Conversões desta página
    $db->query("
        SELECT 
            conversion_type,
            conversion_value,
            utm_source,
            created_at
        FROM visitor_conversions 
        WHERE pages_visitor_id = :pages_visitor_id
        ORDER BY created_at DESC
        LIMIT 20
    ");
    $db->bind(':pages_visitor_id', $pagesVisitorId);
    $conversions = $db->resultSet();
    
    // Totais gerais
    $db->query("
        SELECT 
            COUNT(DISTINCT visitor_hash) as total_unique_visitors,
            COUNT(id) as total_visits,
            AVG(time_spent) as avg_time_spent,
            AVG(max_scroll) as avg_scroll_depth
        FROM visitor_sessions 
        WHERE pages_visitor_id = :pages_visitor_id
    ");
    $db->bind(':pages_visitor_id', $pagesVisitorId);
    $totals = $db->single();
    
    ?>
    
    <div class="row">
        <div class="col-12">
            <h4><?php echo htmlspecialchars($pageVisitor['page_title']); ?></h4>
            <p class="text-muted"><?php echo htmlspecialchars($pageVisitor['page_url']); ?></p>
            
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h3><?php echo number_format($totals['total_unique_visitors'] ?? 0); ?></h3>
                            <small>Visitantes Únicos</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h3><?php echo number_format($totals['total_visits'] ?? 0); ?></h3>
                            <small>Total de Visitas</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h3><?php echo gmdate("i:s", $totals['avg_time_spent'] ?? 0); ?></h3>
                            <small>Tempo Médio</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h3><?php echo round($totals['avg_scroll_depth'] ?? 0); ?>%</h3>
                            <small>Scroll Médio</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- Estatísticas Diárias -->
        <div class="col-md-6">
            <h5>Últimos 7 Dias</h5>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Data</th>
                            <th>Visitantes</th>
                            <th>Visitas</th>
                            <th>Conversões</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($dailyStats)): ?>
                            <?php foreach ($dailyStats as $stat): ?>
                            <tr>
                                <td><?php echo date('d/m', strtotime($stat['visit_date'])); ?></td>
                                <td><?php echo number_format($stat['unique_visitors']); ?></td>
                                <td><?php echo number_format($stat['total_visits']); ?></td>
                                <td><?php echo number_format($stat['conversions']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted">Nenhum dado encontrado</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Sources UTM -->
        <div class="col-md-6">
            <h5>Top Sources UTM (30 dias)</h5>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Source</th>
                            <th>Medium</th>
                            <th>Visitantes</th>
                            <th>Última Visita</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($utmSources)): ?>
                            <?php foreach ($utmSources as $source): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($source['utm_source']); ?></td>
                                <td><?php echo htmlspecialchars($source['utm_medium'] ?: '-'); ?></td>
                                <td><?php echo number_format($source['visitors']); ?></td>
                                <td><?php echo date('d/m H:i', strtotime($source['last_visit'])); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted">Nenhum source UTM encontrado</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <?php if (!empty($conversions)): ?>
    <div class="row mt-4">
        <div class="col-12">
            <h5>Conversões Recentes</h5>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Tipo</th>
                            <th>Valor</th>
                            <th>Source</th>
                            <th>Data</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($conversions as $conversion): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($conversion['conversion_type']); ?></td>
                            <td><?php echo htmlspecialchars($conversion['conversion_value'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars($conversion['utm_source'] ?: '-'); ?></td>
                            <td><?php echo date('d/m H:i', strtotime($conversion['created_at'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <div class="row mt-4">
        <div class="col-12">
            <h5>Informações da Página</h5>
            <table class="table table-bordered">
                <tr>
                    <th style="width: 200px;">Tipo</th>
                    <td><?php echo htmlspecialchars($pageVisitor['page_type']); ?></td>
                </tr>
                <tr>
                    <th>Categoria</th>
                    <td><?php echo htmlspecialchars($pageVisitor['page_category'] ?: 'N/A'); ?></td>
                </tr>
                <tr>
                    <th>Auto-criada</th>
                    <td><?php echo $pageVisitor['auto_created'] ? 'Sim' : 'Não'; ?></td>
                </tr>
                <tr>
                    <th>Primeira Detecção</th>
                    <td><?php echo date('d/m/Y H:i', strtotime($pageVisitor['first_detected'])); ?></td>
                </tr>
                <tr>
                    <th>Última Atividade</th>
                    <td><?php echo date('d/m/Y H:i', strtotime($pageVisitor['last_activity'])); ?></td>
                </tr>
                <?php if ($pageVisitor['page_id']): ?>
                <tr>
                    <th>Página no CMS</th>
                    <td>
                        <a href="page-edit.php?id=<?php echo $pageVisitor['page_id']; ?>" class="btn btn-sm btn-primary" target="_blank">
                            Editar Página
                        </a>
                    </td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
    </div>
    
<?php
    
} catch (Exception $e) {
    echo '<div class="alert alert-danger">Erro ao carregar detalhes: ' . htmlspecialchars($e->getMessage()) . '</div>';
    error_log("Erro ao carregar detalhes da página visitante: " . $e->getMessage());
}
?>