<?php
/**
 * EZ Horoscope Summaries Block - Server-side Render (AJAX Version)
 * 
 * This file outputs a placeholder and loads content via AJAX to bypass page caching.
 * The REST endpoint is registered in includes/summaries-rest.php
 */
defined('ABSPATH') || exit;

if (defined('REST_REQUEST') && REST_REQUEST) {
    // We're in the editor - render content directly
    $ezhp_html = ezhp_build_summaries_html($attributes);
    echo wp_kses_post($ezhp_html);
    return;
}

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

/*
|--------------------------------------------------------------------------
| RTL Languages
|--------------------------------------------------------------------------
*/
$ezhp_rtl_languages = ['ar', 'he', 'fa', 'ur'];

/*
|--------------------------------------------------------------------------
| "Loading..." Translations (45 languages)
|--------------------------------------------------------------------------
*/
$ezhp_loading_translations = [
    'en' => 'Loading horoscopes...',
    'fr' => 'Chargement des horoscopes...',
    'it' => 'Caricamento oroscopi...',
    'de' => 'Horoskope werden geladen...',
    'es' => 'Cargando horóscopos...',
    'ar' => 'جارٍ تحميل الأبراج...',
    'bn' => 'রাশিফল লোড হচ্ছে...',
    'cs' => 'Načítání horoskopů...',
    'da' => 'Indlæser horoskoper...',
    'el' => 'Φόρτωση ωροσκοπίων...',
    'et' => 'Horoskoopide laadimine...',
    'eu' => 'Horoskopoak kargatzen...',
    'fa' => 'در حال بارگذاری فال...',
    'fi' => 'Ladataan horoskooppeja...',
    'he' => 'טוען הורוסקופים...',
    'hi' => 'राशिफल लोड हो रहा है...',
    'hu' => 'Horoszkópok betöltése...',
    'id' => 'Memuat horoskop...',
    'ja' => '星占いを読み込み中...',
    'ko' => '운세 로딩 중...',
    'lt' => 'Kraunami horoskopai...',
    'lv' => 'Ielādē horoskopus...',
    'ms' => 'Memuatkan horoskop...',
    'nb' => 'Laster horoskoper...',
    'nl' => 'Horoscopen laden...',
    'pl' => 'Ładowanie horoskopów...',
    'pt' => 'Carregando horóscopos...',
    'ro' => 'Se încarcă horoscopul...',
    'ru' => 'Загрузка гороскопов...',
    'sq' => 'Duke ngarkuar horoskopet...',
    'sv' => 'Laddar horoskop...',
    'th' => 'กำลังโหลดดวง...',
    'tl' => 'Naglo-load ng horoscope...',
    'tr' => 'Burçlar yükleniyor...',
    'uk' => 'Завантаження гороскопів...',
    'ur' => 'زائچہ لوڈ ہو رہا ہے...',
    'eo' => 'Ŝargante horoskopojn...',
    'ga' => 'Ag lódáil horoscopes...',
    'gl' => 'Cargando horóscopos...',
    'az' => 'Bürclər yüklənir...',
    'bg' => 'Зареждане на хороскопи...',
    'ca' => 'Carregant horòscops...',
    'sk' => 'Načítavanie horoskopov...',
    'sl' => 'Nalaganje horoskopov...',
    'zh' => '正在加载星座运势...',
];

