<?php
defined('ABSPATH') || exit;

// Track block usage (first render only)
if (function_exists('ezhp_track_block_usage')) {
    ezhp_track_block_usage('daily-horoscope', $attributes);
}

// Sanitize inputs
$ezhp_sign            = sanitize_text_field($attributes['sign'] ?? 'aries');
$ezhp_horoscope_style = sanitize_text_field($attributes['horoscopeStyle'] ?? 'poetic');
$ezhp_language        = sanitize_text_field($attributes['language'] ?? 'en');
$ezhp_api_key         = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

// Professional style is premium-only — force poetic for free users
if ( function_exists( 'ezhp_fs' ) && ezhp_fs()->can_use_premium_code__premium_only() ) {
    // Premium user — allow professional style
} else {
    // Free user — force poetic
    $ezhp_horoscope_style = 'poetic';
}

// RTL language detection
$ezhp_rtl_languages = array('ar', 'he', 'fa', 'ur', 'yi', 'ps', 'sd');
$ezhp_is_rtl = in_array($ezhp_language, $ezhp_rtl_languages, true);

// Section visibility attributes
$ezhp_show_hero       = isset($attributes['showHeroSection']) ? (bool) $attributes['showHeroSection'] : true;
$ezhp_show_guidance   = isset($attributes['showGuidanceSection']) ? (bool) $attributes['showGuidanceSection'] : true;
$ezhp_show_advice     = isset($attributes['showAdviceSection']) ? (bool) $attributes['showAdviceSection'] : true;
$ezhp_show_conclusion = isset($attributes['showConclusionSection']) ? (bool) $attributes['showConclusionSection'] : true;

// Planet visibility attributes
$ezhp_show_moon    = isset($attributes['showMoonItem']) ? (bool) $attributes['showMoonItem'] : true;
$ezhp_show_sun     = isset($attributes['showSunItem']) ? (bool) $attributes['showSunItem'] : true;
$ezhp_show_mars    = isset($attributes['showMarsItem']) ? (bool) $attributes['showMarsItem'] : true;
$ezhp_show_mercury = isset($attributes['showMercuryItem']) ? (bool) $attributes['showMercuryItem'] : true;
$ezhp_show_jupiter = isset($attributes['showJupiterItem']) ? (bool) $attributes['showJupiterItem'] : true;
$ezhp_show_venus   = isset($attributes['showVenusItem']) ? (bool) $attributes['showVenusItem'] : true;
$ezhp_show_saturn  = isset($attributes['showSaturnItem']) ? (bool) $attributes['showSaturnItem'] : true;
$ezhp_show_neptune = isset($attributes['showNeptuneItem']) ? (bool) $attributes['showNeptuneItem'] : true;
$ezhp_show_uranus  = isset($attributes['showUranusItem']) ? (bool) $attributes['showUranusItem'] : true;
$ezhp_show_pluto   = isset($attributes['showPlutoItem']) ? (bool) $attributes['showPlutoItem'] : true;

// CTA attributes (sanitized)
$ezhp_cta1_enabled         = !empty($attributes['cta1Enabled']);
$ezhp_cta1_header_text     = sanitize_text_field($attributes['cta1HeaderText'] ?? '');
$ezhp_cta1_header_level    = sanitize_text_field($attributes['cta1HeaderLevel'] ?? 'h3');
$ezhp_cta1_text            = sanitize_text_field($attributes['cta1Text'] ?? '');
$ezhp_cta1_image_url       = esc_url($attributes['cta1ImageUrl'] ?? '');
$ezhp_cta1_image_alt       = sanitize_text_field($attributes['cta1ImageAlt'] ?? '');
$ezhp_cta1_url             = esc_url($attributes['cta1Url'] ?? '');
$ezhp_cta1_link_type       = sanitize_text_field($attributes['cta1LinkType'] ?? 'button');
$ezhp_cta1_link_text       = sanitize_text_field($attributes['cta1LinkText'] ?? '');
$ezhp_cta1_image_clickable = !empty($attributes['cta1ImageClickable']);
$ezhp_cta1_element_id      = sanitize_html_class($attributes['cta1ElementId'] ?? '');
$ezhp_cta1_alignment       = sanitize_text_field($attributes['cta1Alignment'] ?? 'center');

