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

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

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

// RTL language detection
$ezhp_rtl_languages = ['ar', 'he', 'fa', 'ur', 'ps', 'sd', 'yi', 'ku', 'dv', 'ug', 'arc', 'azb', 'ckb', 'mzn', 'pnb', 'ks', 'glk', 'bal', 'bqi', 'luz', 'gbz', 'khw', 'lrc', 'prd', 'sdh', 'skr'];
$ezhp_lang_base = strtolower(explode('-', $ezhp_language)[0]);
$ezhp_is_rtl = in_array($ezhp_lang_base, $ezhp_rtl_languages, true);

// Build API URL for professional weekly horoscope
$ezhp_api_url = sprintf(
    'https://api.ezhoroscope.com/api/WeeklyHoroscope/western-weekly?zodiacSign=%s&apikey=%s&language=%s&style=professional',
    rawurlencode($ezhp_sign),
    rawurlencode($ezhp_api_key),
    rawurlencode($ezhp_language)
);

// Build unique transient key
$ezhp_cache_key = 'ezhp_weekly_pro_' . md5(
    $ezhp_sign . '_' .
    $ezhp_language
);

// Try to load cached data first
$ezhp_cached_body = get_transient($ezhp_cache_key);
$ezhp_body = false;

if (false === $ezhp_cached_body) {
    // Fetch fresh data from API
    $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') .
            ' Debug: ' . esc_html($ezhp_response->get_error_message()) .
            '</div>';
        return;
    }

    $ezhp_body = wp_remote_retrieve_body($ezhp_response);

    // Only cache if body doesn't contain "error"
    if (stripos($ezhp_body, 'error') === false && ! empty($ezhp_body)) {
        set_transient($ezhp_cache_key, $ezhp_body, HOUR_IN_SECONDS);
    }
} else {
    // Use cached response
    $ezhp_body = $ezhp_cached_body;
}

// Ensure $ezhp_body exists and is decoded properly
if (empty($ezhp_body)) {
    echo '<div class="ez-horoscope-block-error">' .
        esc_html__('Empty response from horoscope API.', 'ez-horoscope') .
        '</div>';
    return;
}

$ezhp_data = json_decode($ezhp_body, true);

// Validate decoded structure
if (! is_array($ezhp_data) || ! isset($ezhp_data['horoscopeText']) || empty($ezhp_data['horoscopeText'])) {
    // Delete bad cache so next request fetches fresh data
    delete_transient($ezhp_cache_key);

    echo '<div class="ez-horoscope-block-error">' .
        esc_html__('Unable to decode horoscope data. Retrying later.', 'ez-horoscope') .
        '</div>';
    return;
}

// ============================================================================
// HERO IMAGE INJECTION
// ============================================================================

// Build default hero image URL based on zodiac sign
$ezhp_zodiac_images_url = plugins_url('assets/images/zodiac/', dirname(dirname(dirname(__FILE__))));
$ezhp_default_hero_url = $ezhp_zodiac_images_url . 'ez-' . $ezhp_sign . '.jpg';

// Inject hero image configuration
$ezhp_hero_url      = !empty($attributes['heroImageUrl']) ? $attributes['heroImageUrl'] : $ezhp_default_hero_url;
$ezhp_hero_mode     = $attributes['heroImageDisplayMode'] ?? 'inline';
$ezhp_hero_align    = $attributes['heroImageAlignment'] ?? 'center';
$ezhp_hero_wrap     = $attributes['heroImageTextWrap'] ?? 'none';
$ezhp_hero_alt      = esc_attr($attributes['heroImageAlt'] ?? '');