/*
|--------------------------------------------------------------------------
| "Unable to load" Error Translations (45 languages)
|--------------------------------------------------------------------------
*/
$ezhp_error_translations = [
    'en' => 'Unable to load horoscope summaries.',
    'fr' => 'Impossible de charger les horoscopes.',
    'it' => 'Impossibile caricare gli oroscopi.',
    'de' => 'Horoskope konnten nicht geladen werden.',
    'es' => 'No se pudieron cargar los horóscopos.',
    'ar' => 'تعذر تحميل الأبراج.',
    'bn' => 'রাশিফল লোড করা যায়নি।',
    'cs' => 'Nelze načíst horoskopy.',
    'da' => 'Kunne ikke indlæse horoskoper.',
    'el' => 'Αδυναμία φόρτωσης ωροσκοπίων.',
    'et' => 'Horoskoope ei õnnestunud laadida.',
    'eu' => 'Ezin izan dira horoskopoak kargatu.',
    'fa' => 'بارگذاری فال امکان‌پذیر نیست.',
    'fi' => 'Horoskooppien lataus epäonnistui.',
    'he' => 'לא ניתן לטעון הורוסקופים.',
    'hi' => 'राशिफल लोड नहीं हो सका।',
    'hu' => 'Nem sikerült betölteni a horoszkópokat.',
    'id' => 'Tidak dapat memuat horoskop.',
    'ja' => '星占いを読み込めませんでした。',
    'ko' => '운세를 불러올 수 없습니다.',
    'lt' => 'Nepavyko įkelti horoskopų.',
    'lv' => 'Neizdevās ielādēt horoskopus.',
    'ms' => 'Tidak dapat memuatkan horoskop.',
    'nb' => 'Kunne ikke laste horoskoper.',
    'nl' => 'Kan horoscopen niet laden.',
    'pl' => 'Nie można załadować horoskopów.',
    'pt' => 'Não foi possível carregar os horóscopos.',
    'ro' => 'Nu s-a putut încărca horoscopul.',
    'ru' => 'Не удалось загрузить гороскопы.',
    'sq' => 'Nuk mund të ngarkoheshin horoskopet.',
    'sv' => 'Kunde inte ladda horoskop.',
    'th' => 'ไม่สามารถโหลดดวงได้',
    'tl' => 'Hindi ma-load ang horoscope.',
    'tr' => 'Burçlar yüklenemedi.',
    'uk' => 'Не вдалося завантажити гороскопи.',
    'ur' => 'زائچہ لوڈ نہیں ہو سکا۔',
    'eo' => 'Ne eblis ŝargi horoskopojn.',
    'ga' => 'Níorbh fhéidir horoscopes a lódáil.',
    'gl' => 'Non se puideron cargar os horóscopos.',
    'az' => 'Bürclər yüklənə bilmədi.',
    'bg' => 'Хороскопите не можаха да бъдат заредени.',
    'ca' => 'No s\'han pogut carregar els horòscops.',
    'sk' => 'Nepodarilo sa načítať horoskopy.',
    'sl' => 'Horoskopov ni bilo mogoče naložiti.',
    'zh' => '无法加载星座运势。',
];

/*
|--------------------------------------------------------------------------
| Prepare attributes for AJAX
|--------------------------------------------------------------------------
*/
$ezhp_language     = sanitize_text_field($attributes['language'] ?? 'en');
$ezhp_is_rtl       = in_array($ezhp_language, $ezhp_rtl_languages, true);
$ezhp_loading_text = $ezhp_loading_translations[$ezhp_language] ?? $ezhp_loading_translations['en'];
$ezhp_error_text   = $ezhp_error_translations[$ezhp_language] ?? $ezhp_error_translations['en'];

// Generate unique ID for this block instance
$ezhp_unique_id = 'ezhp-summaries-' . wp_unique_id();

// Prepare attributes for JavaScript
$ezhp_ajax_attributes = [
    'language'               => $attributes['language'] ?? 'en',
    'showHeader'             => $attributes['showHeader'] ?? true,
    'imageAries'             => $attributes['imageAries'] ?? '',
    'imageTaurus'            => $attributes['imageTaurus'] ?? '',
    'imageGemini'            => $attributes['imageGemini'] ?? '',
    'imageCancer'            => $attributes['imageCancer'] ?? '',
    'imageLeo'               => $attributes['imageLeo'] ?? '',
    'imageVirgo'             => $attributes['imageVirgo'] ?? '',
    'imageLibra'             => $attributes['imageLibra'] ?? '',
    'imageScorpio'           => $attributes['imageScorpio'] ?? '',
    'imageSagittarius'       => $attributes['imageSagittarius'] ?? '',
    'imageCapricorn'         => $attributes['imageCapricorn'] ?? '',
    'imageAquarius'          => $attributes['imageAquarius'] ?? '',
    'imagePisces'            => $attributes['imagePisces'] ?? '',
    'linkAries'              => $attributes['linkAries'] ?? '',
    'linkTaurus'             => $attributes['linkTaurus'] ?? '',
    'linkGemini'             => $attributes['linkGemini'] ?? '',
    'linkCancer'             => $attributes['linkCancer'] ?? '',
    'linkLeo'                => $attributes['linkLeo'] ?? '',
    'linkVirgo'              => $attributes['linkVirgo'] ?? '',
    'linkLibra'              => $attributes['linkLibra'] ?? '',
    'linkScorpio'            => $attributes['linkScorpio'] ?? '',
    'linkSagittarius'        => $attributes['linkSagittarius'] ?? '',
    'linkCapricorn'          => $attributes['linkCapricorn'] ?? '',
    'linkAquarius'           => $attributes['linkAquarius'] ?? '',
    'linkPisces'             => $attributes['linkPisces'] ?? '',
    'heroImageDisplayMode'   => $attributes['heroImageDisplayMode'] ?? 'inline',
    'heroImageTextWrap'      => $attributes['heroImageTextWrap'] ?? 'none',
    'heroImageAlignment'     => $attributes['heroImageAlignment'] ?? 'center',
    'heroImageOverlayOpacity'=> $attributes['heroImageOverlayOpacity'] ?? 50,
    'heroImageOverlayColor'  => $attributes['heroImageOverlayColor'] ?? 'black',
    'heroImageMaxWidth'      => $attributes['heroImageMaxWidth'] ?? '40%',
];