$ezhp_cta2_enabled         = !empty($attributes['cta2Enabled']);
$ezhp_cta2_header_text     = sanitize_text_field($attributes['cta2HeaderText'] ?? '');
$ezhp_cta2_header_level    = sanitize_text_field($attributes['cta2HeaderLevel'] ?? 'h3');
$ezhp_cta2_text            = sanitize_text_field($attributes['cta2Text'] ?? '');
$ezhp_cta2_image_url       = esc_url($attributes['cta2ImageUrl'] ?? '');
$ezhp_cta2_image_alt       = sanitize_text_field($attributes['cta2ImageAlt'] ?? '');
$ezhp_cta2_url             = esc_url($attributes['cta2Url'] ?? '');
$ezhp_cta2_link_type       = sanitize_text_field($attributes['cta2LinkType'] ?? 'button');
$ezhp_cta2_link_text       = sanitize_text_field($attributes['cta2LinkText'] ?? '');
$ezhp_cta2_image_clickable = !empty($attributes['cta2ImageClickable']);
$ezhp_cta2_element_id      = sanitize_html_class($attributes['cta2ElementId'] ?? '');
$ezhp_cta2_alignment       = sanitize_text_field($attributes['cta2Alignment'] ?? 'center');

$ezhp_cta3_enabled         = !empty($attributes['cta3Enabled']);
$ezhp_cta3_header_text     = sanitize_text_field($attributes['cta3HeaderText'] ?? '');
$ezhp_cta3_header_level    = sanitize_text_field($attributes['cta3HeaderLevel'] ?? 'h3');
$ezhp_cta3_text            = sanitize_text_field($attributes['cta3Text'] ?? '');
$ezhp_cta3_image_url       = esc_url($attributes['cta3ImageUrl'] ?? '');
$ezhp_cta3_image_alt       = sanitize_text_field($attributes['cta3ImageAlt'] ?? '');
$ezhp_cta3_url             = esc_url($attributes['cta3Url'] ?? '');
$ezhp_cta3_link_type       = sanitize_text_field($attributes['cta3LinkType'] ?? 'button');
$ezhp_cta3_link_text       = sanitize_text_field($attributes['cta3LinkText'] ?? '');
$ezhp_cta3_image_clickable = !empty($attributes['cta3ImageClickable']);
$ezhp_cta3_element_id      = sanitize_html_class($attributes['cta3ElementId'] ?? '');
$ezhp_cta3_alignment       = sanitize_text_field($attributes['cta3Alignment'] ?? 'center');

// Check if user can use premium code
$ezhp_is_premium = function_exists('ezhp_fs') && ezhp_fs()->can_use_premium_code__premium_only();

// Build cache key — include hero attributes to bust cache when changed
$ezhp_cache_key_parts = $ezhp_sign . '_' .
    $ezhp_horoscope_style . '_' .
    $ezhp_language . '_' .
    ($attributes['heroImageUrl'] ?? '') . '_' .
    ($attributes['heroImageDisplayMode'] ?? '') . '_' .
    ($attributes['heroImageAlignment'] ?? '') . '_' .
    ($attributes['heroImageTextWrap'] ?? '') . '_' .
    ($attributes['heroImageOverlayOpacity'] ?? '') . '_' .
    ($attributes['heroImageOverlayColor'] ?? '') . '_' .
    ($attributes['heroImageMaxWidth'] ?? '') . '_' .
    ($attributes['suppressHeading'] ?? '') . '_' .
    ($attributes['suppressPromotionalContent'] ?? '');

