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

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

$ezhp_sign     = sanitize_text_field($attributes['sign'] ?? 'aries');
$ezhp_section  = sanitize_text_field($attributes['section'] ?? 'guidance');
$ezhp_language = sanitize_text_field($attributes['language'] ?? 'en');
$ezhp_api_key  = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

// Cache key WITHOUT overlay settings
$ezhp_cache_key = 'ezhp_daily_section_' . md5(
    $ezhp_sign . '_' .
    $ezhp_section . '_' .
    $ezhp_language . '_' .
    ($attributes['heroImageUrl'] ?? '') . '_' .
    ($attributes['heroImageTextWrap'] ?? '') . '_' .
    ($attributes['heroImageMaxWidth'] ?? '')
);

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

$ezhp_api_url = sprintf(
    'https://api.ezhoroscope.com/api/Horoscope/western-section?zodiacSign=%s&content=%s&apikey=%s&language=%s',
    rawurlencode($ezhp_sign),
    rawurlencode($ezhp_section),
    rawurlencode($ezhp_api_key),
    rawurlencode($ezhp_language)
);

$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">Unable to retrieve horoscope section.</div>';
    return;
}

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

if (empty($ezhp_data) || empty($ezhp_data['sectionHtml'])) {
    echo '<div class="ez-horoscope-block-error">No horoscope section available.</div>';
    return;
}

$ezhp_html = $ezhp_data['sectionHtml'];

// Strip eztype background divs completely (editor-safe)
$ezhp_html = preg_replace(
    '/<div\s+class="eztype-flexbox-background[^"]*"[^>]*><\/div>/i',
    '',
    $ezhp_html
);

// Convert Flexbox Item → direct content container
$ezhp_html = preg_replace(
    '/<div\s+class="eztype-flexbox-item"[^>]*>\s*<div\s+class="eztype-flexbox-content"[^>]*>(.*?)<\/div>\s*<\/div>/is',
    '<div class="eztype-flexbox-content">$1</div>',
    $ezhp_html
);

// Wrap HTML
$ezhp_html = '
<section class="ez-hero">
    <div class="ez-hero-content">
        <div class="ez-hero-text">
            ' . $ezhp_html . '
        </div>
    </div>
</section>
';

// IMAGE (INLINE ONLY)
$ezhp_hero_url  = $attributes['heroImageUrl'] ?? '';
$ezhp_hero_wrap = $attributes['heroImageTextWrap'] ?? 'none';
$ezhp_hero_alt  = esc_attr($attributes['heroImageAlt'] ?? '');

if (!empty($ezhp_hero_url)) {

    $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_inline_image  = '<img src="' . esc_url($ezhp_hero_url) . '" alt="' . $ezhp_hero_alt . '" ';
    $ezhp_inline_image .= 'style="' . esc_attr($ezhp_float_style) . 'max-width:' . esc_attr($attributes['heroImageMaxWidth'] ?? '40%') . ';border-radius:8px;">';

    $ezhp_html = preg_replace(
        '/(<div\s+class="ez-hero-text">)/i',
        '$1' . $ezhp_inline_image,
        $ezhp_html,
        1
    );
}

$ezhp_output  = '<div class="ez-horoscope-block">';
$ezhp_output .= $ezhp_html;
$ezhp_output .= '</div>';

set_transient($ezhp_cache_key, $ezhp_output, HOUR_IN_SECONDS);

echo wp_kses_post($ezhp_output);
