<?php
// pages/step1.php
// Primeira etapa do curso - Página de conteúdo com Preloader

// Configurações iniciais
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';

// Arquivo opcional de anúncios
if (file_exists(BASE_PATH . '/includes/ads-functions.php')) {
    require_once BASE_PATH . '/includes/ads-functions.php';
}

// Adicione após carregar os dados da página
require_once BASE_PATH . '/includes/unique-visits-tracker.php';

if (isset($page) && $page) {
    $uniqueVisitsTracker->trackUniqueVisit($page['id'], null, $page['title']);
}

// Inclui sistema de tracking UTM
if (file_exists(BASE_PATH . '/includes/utm-tracking.php')) {
    require_once BASE_PATH . '/includes/utm-tracking.php';
    
    // Apenas inicializa tracking
    try {
        initUtmTracking();
    } catch (Exception $e) {
        if (function_exists('logError')) {
            logError("Erro na inicialização do tracking UTM: " . $e->getMessage());
        }
    }
} else {
    // Fallback se arquivo não existir
    if (function_exists('logError')) {
        logError("Arquivo utm-tracking.php não encontrado");
    }
}

// Carrega helpers do WhatsApp de forma segura
$whatsappDynamicAvailable = false;
try {
    if (file_exists(BASE_PATH . '/includes/whatsapp-helper.php') && 
        file_exists(BASE_PATH . '/includes/whatsapp-dynamic.php')) {
        
        require_once BASE_PATH . '/includes/whatsapp-helper.php';
        require_once BASE_PATH . '/includes/whatsapp-dynamic.php';
        $whatsappDynamicAvailable = true;
    }
} catch (Exception $e) {
    error_log("Erro ao carregar WhatsApp helpers: " . $e->getMessage());
}

/**
 * Insere um botão CTA após o quarto parágrafo do conteúdo
 */
function insertIntermediateButton($content, $ctaLink, $pageId) {
    // Remove quebras de linha desnecessárias e normaliza o HTML
    $content = trim($content);
    
    // Encontra todos os parágrafos no conteúdo
    preg_match_all('/<p[^>]*>.*?<\/p>/is', $content, $matches, PREG_OFFSET_CAPTURE);
    
    $paragraphs = $matches[0];
    
    // Se não há pelo menos 4 parágrafos, insere no final
    if (count($paragraphs) < 4) {
        $buttonHtml = generateIntermediateButtonHtml($ctaLink, $pageId);
        return $content . $buttonHtml;
    }
    
    // Pega o quarto parágrafo (índice 3)
    $fourthParagraph = $paragraphs[3];
    $insertPosition = $fourthParagraph[1] + strlen($fourthParagraph[0]);
    
    // Gera o HTML do botão
    $buttonHtml = generateIntermediateButtonHtml($ctaLink, $pageId);
    
    // Insere o botão após o quarto parágrafo
    $newContent = substr($content, 0, $insertPosition) . $buttonHtml . substr($content, $insertPosition);
    
    return $newContent;
}

/**
 * Gera o HTML do botão intermediário
 */
function generateIntermediateButtonHtml($ctaLink, $pageId) {
    return '
    <div class="intermediate-cta-section">
        <div class="intermediate-cta-container">
            <p class="intermediate-cta-text">¿Quieres acceder al curso completo?</p>
            <a href="' . htmlspecialchars($ctaLink) . '" 
               class="intermediate-cta-button" 
               onclick="registrarRedirecionamento(\'cta_intermediate\', ' . intval($pageId) . ')"
               data-page-id="' . intval($pageId) . '">
                <i class="fas fa-play-circle me-2"></i>
                Vea cómo inscribirse en el curso
                <i class="fas fa-arrow-right ms-2"></i>
            </a>
        </div>
    </div>';
}

// Inicializa tracking da página
$pageType = 'step1';
$pageId = isset($_GET['id']) ? intval($_GET['id']) : null;
$slug = isset($_GET['slug']) ? sanitizeInput($_GET['slug']) : null;