// Add section visibility to cache key
$ezhp_cache_key_parts .= '_' .
    ($ezhp_show_hero ? '1' : '0') . '_' .
    ($ezhp_show_guidance ? '1' : '0') . '_' .
    ($ezhp_show_advice ? '1' : '0') . '_' .
    ($ezhp_show_conclusion ? '1' : '0') . '_' .
    ($ezhp_show_moon ? '1' : '0') . '_' .
    ($ezhp_show_sun ? '1' : '0') . '_' .
    ($ezhp_show_mars ? '1' : '0') . '_' .
    ($ezhp_show_mercury ? '1' : '0') . '_' .
    ($ezhp_show_jupiter ? '1' : '0') . '_' .
    ($ezhp_show_venus ? '1' : '0') . '_' .
    ($ezhp_show_saturn ? '1' : '0') . '_' .
    ($ezhp_show_neptune ? '1' : '0') . '_' .
    ($ezhp_show_uranus ? '1' : '0') . '_' .
    ($ezhp_show_pluto ? '1' : '0');

// Add CTA settings to cache key for premium users
if ($ezhp_is_premium) {
    $ezhp_cache_key_parts .= '_' .
        ($ezhp_cta1_enabled ? '1' : '0') . '_' .
        $ezhp_cta1_header_text . '_' .
        $ezhp_cta1_header_level . '_' .
        $ezhp_cta1_text . '_' .
        $ezhp_cta1_image_url . '_' .
        $ezhp_cta1_url . '_' .
        $ezhp_cta1_link_type . '_' .
        $ezhp_cta1_link_text . '_' .
        ($ezhp_cta1_image_clickable ? '1' : '0') . '_' .
        $ezhp_cta1_element_id . '_' .
        $ezhp_cta1_alignment . '_' .
        ($ezhp_cta2_enabled ? '1' : '0') . '_' .
        $ezhp_cta2_header_text . '_' .
        $ezhp_cta2_header_level . '_' .
        $ezhp_cta2_text . '_' .
        $ezhp_cta2_image_url . '_' .
        $ezhp_cta2_url . '_' .
        $ezhp_cta2_link_type . '_' .
        $ezhp_cta2_link_text . '_' .
        ($ezhp_cta2_image_clickable ? '1' : '0') . '_' .
        $ezhp_cta2_element_id . '_' .
        $ezhp_cta2_alignment . '_' .
        ($ezhp_cta3_enabled ? '1' : '0') . '_' .
        $ezhp_cta3_header_text . '_' .
        $ezhp_cta3_header_level . '_' .
        $ezhp_cta3_text . '_' .
        $ezhp_cta3_image_url . '_' .
        $ezhp_cta3_url . '_' .
        $ezhp_cta3_link_type . '_' .
        $ezhp_cta3_link_text . '_' .
        ($ezhp_cta3_image_clickable ? '1' : '0') . '_' .
        $ezhp_cta3_element_id . '_' .
        $ezhp_cta3_alignment;
}

$ezhp_cache_key = 'ezhp_daily_' . md5($ezhp_cache_key_parts);

// Skip cache in REST context (block editor preview)
$ezhp_is_rest = defined('REST_REQUEST') && REST_REQUEST;

if (!$ezhp_is_rest) {
    $ezhp_cached = get_transient($ezhp_cache_key);
    if ($ezhp_cached && !str_contains($ezhp_cached, 'error')) {
        echo wp_kses_post($ezhp_cached);
        return;
    }
}

// Build API URL based on horoscope style
if ($ezhp_horoscope_style === 'professional') {
    $ezhp_api_url = sprintf(
        'https://api.ezhoroscope.com/api/DailyHoroscope/western-daily?zodiacSign=%s&apikey=%s&language=%s&style=professional',
        rawurlencode($ezhp_sign),
        rawurlencode($ezhp_api_key),
        rawurlencode($ezhp_language)
    );
} else {
    $ezhp_api_url = sprintf(
        'https://api.ezhoroscope.com/api/Horoscope/western-daily?zodiacSign=%s&apikey=%s&language=%s',
        rawurlencode($ezhp_sign),
        rawurlencode($ezhp_api_key),
        rawurlencode($ezhp_language)
    );
}