if (!empty($ezhp_hero_url) && isset($ezhp_data['horoscopeText'])) {

    $ezhp_html = $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 inline background CSS into existing <section class="ez-horoscope-weekly-professional ez-hero">
        $ezhp_html = preg_replace(
            '/(<section[^>]*class="[^"]*ez-horoscope-weekly-professional[^"]*ez-hero[^"]*"[^>]*)(>)/is',
            '$1 style="' . $ezhp_style . '"$2',
            $ezhp_html,
            1
        );

        // Add overlay div
        $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;

            // Determine overlay tint (black or white)
            $ezhp_overlay_color = (isset($attributes['heroImageOverlayColor']) && $attributes['heroImageOverlayColor'] === 'white')
                ? '255,255,255'
                : '0,0,0';

            // Build complete overlay style
            $ezhp_overlay_class = ($attributes['heroImageOverlayColor'] === 'white') ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark';
            $ezhp_overlay_style = sprintf('background-color:rgba(%s,%.2f); opacity:1;', $ezhp_overlay_color, $ezhp_opacity_css);
            $ezhp_overlay_style .= ' position:absolute; top:0; left:0; right:0; bottom:0; pointer-events:none; z-index:1;';

            // Build overlay div
            $ezhp_overlay_html = '<div class="' . esc_attr($ezhp_overlay_class) . '" style="' . $ezhp_overlay_style . '"></div>';

            // Inject overlay div before the content container
            $ezhp_html = preg_replace(
                '/(<div\s+class="ez-hero-content">)/i',
                $ezhp_overlay_html . '$1',
                $ezhp_html,
                1
            );
        }
    } elseif ($ezhp_hero_mode === 'inline') {
        // Insert inline image into .ez-week-character
        $ezhp_float_style = '';
        if ($ezhp_hero_wrap === 'left') {
            $ezhp_float_style = $ezhp_is_rtl
                ? 'float:right; margin:0 0 1rem 1rem;'
                : 'float:left; margin:0 1rem 1rem 0;';
        } elseif ($ezhp_hero_wrap === 'right') {
            $ezhp_float_style = $ezhp_is_rtl
                ? 'float:left; margin:0 1rem 1rem 0;'
                : 'float:right; margin:0 0 1rem 1rem;';
        } else {
            // none = centered
            $ezhp_float_style = 'display:block; margin:0 auto 1rem auto;';
        }

        $ezhp_hero_max_width = $attributes['heroImageMaxWidth'] ?? '40%';

        // Build inline image with optional overlay
        $ezhp_inline_html = '<div class="ez-weekly-inline-image" style="position:relative; ' . $ezhp_float_style . ' max-width:' . esc_attr($ezhp_hero_max_width) . ';">';
        $ezhp_inline_html .= '<img src="' . esc_url($ezhp_hero_url) . '" alt="' . $ezhp_hero_alt . '" style="width:100%; height:auto; border-radius:6px; display:block;">';

        // Add overlay if opacity > 0
        $ezhp_hero_overlay_opacity = isset($attributes['heroImageOverlayOpacity']) ? floatval($attributes['heroImageOverlayOpacity']) : 50;
        if ($ezhp_hero_overlay_opacity > 0) {
            $ezhp_opacity_css = $ezhp_hero_overlay_opacity / 100;
            $ezhp_overlay_color = (isset($attributes['heroImageOverlayColor']) && $attributes['heroImageOverlayColor'] === 'white') ? '255,255,255' : '0,0,0';
            $ezhp_overlay_class = ($attributes['heroImageOverlayColor'] === 'white') ? 'ez-weekly-overlay light' : 'ez-weekly-overlay dark';
            $ezhp_inline_html .= sprintf(
                '<div class="%s" style="position:absolute; top:0; left:0; right:0; bottom:0; background-color:rgba(%s,%.2f); border-radius:6px; pointer-events:none;"></div>',
                esc_attr($ezhp_overlay_class),
                $ezhp_overlay_color,
                $ezhp_opacity_css
            );
        }

        $ezhp_inline_html .= '</div>';

        // Insert into .ez-week-character (the intro section)
        $ezhp_html = preg_replace(
            '/(<div\s+class="ez-week-character">)/i',
            '$1' . $ezhp_inline_html,
            $ezhp_html,
            1
        );
    }

    $ezhp_data['horoscopeText'] = $ezhp_html;
}

// ============================================================================
// CALL TO ACTION INJECTION
// Uses placeholder slots: cta-slot-1, cta-slot-2, cta-slot-3
// ============================================================================

$ezhp_cta_placement = $attributes['ctaPlacement'] ?? 'none';

// Determine if we should render the CTA
$ezhp_is_editor_preview = defined('REST_REQUEST') && REST_REQUEST;
$ezhp_render_cta = false;

// Always show in editor preview for all users
if ($ezhp_is_editor_preview) {
    $ezhp_render_cta = true;
}

// This block will be stripped from free version during build
if ( function_exists( 'ezhp_fs' ) && ezhp_fs()->can_use_premium_code__premium_only() ) {
    // Premium users see it on frontend too
    $ezhp_render_cta = true;
}