// Busca a página no banco de dados
try {
    $landingId = isset($_GET['landing']) ? intval($_GET['landing']) : null;
    
    if ($landingId) {
        // Se chegou via ?landing=7, busca step1 específico vinculado à landing 7
        $db->query("SELECT * FROM pages WHERE landing_page_id = :landing_id AND type = :type AND published = 1 ORDER BY sequence ASC LIMIT 1");
        $db->bind(':landing_id', $landingId);
        $db->bind(':type', $pageType);
    } else if ($pageId) {
        // Busca por ID específico
        $db->query("SELECT * FROM pages WHERE id = :id AND type = :type AND published = 1");
        $db->bind(':id', $pageId);
        $db->bind(':type', $pageType);
    } else if ($slug) {
        // Busca por slug
        $db->query("SELECT * FROM pages WHERE slug = :slug AND type = :type AND published = 1");
        $db->bind(':slug', $slug);
        $db->bind(':type', $pageType);
    } else {
        // Busca qualquer step1
        $db->query("SELECT * FROM pages WHERE type = :type AND published = 1 ORDER BY sequence ASC LIMIT 1");
        $db->bind(':type', $pageType);
    }
    
    $page = $db->single();
    
    if (!$page) {
        // Define valores padrão para evitar erro
        $pageTitle = 'Página não encontrada';
        $metaDescription = 'A página solicitada não foi encontrada.';
        $currentPage = 'step1';
        $showHeader = false;
        
        require_once BASE_PATH . '/includes/header.php';
        echo '<div class="container mt-5"><div class="alert alert-warning text-center"><h4>Página não encontrada</h4><p>A página que você está procurando não existe ou foi removida.</p><a href="/" class="btn btn-primary">Voltar ao início</a></div></div>';
        require_once BASE_PATH . '/includes/footer.php';
        exit;
    }
    
    // DEFINIR VARIÁVEIS PARA O HEADER (ANTES DE INCLUIR)
    $pageTitle = $page['title'];
    $metaDescription = $page['meta_description'] ?: 'Continue sua jornada de aprendizado com esta etapa do curso gratuito';
    $metaKeywords = 'curso gratuito, etapa 1, aprendizado, educação online, conteúdo educativo';
    $currentPage = 'step1';
    $showHeader = false; // Usaremos hero customizado
    $pageDescription = $page['excerpt'] ?: 'Primera etapa de tu transformación profesional';
    
    // Buscar informações da landing page para breadcrumbs
    $landingPageTitle = 'Curso';
    $landingPageSlug = '';
    if (!empty($page['landing_page_id'])) {
        try {
            $db->query("SELECT title, slug FROM pages WHERE id = :id AND type = 'landing'");
            $db->bind(':id', $page['landing_page_id']);
            $landingPage = $db->single();
            if ($landingPage) {
                $landingPageTitle = $landingPage['title'];
                $landingPageSlug = $landingPage['slug'];
            }
        } catch (Exception $e) {
            error_log("Erro ao buscar landing page: " . $e->getMessage());
        }
    }
    
    // Breadcrumbs
    $breadcrumbs = [
        '/cursos.php' => 'Cursos',
        '/pages/landing/' . $landingPageSlug => $landingPageTitle,
        '' => 'Paso 1'
    ];
    
    // Estilos customizados para esta página + Preloader + Botão Intermediário
    $customStyles = '
        /* ===== PRELOADER STYLES ===== */
        #preloader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #4F46E5, #7C3AED);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            transition: opacity 0.5s ease;
        }

        #preloader.fade-out {
            opacity: 0;
            pointer-events: none;
        }

        .preloader-content {
            text-align: center;
            color: white;
            font-family: "Poppins", sans-serif;
        }

        .preloader-logo {
            margin-bottom: 2rem;
        }

        .preloader-logo i {
            font-size: 3rem;
            margin-bottom: 1rem;
            display: block;
        }

        .preloader-logo h2 {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
        }

        .preloader-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            margin: 2rem auto;
            animation: preloaderSpin 1s linear infinite;
        }

        .preloader-progress-bar {
            width: 200px;
            height: 4px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 2px;
            margin: 1rem auto;
            overflow: hidden;
        }

        .preloader-progress {
            height: 100%;
            background: white;
            border-radius: 2px;
            width: 0%;
            transition: width 0.1s ease;
        }

        .preloader-text {
            font-size: 0.9rem;
            opacity: 0.8;
            margin-top: 1rem;
        }

        @keyframes preloaderSpin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        body.loading {
            overflow: hidden;
        }

        body.loading .main-wrapper {
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.5s ease;
        }

        body:not(.loading) .main-wrapper {
            opacity: 1;
            pointer-events: auto;
        }

        /* ===== BOTÃO INTERMEDIÁRIO STYLES ===== */
        .intermediate-cta-section {
            margin: 2rem 0;
            padding: 0;
            animation: slideInFromLeft 0.6s ease;
        }

        .intermediate-cta-container {
            text-align: center;
            padding: 1.5rem;
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(16, 185, 129, 0.1));
            border: 2px solid rgba(34, 197, 94, 0.2);
            border-radius: 12px;
            position: relative;
            overflow: hidden;
        }

        .intermediate-cta-container::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(34, 197, 94, 0.1), transparent);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            0% { left: -100%; }
            100% { left: 100%; }
        }

        @keyframes slideInFromLeft {
            0% {
                opacity: 0;
                transform: translateX(-50px);
            }
            100% {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .intermediate-cta-text {
            color: #065f46;
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 1rem;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .intermediate-cta-button {
            display: inline-block;
            background: linear-gradient(45deg, #22c55e, #16a34a);
            color: white !important;
            font-weight: 600;
            padding: 1rem 2rem;
            border-radius: 8px;
            text-decoration: none !important;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4);
            font-size: 1rem;
            border: none;
            cursor: pointer;
            position: relative;
            z-index: 1;
            overflow: hidden;
        }

        .intermediate-cta-button::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(45deg, #16a34a, #15803d);
            transition: left 0.3s ease;
            z-index: -1;
        }

        .intermediate-cta-button:hover::before {
            left: 0;
        }

        .intermediate-cta-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(34, 197, 94, 0.6);
            color: white !important;
        }

        .intermediate-cta-button:active {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4);
        }

        .intermediate-cta-button i {
            transition: transform 0.3s ease;
        }

        .intermediate-cta-button:hover i.fa-arrow-right {
            transform: translateX(5px);
        }

        .intermediate-cta-button:hover i.fa-play-circle {
            transform: scale(1.1);
        }

        /* ===== PÁGINA STYLES ===== */
        
        .step-indicator {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 2rem 0;
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }
        
        .step {
            width: 55px;
            height: 55px;
            border-radius: 50%;
            background: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            position: relative;
            z-index: 2;
            text-decoration: none;
            color: #666;
            cursor: pointer;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }
        
        .step-active {
            background: var(--gradient);
            color: white;
            animation: pulse 2s infinite;
        }
        
        .step-complete {
            background: #10B981;
            color: white;
        }
        
        .step-line {
            flex-grow: 1;
            height: 4px;
            background: #e0e0e0;
            margin: 0 20px;
            max-width: 150px;
            position: relative;
            flex-shrink: 0;
        }
        
        .step-line-active {
            background: var(--gradient);
        }
        
        .step-line-complete {
            background: #10B981;
        }
        
        .step:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.3);
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(79, 70, 229, 0); }
            100% { box-shadow: 0 0 0 0 rgba(79, 70, 229, 0); }
        }

        .step:not(.step-active):not(.step-complete) {
            opacity: 0.7;
        }

        .step:not(.step-active):not(.step-complete):hover {
            opacity: 1;
        }
        
        .step-label {
            display: block;
            text-align: center;
            margin-top: 0.7rem;
            font-size: 0.85rem;
            font-weight: 500;
            color: #666;
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            white-space: nowrap;
        }
        
        .step-active .step-label {
            color: var(--primary-color);
            font-weight: 600;
        }
        
        .step-complete .step-label {
            color: #10B981;
        }
        
        .hero-section::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url("data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1000 100\" fill=\"rgba(255,255,255,0.1)\"><polygon points=\"1000,100 1000,0 0,100\"/></svg>") no-repeat bottom;
            background-size: cover;
        }
        
        .hero-content {
            max-width: 800px;
            margin: 0 auto;
            position: relative;
            z-index: 1;
        }
        
        .hero-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 1rem;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .hero-subtitle {
            font-size: 1.1rem;
            margin-bottom: 2rem;
            opacity: 0.95;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        .main-content {
            background: white;
            padding: 3rem 0;
            border-radius: 1rem;
            margin-top: -2rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 2;
        }
        
        .content-block {
            max-width: 800px;
            margin: 0 auto;
            padding: 0 1.5rem;
        }
        
        .content-block img {
            max-width: 100%;
            height: auto;
            border-radius: 0.5rem;
            margin: 1.5rem 0;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        .learning-box {
            background: rgba(79, 70, 229, 0.05);
            border: 1px solid rgba(79, 70, 229, 0.2);
            border-radius: 12px;
            padding: 1.5rem;
            margin: 2rem 0;
            position: relative;
            overflow: hidden;
        }
        
        .learning-box::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: var(--gradient);
        }
        
        .learning-box h4 {
            color: var(--primary-color);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            font-weight: 600;
        }
        
        .learning-box h4 i {
            margin-right: 0.5rem;
            font-size: 1.2rem;
        }
        
        .learning-box ul {
            margin: 0;
            padding-left: 1.5rem;
        }
        
        .learning-box li {
            margin-bottom: 0.5rem;
            color: var(--dark-color);
        }
        
        .cta-button {
            display: inline-block;
            background: linear-gradient(90deg, #facc15, #fbbf24);
            color: #000 !important;
            font-weight: 600;
            padding: 1.2rem 2.5rem;
            border-radius: 8px;
            text-decoration: none !important;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(250, 204, 21, 0.4);
            font-size: 1.1rem;
            border: none;
            cursor: pointer;
        }

        .cta-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(250, 204, 21, 0.6);
            color: #000 !important;
            background: linear-gradient(90deg, #fbbf24, #f59e0b);
        }
        
        .whatsapp-cta-container {
            text-align: center;
            margin: 30px 0;
            padding: 25px;
            background-color: rgba(37, 211, 102, 0.1);
            border-radius: 12px;
            border: 1px solid rgba(37, 211, 102, 0.2);
        }

        .whatsapp-title {
            color: #075E54;
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }

        .whatsapp-cta-button {
            display: inline-block;
            background-color: #25D366;
            color: white !important;
            font-weight: 600;
            font-size: 16px;
            padding: 15px 25px;
            border-radius: 8px;
            text-decoration: none !important;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(37, 211, 102, 0.4);
            border: none;
        }

        .whatsapp-cta-button:hover {
            background-color: #20bf5b;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(37, 211, 102, 0.5);
            color: white !important;
        }

        .whatsapp-cta-button i {
            margin-right: 10px;
            font-size: 20px;
        }    
        
        .navigation-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 3rem;
            gap: 1rem;
        }
        
        .prev-button {
            background: white;
            color: var(--primary-color);
            border: 2px solid var(--primary-color);
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .prev-button:hover {
            background: var(--primary-color);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(79, 70, 229, 0.3);
        }
        
        .progress-bar-container {
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 1rem;
            margin: 1rem 0;
            height: 8px;
            overflow: hidden;
        }
        
        .progress-bar {
            height: 100%;
            background: var(--gradient);
            width: 66.66%;
            border-radius: 1rem;
            transition: width 0.8s ease;
        }

        .author-info {
            margin-top: 3rem;
            padding: 1.5rem;
            background: linear-gradient(to right, rgba(79, 70, 229, 0.05), rgba(124, 58, 237, 0.05));
            border-radius: 12px;
            position: relative;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.03);
            transition: all 0.3s ease;
        }

        .author-info:hover {
            box-shadow: 0 5px 15px rgba(79, 70, 229, 0.1);
            transform: translateY(-2px);
        }

        .author-info:before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 4px;
            background: var(--gradient);
            border-radius: 12px 0 0 12px;
        }

        .post-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
            align-items: center;
            margin: 0;
            font-size: 0.95rem;
            color: var(--dark-color);
        }

        .post-meta .author, 
        .post-meta .date {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 0.8rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        .post-meta .author:hover, 
        .post-meta .date:hover {
            background-color: rgba(255, 255, 255, 0.9);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
            transform: translateY(-1px);
        }

        .post-meta i {
            color: var(--primary-color);
            font-size: 1rem;
        }

        .post-meta .author i {
            color: #7C3AED;
        }

        .post-meta .date i {
            color: #4F46E5;
        }

        .cta-section {
            background: var(--light-color);
            padding: 2rem;
            margin: 3rem 0;
            border-radius: 1rem;
            text-align: center;
            border: 1px solid var(--border-color);
        }

        .cta-section h3 {
            color: var(--dark-color);
            margin-bottom: 1rem;
        }

        .floating-nav {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            padding: 1rem;
            border-radius: 50px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: none;
        }

        .floating-nav.show {
            display: block;
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from { transform: translateX(-50%) translateY(100%); }
            to { transform: translateX(-50%) translateY(0); }
        }
        
        @media (max-width: 768px) {
            .preloader-logo i { font-size: 2.5rem; }
            .preloader-logo h2 { font-size: 1.2rem; }
            .preloader-progress-bar { width: 150px; }
            
            .hero-title {
                font-size: 1.5rem;
            }
            
            .hero-subtitle {
                font-size: 1rem;
            }
            
            .hero-section {
                padding: 2rem 0;
            }
            
            .navigation-buttons {
                flex-direction: column;
                gap: 1rem;
            }
            
            .prev-button, .cta-button {
                width: 100%;
                text-align: center;
                justify-content: center;
            }
            
            .step-indicator {
                max-width: 400px;
            }
            
            .step {
                width: 45px;
                height: 45px;
                font-size: 14px;
            }
            
            .step-line {
                margin: 0 15px;
                max-width: 100px;
            }

            .step-label {
                font-size: 0.8rem;
            }

            .author-info {
                padding: 1rem;
                margin-top: 2rem;
            }
            
            .post-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.8rem;
            }
            
            .post-meta .author, 
            .post-meta .date {
                width: 100%;
            }

            .floating-nav {
                bottom: 10px;
                left: 10px;
                right: 10px;
                transform: none;
                border-radius: 12px;
            }

            /* Botão intermediário mobile */
            .intermediate-cta-container {
                padding: 1rem;
            }

            .intermediate-cta-button {
                padding: 0.875rem 1.5rem;
                font-size: 0.95rem;
                width: 100%;
                box-sizing: border-box;
            }

            .intermediate-cta-text {
                font-size: 1rem;
            }
        }
    ';
    
    // Processar o conteúdo para inserir anúncios
    if (function_exists('insertAdsInContent')) {
        $page['content'] = insertAdsInContent($page['content'], $pageType);
    }    
        
    // Registra visualização da página
    $db->query("INSERT INTO page_views (page_id, visitor_ip, user_agent) 
               VALUES (:page_id, :visitor_ip, :user_agent)");
    $db->bind(':page_id', $page['id']);
    $db->bind(':visitor_ip', $_SERVER['REMOTE_ADDR']);
    $db->bind(':user_agent', $_SERVER['HTTP_USER_AGENT'] ?? '');
    $db->execute();
    
    // Registra page view com UTMs
    if (function_exists('registerConversion')) {
        try {
            registerConversion($page['id'], 'page_view', [
                'page_type' => 'step1',
                'page_title' => $page['title'] ?? '',
                'landing_page_id' => $page['landing_page_id'] ?? null
            ]);
        } catch (Exception $e) {
            if (function_exists('logError')) {
                logError("Erro no registro de conversão: " . $e->getMessage());
            }
        }
    }
    
    // Registra acesso com pixel se a página estiver associada a uma landing
    if (isset($page) && !empty($page['landing_page_id'])) {
        try {
            if (isset($pixelIntegraOn) && is_object($pixelIntegraOn)) {
                $pixelIntegraOn->registerAccess($page['id'], $_SESSION['utm_params'] ?? []);
            }
        } catch (Exception $e) {
            if (function_exists('logError')) {
                logError("Erro no registro do pixel: " . $e->getMessage());
            }
        }
    }
    
    // Define as URLs baseadas na landing_page_id desta página
    $landingPageId = $page['landing_page_id'] ?? $landingId ?? 0;
    
    // URLs simples e diretas
    $landingUrl = '/pages/landing?id=' . $landingPageId;
    $step1Url = '/pages/step1?landing=' . $landingPageId;
    $registrationUrl = '/pages/registration?landing=' . $landingPageId;
    
    // Navegação
    $prevPageUrl = $landingUrl;  // Voltar sempre para a landing
    $nextPageUrl = $registrationUrl;  // Avançar sempre para registration
    
    // Define o link do CTA (usa o configurado da página ou a próxima etapa)
    $ctaLink = !empty($page['cta_link']) ? $page['cta_link'] : $nextPageUrl;
    
} catch (Exception $e) {
    if (function_exists('logError')) {
        logError("Erro ao carregar página step1: " . $e->getMessage());
    }
    
    // Define valores padrão em caso de erro
    $pageTitle = 'Erro ao carregar página';
    $metaDescription = 'Ocorreu um erro ao carregar a página solicitada.';
    $currentPage = 'step1';
    $showHeader = false;
    
    require_once BASE_PATH . '/includes/header.php';
    echo '<div class="container mt-5"><div class="alert alert-danger text-center"><h4>Erro</h4><p>Ocorreu um erro ao carregar a página. Por favor, tente novamente mais tarde.</p><a href="/" class="btn btn-primary">Voltar ao início</a></div></div>';
    require_once BASE_PATH . '/includes/footer.php';
    exit;
}