// Fetch API data
$ezhp_response = wp_remote_get($ezhp_api_url, [
    'timeout' => 20,
    'headers' => ['Accept' => 'application/json'],
]);

if (is_wp_error($ezhp_response)) {
    echo '<div class="ez-horoscope-block-error">' . esc_html__('Unable to retrieve horoscope at this time.', 'ez-horoscope') . '</div>';
    return;
}

$ezhp_body = wp_remote_retrieve_body($ezhp_response);
$ezhp_data = json_decode($ezhp_body, true);

// Graceful fallback if API response invalid
if (empty($ezhp_data) || !isset($ezhp_data['horoscopeText'])) {
    echo '<div class="ez-horoscope-block-error">' . esc_html__('No horoscope data available for today.', 'ez-horoscope') . '</div>';
    return;
}

// ———————————————————————————————
// HERO IMAGE CONFIG
// ———————————————————————————————
$ezhp_hero_url      = $attributes['heroImageUrl'] ?? '';
$ezhp_hero_mode     = $attributes['heroImageDisplayMode'] ?? 'background';
$ezhp_hero_align    = $attributes['heroImageAlignment'] ?? 'center';
$ezhp_hero_wrap     = $attributes['heroImageTextWrap'] ?? 'none';
$ezhp_hero_overlay  = $attributes['heroImageOverlay'] ?? 'none';
$ezhp_hero_alt      = esc_attr($attributes['heroImageAlt'] ?? '');
$ezhp_html          = $ezhp_data['horoscopeText'];

