<?php
// pages/page-view.php - Exemplo de implementação para visualização de páginas

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

require_once BASE_PATH . '/includes/config.php';
require_once BASE_PATH . '/includes/db.php';
require_once BASE_PATH . '/includes/functions.php';
require_once BASE_PATH . '/includes/visitor-tracking.php';

// Obter ID da página pela URL (slug ou ID)
$pageSlug = isset($_GET['slug']) ? sanitizeInput($_GET['slug']) : '';
$pageId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (empty($pageSlug) && empty($pageId)) {
    header("HTTP/1.0 404 Not Found");
    include '404.php';
    exit;
}

try {
    // Buscar página no banco
    if ($pageId > 0) {
        $db->query("SELECT * FROM pages WHERE id = :id AND published = 1");
        $db->bind(':id', $pageId);
    } else {
        $db->query("SELECT * FROM pages WHERE slug = :slug AND published = 1");
        $db->bind(':slug', $pageSlug);
    }
    
    $page = $db->single();
    
    if (!$page) {
        header("HTTP/1.0 404 Not Found");
        include '404.php';
        exit;
    }
    
    // REGISTRAR VISITA ÚNICA
    $isNewUniqueVisit = $visitorTracking->trackUniquePageView($page['id']);
    
    // Log para debug (remover em produção)
    if ($isNewUniqueVisit) {
        logInfo("Nova visita única registrada para página: " . $page['title'] . " (ID: " . $page['id'] . ")");
    } else {
        logInfo("Visita repetida detectada para página: " . $page['title'] . " (ID: " . $page['id'] . ") - não contabilizada");
    }
    
    // Definir meta tags
    $pageTitle = htmlspecialchars($page['title']);
    $metaDescription = htmlspecialchars($page['meta_description'] ?: $page['excerpt']);
    $canonicalUrl = SITE_URL . '/pages/' . $page['slug'];
    
    // Obter próxima página no fluxo
    $nextPageUrl = '';
    if (!empty($page['cta_link'])) {
        $nextPageUrl = $page['cta_link'];
    } else {
        // Gerar URL baseada no fluxo
        $nextSteps = [
            'landing' => 'step1',
            'step1' => 'step2', 
            'step2' => 'step3',
            'step3' => 'registration'
        ];
        
        if (isset($nextSteps[$page['type']])) {
            $nextStep = $nextSteps[$page['type']];
            
            if ($page['type'] === 'landing') {
                $nextPageUrl = SITE_URL . '/pages/' . $nextStep . '?landing=' . $page['id'];
            } elseif ($page['landing_page_id'] > 0) {
                $nextPageUrl = SITE_URL . '/pages/' . $nextStep . '?landing=' . $page['landing_page_id'];
            }
        }
    }
    
} catch (Exception $e) {
    logError("Erro ao carregar página: " . $e->getMessage());
    header("HTTP/1.0 500 Internal Server Error");
    include '500.php';
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - <?php echo SITE_NAME; ?></title>
    
    <!-- Meta tags SEO -->
    <meta name="description" content="<?php echo $metaDescription; ?>">
    <link rel="canonical" href="<?php echo $canonicalUrl; ?>">
    
    <!-- Open Graph -->
    <meta property="og:title" content="<?php echo $pageTitle; ?>">
    <meta property="og:description" content="<?php echo $metaDescription; ?>">
    <meta property="og:url" content="<?php echo $canonicalUrl; ?>">
    <meta property="og:type" content="article">
    <?php if (!empty($page['featured_image'])): ?>
    <meta property="og:image" content="<?php echo SITE_URL . $page['featured_image']; ?>">
    <?php endif; ?>
    
    <!-- Favicon -->
    <link rel="shortcut icon" href="<?php echo SITE_URL; ?>/favicon.ico" type="image/x-icon">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Estilos personalizados -->
    <link href="<?php echo SITE_URL; ?>/assets/css/style.css" rel="stylesheet">
    
    <!-- Schema.org estruturado -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Article",
        "headline": "<?php echo addslashes($pageTitle); ?>",
        "description": "<?php echo addslashes($metaDescription); ?>",
        "url": "<?php echo $canonicalUrl; ?>",
        "publisher": {
            "@type": "Organization",
            "name": "<?php echo SITE_NAME; ?>",
            "url": "<?php echo SITE_URL; ?>"
        },
        "datePublished": "<?php echo date('c', strtotime($page['created_at'])); ?>",
        "dateModified": "<?php echo date('c', strtotime($page['updated_at'] ?: $page['created_at'])); ?>"
    }
    </script>