// INCLUIR O HEADER (APÓS DEFINIR TODAS AS VARIÁVEIS)
require_once BASE_PATH . '/includes/header.php';
?>
<!-- AdSense carregado ANTES do preloader -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9919806376063326"
     crossorigin="anonymous"></script>
    <script>
    // Adiciona classe loading ao body imediatamente
    document.body.classList.add('loading');
    </script>

    <!-- PRELOADER -->
    <div id="preloader">
        <div class="preloader-content">
            <div class="preloader-logo">
                <i class="fas fa-graduation-cap"></i>
                <h2>Curso Gratuito</h2>
            </div>
            
            <div class="preloader-spinner"></div>
            
            <div class="preloader-progress-bar">
                <div class="preloader-progress" id="preloaderProgress"></div>
            </div>
            
            <p class="preloader-text">Cargando contenido...</p>
        </div>
    </div>

    <!-- CONTEÚDO PRINCIPAL -->
    <div class="main-wrapper">
        <!-- Hero Section Customizado -->
        <header class="hero-section">
            <div class="container">
                <div class="hero-content text-center"><br>
                    <h1 class="hero-title"><?php echo htmlspecialchars($page['title']); ?></h1>
                     <!-- Anúncio no topo do conteúdo -->
                    <center><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9919806376063326"
     crossorigin="anonymous"></script>