if ($ezhp_render_cta && $ezhp_cta_placement !== 'none' && isset($ezhp_data['horoscopeText'])) {
    $ezhp_cta_headline = sanitize_text_field($attributes['ctaHeadline'] ?? '');
    $ezhp_cta_heading_level = in_array($attributes['ctaHeadingLevel'] ?? 'h3', ['h2', 'h3', 'h4'], true) 
        ? $attributes['ctaHeadingLevel'] 
        : 'h3';
    $ezhp_cta_text = sanitize_textarea_field($attributes['ctaText'] ?? '');
    $ezhp_cta_button_text = sanitize_text_field($attributes['ctaButtonText'] ?? '');
    $ezhp_cta_button_url = esc_url($attributes['ctaButtonUrl'] ?? '');
    $ezhp_cta_image_url = esc_url($attributes['ctaImageUrl'] ?? '');
    $ezhp_cta_image_alt = esc_attr($attributes['ctaImageAlt'] ?? '');
    $ezhp_cta_image_clickable = !empty($attributes['ctaImageClickable']);
    $ezhp_cta_image_max_width = esc_attr($attributes['ctaImageMaxWidth'] ?? '100%');
    $ezhp_cta_bg_color = sanitize_hex_color($attributes['ctaBackgroundColor'] ?? '');
    $ezhp_cta_bg_transparent = !empty($attributes['ctaBackgroundTransparent']);
    $ezhp_cta_button_color = sanitize_hex_color($attributes['ctaButtonColor'] ?? '');

    // Build CTA HTML with optional custom background
    $ezhp_cta_style = '';
    $ezhp_cta_class = 'ez-weekly-cta';
    if ($ezhp_cta_bg_transparent) {
        $ezhp_cta_style = ' style="background: transparent; box-shadow: none; border: none;"';
        $ezhp_cta_class .= ' ez-weekly-cta-transparent';
    } elseif (!empty($ezhp_cta_bg_color)) {
        $ezhp_cta_style = sprintf(' style="background: %s;"', $ezhp_cta_bg_color);
    }
    $ezhp_cta_html = '<div class="' . $ezhp_cta_class . '"' . $ezhp_cta_style . '>';

    // Headline
    if (!empty($ezhp_cta_headline)) {
        $ezhp_cta_html .= sprintf(
            '<%1$s class="ez-weekly-cta-headline">%2$s</%1$s>',
            $ezhp_cta_heading_level,
            esc_html($ezhp_cta_headline)
        );
    }

    // Image (above text/button)
    if (!empty($ezhp_cta_image_url)) {
        $ezhp_cta_img_tag = sprintf(
            '<img src="%s" alt="%s" class="ez-weekly-cta-image" style="max-width: %s;">',
            $ezhp_cta_image_url,
            $ezhp_cta_image_alt,
            $ezhp_cta_image_max_width
        );

        if ($ezhp_cta_image_clickable && !empty($ezhp_cta_button_url)) {
            $ezhp_cta_html .= sprintf(
                '<a href="%s" class="ez-weekly-cta-image-link">%s</a>',
                $ezhp_cta_button_url,
                $ezhp_cta_img_tag
            );
        } else {
            $ezhp_cta_html .= $ezhp_cta_img_tag;
        }
    }

    // Description text
    if (!empty($ezhp_cta_text)) {
        $ezhp_cta_html .= sprintf(
            '<p class="ez-weekly-cta-text">%s</p>',
            esc_html($ezhp_cta_text)
        );
    }

    // Button
    if (!empty($ezhp_cta_button_text) && !empty($ezhp_cta_button_url)) {
        $ezhp_button_style = '';
        if (!empty($ezhp_cta_button_color)) {
            $ezhp_button_style = sprintf(' style="background: %s;"', $ezhp_cta_button_color);
        }
        $ezhp_cta_html .= sprintf(
            '<a href="%s" class="ez-weekly-cta-button"%s>%s</a>',
            $ezhp_cta_button_url,
            $ezhp_button_style,
            esc_html($ezhp_cta_button_text)
        );
    }

    $ezhp_cta_html .= '</div>';

    // Map placement to slot ID
    $ezhp_cta_slot_map = [
        'after-trigger'      => 'cta-slot-1',
        'after-life-sectors' => 'cta-slot-2',
        'after-limitations'  => 'cta-slot-3',
    ];

    $ezhp_target_slot = $ezhp_cta_slot_map[$ezhp_cta_placement] ?? '';

    if (!empty($ezhp_target_slot)) {
        // Replace the placeholder div with the CTA HTML
        $ezhp_data['horoscopeText'] = str_replace(
            '<div data-elementid="' . $ezhp_target_slot . '"></div>',
            $ezhp_cta_html,
            $ezhp_data['horoscopeText']
        );
    }
}

// Remove any unused CTA placeholder divs
if (isset($ezhp_data['horoscopeText'])) {
    $ezhp_data['horoscopeText'] = preg_replace(
        '/<div data-elementid="cta-slot-[0-9]+"><\/div>/',
        '',
        $ezhp_data['horoscopeText']
    );
}

if (isset($ezhp_data['horoscopeText']) && ! empty($ezhp_data['horoscopeText'])) {
    $ezhp_horoscope_text = $ezhp_data['horoscopeText'];
} else {
    $ezhp_horoscope_text = esc_html__('No horoscope data available for this week.', 'ez-horoscope');
}

// Build block HTML with RTL support
$ezhp_dir_attr = $ezhp_is_rtl ? ' dir="rtl"' : '';
$ezhp_rtl_class = $ezhp_is_rtl ? ' ez-horoscope-rtl' : '';

$ezhp_output  = '<div class="ez-horoscope-block ez-horoscope-professional-weekly' . $ezhp_rtl_class . '"' . $ezhp_dir_attr . ' data-language="' . esc_attr($ezhp_language) . '">';
$ezhp_output .= $ezhp_horoscope_text;
$ezhp_output .= '</div>';

// Output safely — PHPCS compliant.
echo wp_kses_post($ezhp_output);