if (isset($ezhp_data['horoscopeText'])) {
    if ($ezhp_hero_mode === 'background') {
        // Build background CSS
        $ezhp_style  = "background-image:url('" . esc_url($ezhp_hero_url) . "');";
        $ezhp_style .= "background-size:cover;background-repeat:no-repeat;background-position:" . esc_attr($ezhp_hero_align) . ";";
        $ezhp_style .= "display:block;min-height:300px;position:relative;";

        // Inject style into .ez-hero
        $ezhp_html = preg_replace(
            '/(<section[^>]*class="[^"]*\bez-hero\b[^"]*"[^>]*)(>)/is',
            '$1 style="' . $ezhp_style . '"$2',
            $ezhp_html,
            1
        );

        // Overlay logic
        $ezhp_overlay_opacity = isset($attributes['heroImageOverlayOpacity'])
            ? floatval($attributes['heroImageOverlayOpacity'])
            : 50;
        $ezhp_overlay_opacity = max(0, min(100, $ezhp_overlay_opacity));

        if ($ezhp_overlay_opacity > 0) {
            $ezhp_opacity_css = $ezhp_overlay_opacity / 100;
            $ezhp_overlay_color = ($attributes['heroImageOverlayColor'] ?? 'black') === 'white'
                ? '255,255,255'
                : '0,0,0';
            $ezhp_overlay_class = ($attributes['heroImageOverlayColor'] ?? 'black') === 'white'
                ? 'ez-hero-overlay light'
                : 'ez-hero-overlay dark';
            $ezhp_overlay_style = sprintf(
                'background-color:rgba(%s,%.2f);opacity:1;position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none;',
                $ezhp_overlay_color,
                $ezhp_opacity_css
            );
            $ezhp_overlay_html = '<div class="' . esc_attr($ezhp_overlay_class) . '" style="' . esc_attr($ezhp_overlay_style) . '"></div>';

            // Insert overlay before content
            $ezhp_html = preg_replace(
                '/(<div\s+class="ez-hero-content">)/i',
                $ezhp_overlay_html . '$1',
                $ezhp_html,
                1
            );
        }
    } elseif ($ezhp_hero_mode === 'inline') {
        // Determine float/margin
        $ezhp_float_style = match ($ezhp_hero_wrap) {
            'left'  => 'float:left;margin:0 1rem 1rem 0;',
            'right' => 'float:right;margin:0 0 1rem 1rem;',
            default => 'display:block;margin:0 auto 1rem auto;',
        };
        $ezhp_hero_max_width = $attributes['heroImageMaxWidth'] ?? '40%';

        $ezhp_inline_html  = '<div class="ez-daily-inline-image" style="position:relative;">';
        $ezhp_inline_html .= '<img src="' . esc_url($ezhp_hero_url) . '" alt="' . $ezhp_hero_alt . '" ';
        $ezhp_inline_html .= 'style="' . esc_attr($ezhp_float_style) . 'max-width:' . esc_attr($ezhp_hero_max_width) . ';border-radius:8px;">';
        $ezhp_inline_html .= '<div class="ez-hero-overlay" style="position:absolute;inset:0;';
        $ezhp_inline_html .= 'background-color:rgba(' . (($attributes['heroImageOverlayColor'] ?? 'black') === 'white' ? '255,255,255' : '0,0,0') . ',' . (($attributes['heroImageOverlayOpacity'] ?? 50) / 100) . ');border-radius:8px;pointer-events:none;"></div>';
        $ezhp_inline_html .= '</div>';

        // Add marker class so CSS disables flex when inline mode active
        $ezhp_html = preg_replace(
            '/(<section[^>]*class="[^"]*\bez-hero\b[^"]*"[^>]*)(>)/i',
            '$1 has-inline-image$2',
            $ezhp_html,
            1
        );

        // Insert image into .ez-hero-text (poetic) or .ez-professional-intro (professional)
        $ezhp_inline_inserted = false;
        
        // Try poetic structure first (.ez-hero-text)
        if (preg_match('/\bez-hero-text\b/', $ezhp_html)) {
            $ezhp_html = preg_replace(
                '/(<div\s+class="[^"]*\bez-hero-text\b[^"]*">)/is',
                '$1' . $ezhp_inline_html,
                $ezhp_html,
                1
            );
            $ezhp_inline_inserted = true;
        }
        
        // Fallback to professional structure (.ez-professional-intro)
        if (!$ezhp_inline_inserted && preg_match('/\bez-professional-intro\b/', $ezhp_html)) {
            $ezhp_html = preg_replace(
                '/(<div\s+class="[^"]*\bez-professional-intro\b[^"]*">)/is',
                '$1' . $ezhp_inline_html,
                $ezhp_html,
                1
            );
        }
    }
}

// ———————————————————————————————
// H1 suppression
// ———————————————————————————————
if (!empty($attributes['suppressHeading']) && $attributes['suppressHeading']) {
    $ezhp_html = preg_replace('/<h1\b[^>]*>.*?<\/h1>/is', '', $ezhp_html);
}

// ———————————————————————————————
// Promotional content suppression (Premium only)
// ———————————————————————————————
if ($ezhp_is_premium) {
    if (!empty($attributes['suppressPromotionalContent']) && $attributes['suppressPromotionalContent']) {

        // Remove ALL links containing enneagramzoom FIRST (before anything else)
        $ezhp_html = preg_replace('/<a\s+[^>]*enneagramzoom[^>]*>.*?<\/a>/is', '', $ezhp_html);

        // Remove the ez-cta div by matching data-elementid
        $ezhp_html = preg_replace('/<div\s+[^>]*data-elementid\s*=\s*["\']enneagram-cta-top["\'][^>]*>.*?<\/div>/is', '', $ezhp_html);

        // Remove elements with data-elementid starting with "cb-"
        $ezhp_html = preg_replace('/<section\s+[^>]*data-elementid\s*=\s*["\']cb-[^"\']*["\'][^>]*>.*?<\/section>/is', '', $ezhp_html);
        $ezhp_html = preg_replace('/<div\s+[^>]*data-elementid\s*=\s*["\']cb-[^"\']*["\'][^>]*>.*?<\/div>/is', '', $ezhp_html);
        $ezhp_html = preg_replace('/<p\s+[^>]*data-elementid\s*=\s*["\']cb-[^"\']*["\'][^>]*>.*?<\/p>/is', '', $ezhp_html);
    }
}