<!-- Lebeh -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-9919806376063326"
     data-ad-slot="6544644851"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></center><br>
                    <p class="page-subtitle">¿Quieres saber cómo inscribirte en el curso?</p>
                    
                    <!-- Botão CTA Principal no Hero -->
                    <a href="<?php echo htmlspecialchars($ctaLink); ?>" class="cta-button" onclick="registrarRedirecionamento('cta_hero', <?php echo $page['id']; ?>)">
                        <i class="fas fa-graduation-cap me-2"></i>
                        <?php echo htmlspecialchars($page['cta_text'] ?: 'Ir al Registro'); ?>
                        <i class="fas fa-arrow-right ms-2"></i>
                    </a>
                </div>
            </div>
        </header>

        <div class="container">
            <!-- Barra de Progresso - Sempre 3 etapas fixas -->
            <div class="step-indicator">
                <!-- Etapa 1 (Landing) - Completa -->
                <a href="<?php echo htmlspecialchars($prevPageUrl); ?>" class="step step-complete" title="Página Inicial - Completa">
                    <i class="fas fa-check"></i>
                </a>
                
                <div class="step-line step-line-complete"></div>
                
                <!-- Etapa 2 (Conteúdo) - Ativa -->
                <div class="step step-active" title="Conteúdo do Curso - Atual">
                    <i class="fas fa-book"></i>
                </div>
                
                <div class="step-line"></div>
                
                <!-- Etapa 3 (Registro) -->
                <div class="step" title="Registro Final">
                    <i class="fas fa-graduation-cap"></i>
                </div>
            </div>
            
            <div class="progress-bar-container" title="Progresso: 67% completo">
                <div class="progress-bar"></div>
            </div>
           
            <div class="main-content">
                
                        <div class="content-block">
                    <?php 
                    try {
                        // Processa o conteúdo para inserir o botão intermediário
                        $processedContent = $page['content'];
                        
                        // Insere o botão após o quarto parágrafo
                        $processedContent = insertIntermediateButton(
                            $processedContent, 
                            $ctaLink, 
                            $page['id']
                        );
                        
                        // Processa para WhatsApp dinâmico se disponível
                        if ($whatsappDynamicAvailable && isset($whatsappDynamic) && is_object($whatsappDynamic)) {
                            $processedContent = $whatsappDynamic->processContent($processedContent);
                        }
                        
                        // Exibe o conteúdo processado
                        echo $processedContent;
                        
                    } catch (Exception $e) {
                        // Em caso de erro, sempre exibe o conteúdo original
                        error_log("Erro no processamento do conteúdo: " . $e->getMessage());
                        echo $page['content'];
                    }
                    ?>
                    
                    <div class="learning-box">
                        <h4><i class="fas fa-lightbulb"></i> Puntos Importantes</h4>
                        <ul>
                            <li>Comprenda los conceptos fundamentales presentados en esta etapa</li>
                            <li>Practique los ejercicios sugeridos para consolidar el conocimiento</li>
                            <li>Tome notas de los aspectos más relevantes para su situación</li>
                            <li>Avance a la siguiente etapa cuando se sienta seguro con el contenido</li>
                        </ul>
                    </div>

                    <!-- Autor e data de publicação -->
                    <div class="author-info">
                        <?php
                        try {
                            $publishDate = new DateTime($page['created_at'] ?? 'now');
                            $formattedDate = $publishDate->format('d/m/Y');
                            
                            // Nome do autor
                            $authorName = "Sebastian Álvarez";
                            if (!empty($page['author_id'])) {
                                $db->query("SELECT username FROM admins WHERE id = :author_id");
                                $db->bind(':author_id', $page['author_id']);
                                $author = $db->single();
                                if ($author && isset($author['username'])) {
                                    $authorName = htmlspecialchars($author['username']);
                                }
                            }
                        } catch (Exception $e) {
                            error_log("Erro ao buscar info do autor: " . $e->getMessage());
                            $authorName = "Sebastian Álvarez";
                            $formattedDate = date('d/m/Y');
                        }
                        ?>
                        <p class="post-meta">
                            <span class="author">
                                <i class="fas fa-user-edit"></i> 
                                <?php echo $authorName; ?>
                            </span>
                            <span class="date">
                                <i class="fas fa-calendar-alt"></i> 
                                <?php echo $formattedDate; ?>
                            </span>
                            <span class="date">
                                <i class="fas fa-folder"></i> 
                                Cursos Gratuitos
                            </span>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Navegação flutuante (apenas mobile) -->
        <div class="floating-nav d-md-none" id="floatingNav">
            <div class="d-flex justify-content-between align-items-center">
                <a href="<?php echo htmlspecialchars($prevPageUrl); ?>" class="btn btn-outline-primary btn-sm">
                    <i class="fas fa-arrow-left"></i>
                </a>
                <span class="mx-3 small text-muted">Paso 1 de 3</span>
                <a href="<?php echo htmlspecialchars($ctaLink); ?>" class="btn btn-primary btn-sm">
                    <i class="fas fa-arrow-right"></i>
                </a>
            </div>
        </div>
    </div>

    <!-- Scripts específicos da página + Preloader -->
    <script>
    // PRELOADER JAVASCRIPT
    document.addEventListener('DOMContentLoaded', function() {
        const preloader = document.getElementById('preloader');
        const progress = document.getElementById('preloaderProgress');
        
        let progressValue = 0;
        const duration = 2000; // 2 segundos
        const interval = 50;
        const increment = (100 * interval) / duration;
        
        const progressInterval = setInterval(() => {
            progressValue += increment;
            
            if (progressValue >= 100) {
                progressValue = 100;
                clearInterval(progressInterval);
                
                setTimeout(() => {
                    preloader.classList.add('fade-out');
                    document.body.classList.remove('loading');
                    
                    setTimeout(() => {
                        if (preloader.parentNode) {
                            preloader.parentNode.removeChild(preloader);
                        }
                    }, 500);
                }, 200);
            }
            
            if (progress) {
                progress.style.width = progressValue + '%';
            }
        }, interval);
        
        // CÓDIGO DA PÁGINA APÓS PRELOADER
        setTimeout(() => {
            initPageFunctions();
        }, 2500);
    });
    
    function initPageFunctions() {
        // Função para tracking com UTMs
        function registrarRedirecionamento(tipo, pageId) {
            // Coleta UTMs do localStorage se disponível
            const utmData = {};
            const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
            
            // Tenta coletar UTMs da URL atual
            const urlParams = new URLSearchParams(window.location.search);
            utmParams.forEach(param => {
                if (urlParams.has(param)) {
                    utmData[param] = urlParams.get(param);
                }
            });
            
            // Dados para envio
            const trackingData = {
                action: 'redirect',
                tipo: tipo,
                page_id: pageId,
                utm_data: utmData,
                referrer: document.referrer,
                timestamp: Date.now()
            };
            
            if (typeof fetch !== 'undefined') {
                fetch('/includes/track.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(trackingData)
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Tracking successful:', data);
                    
                    // Envia para pixels se disponíveis
                    sendToPixels(tipo, utmData);
                })
                .catch(error => {
                    console.error('Tracking error:', error);
                });
            }
        }

        // Função para enviar dados aos pixels
        function sendToPixels(eventType, utmData) {
            // Facebook Pixel
            if (typeof fbq !== 'undefined') {
                fbq('track', 'CustomEvent', {
                    event_type: eventType,
                    utm_source: utmData.utm_source || '',
                    utm_campaign: utmData.utm_campaign || ''
                });
            }
            
            // Google Analytics
            if (typeof gtag !== 'undefined') {
                gtag('event', eventType, {
                    custom_map: utmData
                });
            }
            
            // JoinAds
            if (typeof window.joinads !== 'undefined') {
                window.joinads.track(eventType, utmData);
            }
        }

        // Auto-captura UTMs na primeira carga
        const urlParams = new URLSearchParams(window.location.search);
        const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
        const hasUtms = utmParams.some(param => urlParams.has(param));
        
        if (hasUtms) {
            console.log('UTMs detectados na URL:', Object.fromEntries(urlParams));
            
            // Registra page view automaticamente se há UTMs
            registrarRedirecionamento('auto_page_view', <?php echo $page['id'] ?? 0; ?>);
        }

        // Expor função globalmente
        window.registrarRedirecionamento = registrarRedirecionamento;
        
        // Animação da barra de progresso
        const progressBar = document.querySelector('.progress-bar');
        if (progressBar) {
            setTimeout(() => {
                progressBar.style.width = '66.66%';
            }, 500);
        }

        // Navegação flutuante no mobile
        const floatingNav = document.getElementById('floatingNav');
        let lastScrollY = window.scrollY;

        window.addEventListener('scroll', () => {
            if (window.innerWidth <= 768) {
                const currentScrollY = window.scrollY;
                
                if (currentScrollY > 300 && currentScrollY > lastScrollY) {
                    // Scrolling down
                    floatingNav.classList.add('show');
                } else if (currentScrollY < lastScrollY - 50) {
                    // Scrolling up significantly
                    floatingNav.classList.remove('show');
                }
                
                lastScrollY = currentScrollY;
            }
        });

        // Rastrear cliques nas etapas
        const stepLinks = document.querySelectorAll('.step-indicator .step');
        
        stepLinks.forEach(function(link) {
            link.addEventListener('click', function(e) {
                const currentStep = '<?php echo $pageType; ?>';
                
                // Registrar navegação na etapa
                fetch('/includes/track.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'action=step_navigation&from=' + currentStep + '&to=' + this.getAttribute('href') + '&page_id=' + <?php echo $page['id']; ?>
                })
                .then(response => response.json())
                .catch(error => console.error('Tracking error:', error));
            });
        });

        // Intersection Observer para animações
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, observerOptions);

        // Observa elementos para animação incluindo o botão intermediário
        document.querySelectorAll('.learning-box, .author-info, .cta-section, .navigation-buttons, .intermediate-cta-section').forEach(el => {
            el.style.opacity = '0';
            el.style.transform = 'translateY(20px)';
            el.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            observer.observe(el);
        });

        // Loading states para botões (incluindo o botão intermediário)
        document.querySelectorAll('.cta-button, .prev-button, .intermediate-cta-button').forEach(button => {
            button.addEventListener('click', function() {
                if (!this.classList.contains('loading')) {
                    this.classList.add('loading');
                    const originalText = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Cargando...';
                    
                    // Remove o loading após 2 segundos
                    setTimeout(() => {
                        this.classList.remove('loading');
                        this.innerHTML = originalText;
                    }, 2000);
                }
            });
        });

        // Animação especial para o botão intermediário quando fica visível
        const intermediateButton = document.querySelector('.intermediate-cta-button');
        if (intermediateButton) {
            const intermediateObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        setTimeout(() => {
                            entry.target.style.animation = 'pulse 0.6s ease';
                        }, 300);
                    }
                });
            }, { threshold: 0.8 });
            
            intermediateObserver.observe(intermediateButton);
        }

        // Smooth scroll para links internos
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });

        // Debug UTMs (apenas se debug=1 na URL)
        if (urlParams.has('debug') && urlParams.get('debug') === '1') {
            console.log('=== DEBUG UTM ===');
            console.log('UTMs na URL:', Object.fromEntries(urlParams));
            console.log('UTMs no sessionStorage:', {
                utm_source: sessionStorage.getItem('utm_source'),
                utm_medium: sessionStorage.getItem('utm_medium'),
                utm_campaign: sessionStorage.getItem('utm_campaign')
            });
        }
    }

    // CSS adicional para estados de loading
    const style = document.createElement('style');
    style.textContent = `
        .loading {
            opacity: 0.7;
            pointer-events: none;
        }
        
        .loading:hover {
            transform: none !important;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
    `;
    document.head.appendChild(style);
    </script>

    <!-- UTM Tracking Scripts -->
    <script>
    // Preserva UTMs durante navegação
    (function() {
        // Captura UTMs da URL atual
        const urlParams = new URLSearchParams(window.location.search);
        const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'gclid', 'fbclid'];
        const currentUtms = {};
        
        utmParams.forEach(param => {
            if (urlParams.has(param)) {
                currentUtms[param] = urlParams.get(param);
                // Preserva no sessionStorage
                sessionStorage.setItem(param, urlParams.get(param));
            }
        });
        
        // Adiciona UTMs preservados aos links internos
        document.addEventListener('DOMContentLoaded', function() {
            const internalLinks = document.querySelectorAll('a[href^="/"], a[href^="./"], a[href^="../"]');
            
            internalLinks.forEach(link => {
                link.addEventListener('click', function() {
                    const href = this.getAttribute('href');
                    const hasQuery = href.includes('?');
                    const separator = hasQuery ? '&' : '?';
                    
                    // Adiciona UTMs preservados ao link
                    const utmString = utmParams
                        .filter(param => sessionStorage.getItem(param))
                        .map(param => `${param}=${encodeURIComponent(sessionStorage.getItem(param))}`)
                        .join('&');
                        
                    if (utmString) {
                        this.setAttribute('href', href + separator + utmString);
                    }
                });
            });
        });
    })();
    </script>

    <!-- Script final para envio de UTMs aos pixels -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Envia UTMs para todos os pixels configurados
        <?php
        if (function_exists('sendUtmsToPixels')) {
            sendUtmsToPixels();
        }
        ?>
    });
    </script>