// Check if any images use background mode
$ezhp_has_bg_images = false;
$ezhp_hero_mode = $attributes['heroImageDisplayMode'] ?? 'inline';
if ($ezhp_hero_mode === 'background') {
    $ezhp_image_keys = ['imageAries', 'imageTaurus', 'imageGemini', 'imageCancer', 'imageLeo', 'imageVirgo', 
                        'imageLibra', 'imageScorpio', 'imageSagittarius', 'imageCapricorn', 'imageAquarius', 'imagePisces'];
    foreach ($ezhp_image_keys as $ezhp_key) {
        if (!empty($attributes[$ezhp_key])) {
            $ezhp_has_bg_images = true;
            break;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Enqueue AJAX Script and Pass Data
|--------------------------------------------------------------------------
*/
$ezhp_script_handle = 'ezhp-summaries-ajax';
$ezhp_script_path   = plugin_dir_path(__FILE__) . 'summaries-ajax.js';
$ezhp_script_url    = plugin_dir_url(__FILE__) . 'summaries-ajax.js';

// Only register once
if (!wp_script_is($ezhp_script_handle, 'registered')) {
    wp_register_script(
        $ezhp_script_handle,
        $ezhp_script_url,
        [],
        file_exists($ezhp_script_path) ? filemtime($ezhp_script_path) : '1.0.0',
        true
    );
}

// Enqueue the script
wp_enqueue_script($ezhp_script_handle);

// Cache-bust value mirrors server-side invalidation: changes daily + on post save
$ezhp_cache_buster = (int) get_option('ezhp_summaries_cache_version', 0) . '-' . wp_date('Y-m-d-H');

// Build the data for this specific block instance
$ezhp_block_data = [
    'ajaxUrl'    => esc_url_raw(add_query_arg('_ezhp_v', $ezhp_cache_buster, admin_url('admin-ajax.php'))),
    'nonce'      => wp_create_nonce('ezhp_summaries'),
    'restUrl'    => esc_url_raw(add_query_arg('_ezhp_v', $ezhp_cache_buster, rest_url('ezhoroscope/v1/summaries'))),
    'attributes' => $ezhp_ajax_attributes,
    'hasBgImages'=> $ezhp_has_bg_images,
    'errorText'  => $ezhp_error_text,
];

// Add this block's data to the global object
wp_add_inline_script(
    $ezhp_script_handle,
    'window.ezhpSummariesData = window.ezhpSummariesData || {};' .
    'window.ezhpSummariesData[' . wp_json_encode($ezhp_unique_id) . '] = ' . wp_json_encode($ezhp_block_data) . ';',
    'before'
);

/*
|--------------------------------------------------------------------------
| Output Placeholder HTML
|--------------------------------------------------------------------------
*/
?>
<div id="<?php echo esc_attr($ezhp_unique_id); ?>" class="ez-horoscope-block ez-horoscope-summaries ezhp-summaries-ajax-container ezhp-ajax-loading" data-block-id="<?php echo esc_attr($ezhp_unique_id); ?>"<?php if ($ezhp_is_rtl) : ?> dir="rtl" lang="<?php echo esc_attr($ezhp_language); ?>"<?php endif; ?>>
    <div class="ezhp-loading-placeholder">
        <span class="ezhp-loading-spinner"></span>
        <p><?php echo esc_html($ezhp_loading_text); ?></p>
    </div>
</div>