// ———————————————————————————————
// Section and Planet visibility using DOMDocument
// ———————————————————————————————
$ezhp_needs_dom_processing = !$ezhp_show_hero || !$ezhp_show_guidance || !$ezhp_show_advice || 
    !$ezhp_show_conclusion || !$ezhp_show_moon || !$ezhp_show_sun || !$ezhp_show_mars || 
    !$ezhp_show_mercury || !$ezhp_show_jupiter || !$ezhp_show_venus || !$ezhp_show_saturn || 
    !$ezhp_show_neptune || !$ezhp_show_uranus || !$ezhp_show_pluto;

if ($ezhp_needs_dom_processing) {
    // Suppress DOMDocument warnings for HTML5 elements
    $ezhp_libxml_previous_state = libxml_use_internal_errors(true);
    
    $ezhp_dom = new DOMDocument();
    // Load HTML with UTF-8 encoding
    $ezhp_dom->loadHTML(
        '<?xml encoding="UTF-8">' . $ezhp_html,
        LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
    );
    
    // Clear any libxml errors
    libxml_clear_errors();
    libxml_use_internal_errors($ezhp_libxml_previous_state);
    
    $ezhp_xpath = new DOMXPath($ezhp_dom);
    
    // Array of elements to remove
    $ezhp_elements_to_remove = array();
    
    // ———————————————————————————————
    // Section visibility
    // ———————————————————————————————
    
    // Hide Hero Section
    if (!$ezhp_show_hero) {
        $ezhp_hero_sections = $ezhp_xpath->query('//section[contains(@class, "ez-hero")]');
        foreach ($ezhp_hero_sections as $ezhp_node) {
            $ezhp_elements_to_remove[] = $ezhp_node;
        }
    }
    
    // Hide Guidance Section
    if (!$ezhp_show_guidance) {
        $ezhp_guidance_node = $ezhp_dom->getElementById('guidance-section');
        if ($ezhp_guidance_node) {
            $ezhp_elements_to_remove[] = $ezhp_guidance_node;
        }
    }
    
    // Hide Advice Section
    if (!$ezhp_show_advice) {
        $ezhp_advice_node = $ezhp_dom->getElementById('advice-section');
        if ($ezhp_advice_node) {
            $ezhp_elements_to_remove[] = $ezhp_advice_node;
        }
    }
    
    // Hide Conclusion Section
    if (!$ezhp_show_conclusion) {
        $ezhp_conclusion_node = $ezhp_dom->getElementById('conclusion-section');
        if ($ezhp_conclusion_node) {
            $ezhp_elements_to_remove[] = $ezhp_conclusion_node;
        }
    }
    
    // ———————————————————————————————
    // Planet visibility
    // ———————————————————————————————
    
    // Hide Moon Item
    if (!$ezhp_show_moon) {
        $ezhp_moon_node = $ezhp_dom->getElementById('moon-item');
        if ($ezhp_moon_node) {
            $ezhp_elements_to_remove[] = $ezhp_moon_node;
        }
    }
    
    // Hide Sun Item
    if (!$ezhp_show_sun) {
        $ezhp_sun_node = $ezhp_dom->getElementById('sun-item');
        if ($ezhp_sun_node) {
            $ezhp_elements_to_remove[] = $ezhp_sun_node;
        }
    }
    
    // Hide Mars Item
    if (!$ezhp_show_mars) {
        $ezhp_mars_node = $ezhp_dom->getElementById('mars-item');
        if ($ezhp_mars_node) {
            $ezhp_elements_to_remove[] = $ezhp_mars_node;
        }
    }
    
    // Hide Mercury Item
    if (!$ezhp_show_mercury) {
        $ezhp_mercury_node = $ezhp_dom->getElementById('mercury-item');
        if ($ezhp_mercury_node) {
            $ezhp_elements_to_remove[] = $ezhp_mercury_node;
        }
    }
    
    // Hide Jupiter Item
    if (!$ezhp_show_jupiter) {
        $ezhp_jupiter_node = $ezhp_dom->getElementById('jupiter-item');
        if ($ezhp_jupiter_node) {
            $ezhp_elements_to_remove[] = $ezhp_jupiter_node;
        }
    }
    
    // Hide Venus Item
    if (!$ezhp_show_venus) {
        $ezhp_venus_node = $ezhp_dom->getElementById('venus-item');
        if ($ezhp_venus_node) {
            $ezhp_elements_to_remove[] = $ezhp_venus_node;
        }
    }
    
    // Hide Saturn Item
    if (!$ezhp_show_saturn) {
        $ezhp_saturn_node = $ezhp_dom->getElementById('saturn-item');
        if ($ezhp_saturn_node) {
            $ezhp_elements_to_remove[] = $ezhp_saturn_node;
        }
    }
    
    // Hide Neptune Item
    if (!$ezhp_show_neptune) {
        $ezhp_neptune_node = $ezhp_dom->getElementById('neptune-item');
        if ($ezhp_neptune_node) {
            $ezhp_elements_to_remove[] = $ezhp_neptune_node;
        }
    }
    
    // Hide Uranus Item
    if (!$ezhp_show_uranus) {
        $ezhp_uranus_node = $ezhp_dom->getElementById('uranus-item');
        if ($ezhp_uranus_node) {
            $ezhp_elements_to_remove[] = $ezhp_uranus_node;
        }
    }
    
    // Hide Pluto Item
    if (!$ezhp_show_pluto) {
        $ezhp_pluto_node = $ezhp_dom->getElementById('pluto-item');
        if ($ezhp_pluto_node) {
            $ezhp_elements_to_remove[] = $ezhp_pluto_node;
        }
    }
    
    // ———————————————————————————————
    // Check if all planets hidden - remove flexbox section
    // ———————————————————————————————
    $ezhp_all_planets_hidden = !$ezhp_show_moon && !$ezhp_show_sun && !$ezhp_show_mars &&
        !$ezhp_show_mercury && !$ezhp_show_jupiter && !$ezhp_show_venus &&
        !$ezhp_show_saturn && !$ezhp_show_neptune && !$ezhp_show_uranus && !$ezhp_show_pluto;

    if ($ezhp_all_planets_hidden) {
        $ezhp_flexbox_sections = $ezhp_xpath->query('//section[contains(@class, "eztype-flexbox-section")]');
        foreach ($ezhp_flexbox_sections as $ezhp_node) {
            $ezhp_elements_to_remove[] = $ezhp_node;
        }
    }
    
    // ———————————————————————————————
    // Remove all collected elements
    // ———————————————————————————————
    foreach ($ezhp_elements_to_remove as $ezhp_element) {
        if ($ezhp_element && $ezhp_element->parentNode) {
            $ezhp_element->parentNode->removeChild($ezhp_element);
        }
    }
    
    // Get the processed HTML back
    $ezhp_html = $ezhp_dom->saveHTML();
    
    // Remove the XML declaration we added
    $ezhp_html = preg_replace('/^<\?xml encoding="UTF-8"\?>\s*/i', '', $ezhp_html);
}