<script>
function registrarConversao(tipo, pageId, valor = null) {
    // Dados adicionais da conversão
    const conversionData = {
        page_url: window.location.pathname,
        page_title: document.title,
        timestamp: Date.now(),
        user_agent: navigator.userAgent
    };
    
    // Envia via AJAX
    fetch('/includes/track-conversion.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            page_id: pageId,
            conversion_type: tipo,
            conversion_value: valor,
            conversion_data: conversionData
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Conversão registrada:', tipo);
        }
    })
    .catch(error => {
        console.error('Erro ao registrar conversão:', error);
    });
}

// Exemplo de uso nos botões (incluindo o botão intermediário)
document.addEventListener('DOMContentLoaded', function() {
    // CTAs principais e intermediários
    document.querySelectorAll('.cta-button, .intermediate-cta-button').forEach(button => {
        button.addEventListener('click', function() {
            const pageId = this.getAttribute('data-page-id') || 0;
            const buttonType = this.classList.contains('intermediate-cta-button') ? 'intermediate_cta_click' : 'cta_click';
            registrarConversao(buttonType, pageId, this.textContent);
        });
    });
    
    // Links do WhatsApp
    document.querySelectorAll('.whatsapp-cta-button').forEach(button => {
        button.addEventListener('click', function() {
            const pageId = this.getAttribute('data-page-id') || 0;
            registrarConversao('whatsapp_click', pageId, this.href);
        });
    });
    
    // Formulários
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function() {
            const pageId = this.getAttribute('data-page-id') || 0;
            registrarConversao('form_submit', pageId, this.action);
        });
    });
});
</script>

<script>
function initializeAdsense() {
    // Aguarda o preloader terminar
    setTimeout(function() {
        // Verifica se o AdSense ainda não foi inicializado
        if (typeof adsbygoogle !== 'undefined') {
            // Encontra todos os anúncios não inicializados
            const ads = document.querySelectorAll('.adsbygoogle');
            ads.forEach(function(ad) {
                if (!ad.dataset.adsbygoogleStatus) {
                    (adsbygoogle = window.adsbygoogle || []).push({});
                }
            });
        }
    }, 3000); // Após o preloader + margem de segurança
}

// Inicializa quando a página estiver pronta
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAdsense);
} else {
    initializeAdsense();
}
</script>

<?php
// Incluir o footer
require_once BASE_PATH . '/includes/footer.php';
?>