</head>
<body>
    <!-- Header/Navegação -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div class="container">
            <a class="navbar-brand" href="<?php echo SITE_URL; ?>">
                <img src="<?php echo SITE_URL; ?>/assets/img/logo.png" alt="<?php echo SITE_NAME; ?>" height="40">
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="<?php echo SITE_URL; ?>">Início</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?php echo SITE_URL; ?>/cursos">Cursos</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?php echo SITE_URL; ?>/contato">Contato</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Conteúdo principal -->
    <main class="main-content">
        <div class="container my-5">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <!-- Imagem destacada -->
                    <?php if (!empty($page['featured_image'])): ?>
                    <div class="featured-image mb-4">
                        <img src="<?php echo SITE_URL . $page['featured_image']; ?>" 
                             alt="<?php echo $pageTitle; ?>" 
                             class="img-fluid rounded shadow">
                    </div>
                    <?php endif; ?>
                    
                    <!-- Título da página -->
                    <h1 class="page-title mb-4"><?php echo $pageTitle; ?></h1>
                    
                    <!-- Conteúdo -->
                    <div class="page-content">
                        <?php echo $page['content']; ?>
                    </div>
                    
                    <!-- Call to Action -->
                    <?php if (!empty($nextPageUrl) && !empty($page['cta_text'])): ?>
                    <div class="cta-section mt-5 mb-4">
                        <div class="text-center">
                            <a href="<?php echo $nextPageUrl; ?>" 
                               class="btn btn-primary btn-lg cta-button" 
                               data-page-id="<?php echo $page['id']; ?>"
                               data-action="cta-click">
                                <?php echo htmlspecialchars($page['cta_text']); ?>
                                <i class="fas fa-arrow-right ms-2"></i>
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Navegação do fluxo -->
                    <div class="flow-navigation mt-4">
                        <div class="row">
                            <?php if ($page['type'] !== 'landing'): ?>
                            <div class="col-md-6">
                                <a href="javascript:history.back()" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i>Voltar
                                </a>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($nextPageUrl)): ?>
                            <div class="col-md-6 text-md-end">
                                <a href="<?php echo $nextPageUrl; ?>" 
                                   class="btn btn-outline-primary"
                                   data-page-id="<?php echo $page['id']; ?>"
                                   data-action="next-step">
                                    Próximo Passo <i class="fas fa-arrow-right ms-2"></i>
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Footer -->
    <footer class="footer bg-dark text-white py-4">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <p>&copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. Todos os direitos reservados.</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <a href="<?php echo SITE_URL; ?>/privacidade" class="text-light me-3">Privacidade</a>
                    <a href="<?php echo SITE_URL; ?>/termos" class="text-light">Termos</a>
                </div>
            </div>
        </div>
    </footer>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Script de rastreamento personalizado -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Dados da página atual
        const pageData = {
            id: <?php echo $page['id']; ?>,
            type: '<?php echo $page['type']; ?>',
            title: '<?php echo addslashes($pageTitle); ?>',
            isNewUniqueVisit: <?php echo $isNewUniqueVisit ? 'true' : 'false'; ?>
        };
        
        console.log('Página carregada:', pageData);
        
        // Rastrear cliques nos CTAs
        document.querySelectorAll('[data-action]').forEach(function(element) {
            element.addEventListener('click', function(e) {
                const action = this.getAttribute('data-action');
                const pageId = this.getAttribute('data-page-id') || pageData.id;
                
                // Fazer requisição AJAX para registrar o clique
                fetch('<?php echo SITE_URL; ?>/api/track-action.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        page_id: pageId,
                        action: action,
                        target_url: this.href || this.getAttribute('data-target')
                    })
                }).then(response => response.json())
                  .then(data => {
                      console.log('Ação rastreada:', action, data);
                  })
                  .catch(error => {
                      console.error('Erro ao rastrear ação:', error);
                  });
                
                // Pequeno delay para garantir que a requisição seja enviada antes do redirecionamento
                if (this.tagName === 'A' && this.href) {
                    e.preventDefault();
                    setTimeout(() => {
                        window.location.href = this.href;
                    }, 100);
                }
            });
        });
        
        // Rastrear tempo na página
        let startTime = new Date().getTime();
        let maxScroll = 0;
        
        // Rastrear scroll
        window.addEventListener('scroll', function() {
            const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
            maxScroll = Math.max(maxScroll, scrollPercent);
        });
        
        // Rastrear saída da página
        window.addEventListener('beforeunload', function() {
            const timeSpent = Math.round((new Date().getTime() - startTime) / 1000);
            
            // Usar navigator.sendBeacon para garantir que os dados sejam enviados
            if (navigator.sendBeacon) {
                const data = JSON.stringify({
                    page_id: pageData.id,
                    time_spent: timeSpent,
                    max_scroll: maxScroll,
                    action: 'page-exit'
                });
                
                navigator.sendBeacon('<?php echo SITE_URL; ?>/api/track-action.php', data);
            }
        });
        
        // Rastrear engajamento a cada 30 segundos
        let engagementInterval = setInterval(function() {
            const timeSpent = Math.round((new Date().getTime() - startTime) / 1000);
            
            fetch('<?php echo SITE_URL; ?>/api/track-engagement.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    page_id: pageData.id,
                    time_spent: timeSpent,
                    max_scroll: maxScroll,
                    is_active: document.hasFocus()
                })
            }).catch(error => {
                console.error('Erro ao rastrear engajamento:', error);
            });
        }, 30000); // A cada 30 segundos
        
        // Parar rastreamento de engajamento quando a página perder o foco por muito tempo
        let focusTimeout;
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                focusTimeout = setTimeout(function() {
                    clearInterval(engagementInterval);
                }, 300000); // 5 minutos
            } else {
                clearTimeout(focusTimeout);
            }
        });
    });
    </script>
    
    <!-- Google Analytics (opcional) -->
    <?php if (defined('GOOGLE_ANALYTICS_ID') && !empty(GOOGLE_ANALYTICS_ID)): ?>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo GOOGLE_ANALYTICS_ID; ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo GOOGLE_ANALYTICS_ID; ?>');
        
        // Eventos customizados para o GA
        <?php if ($isNewUniqueVisit): ?>
        gtag('event', 'unique_page_view', {
            'event_category': 'engagement',
            'event_label': '<?php echo $page['type']; ?>',
            'page_id': <?php echo $page['id']; ?>
        });
        <?php endif; ?>
    </script>
    <?php endif; ?>
</body>
</html>