// ———————————————————————————————
// Build CTA data attributes
// - Editor preview (REST): All users (so they can preview before subscribing)
// - Frontend: Premium users only
// ———————————————————————————————
$ezhp_cta_data_attrs = '';
$ezhp_should_output_cta = false;

// Editor preview: All users can see CTAs
if ($ezhp_is_rest) {
    $ezhp_should_output_cta = true;
}

// Frontend: Only premium users (this block will be stripped from free version)
if ( function_exists('ezhp_fs') && ezhp_fs()->can_use_premium_code__premium_only() ) {
    $ezhp_should_output_cta = true;
}

if ($ezhp_should_output_cta) {
    // CTA 1 data attributes
    if ($ezhp_cta1_enabled) {
        $ezhp_cta_data_attrs .= ' data-cta1-enabled="1"';
        $ezhp_cta_data_attrs .= ' data-cta1-header-text="' . esc_attr($ezhp_cta1_header_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-header-level="' . esc_attr($ezhp_cta1_header_level) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-text="' . esc_attr($ezhp_cta1_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-image-url="' . esc_attr($ezhp_cta1_image_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-image-alt="' . esc_attr($ezhp_cta1_image_alt) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-url="' . esc_attr($ezhp_cta1_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-link-type="' . esc_attr($ezhp_cta1_link_type) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-link-text="' . esc_attr($ezhp_cta1_link_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-image-clickable="' . ($ezhp_cta1_image_clickable ? '1' : '0') . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-element-id="' . esc_attr($ezhp_cta1_element_id) . '"';
        $ezhp_cta_data_attrs .= ' data-cta1-alignment="' . esc_attr($ezhp_cta1_alignment) . '"';
    }

    // CTA 2 data attributes
    if ($ezhp_cta2_enabled) {
        $ezhp_cta_data_attrs .= ' data-cta2-enabled="1"';
        $ezhp_cta_data_attrs .= ' data-cta2-header-text="' . esc_attr($ezhp_cta2_header_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-header-level="' . esc_attr($ezhp_cta2_header_level) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-text="' . esc_attr($ezhp_cta2_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-image-url="' . esc_attr($ezhp_cta2_image_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-image-alt="' . esc_attr($ezhp_cta2_image_alt) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-url="' . esc_attr($ezhp_cta2_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-link-type="' . esc_attr($ezhp_cta2_link_type) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-link-text="' . esc_attr($ezhp_cta2_link_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-image-clickable="' . ($ezhp_cta2_image_clickable ? '1' : '0') . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-element-id="' . esc_attr($ezhp_cta2_element_id) . '"';
        $ezhp_cta_data_attrs .= ' data-cta2-alignment="' . esc_attr($ezhp_cta2_alignment) . '"';
    }

    // CTA 3 data attributes
    if ($ezhp_cta3_enabled) {
        $ezhp_cta_data_attrs .= ' data-cta3-enabled="1"';
        $ezhp_cta_data_attrs .= ' data-cta3-header-text="' . esc_attr($ezhp_cta3_header_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-header-level="' . esc_attr($ezhp_cta3_header_level) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-text="' . esc_attr($ezhp_cta3_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-image-url="' . esc_attr($ezhp_cta3_image_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-image-alt="' . esc_attr($ezhp_cta3_image_alt) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-url="' . esc_attr($ezhp_cta3_url) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-link-type="' . esc_attr($ezhp_cta3_link_type) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-link-text="' . esc_attr($ezhp_cta3_link_text) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-image-clickable="' . ($ezhp_cta3_image_clickable ? '1' : '0') . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-element-id="' . esc_attr($ezhp_cta3_element_id) . '"';
        $ezhp_cta_data_attrs .= ' data-cta3-alignment="' . esc_attr($ezhp_cta3_alignment) . '"';
    }
}

// ———————————————————————————————
// Wrap & output safely
// ———————————————————————————————
$ezhp_dir_attr = $ezhp_is_rtl ? ' dir="rtl"' : '';
$ezhp_output  = '<div class="ez-horoscope-block"' . $ezhp_dir_attr . $ezhp_cta_data_attrs . '>';
$ezhp_output .= $ezhp_html;
$ezhp_output .= '</div>';

// Only cache successful, non-error responses (skip in REST context)
if (!$ezhp_is_rest && !empty($ezhp_html) && !str_contains($ezhp_html, 'error')) {
    set_transient($ezhp_cache_key, $ezhp_output, HOUR_IN_SECONDS);
}

echo wp_kses_post($ezhp_output);