<?php
/**
 * EZ Horoscope Summaries REST API Endpoint
 * 
 * This file must be loaded on every request (via main plugin file) so the REST route is available.
 */
defined('ABSPATH') || exit;

/*
|--------------------------------------------------------------------------
| Register REST API Endpoint
|--------------------------------------------------------------------------
*/
add_action('rest_api_init', function() {
    register_rest_route('ezhoroscope/v1', '/summaries', [
        'methods'             => 'POST',
        'callback'            => 'ezhp_summaries_rest_callback',
        'permission_callback' => '__return_true',
    ]);
});

/*
|--------------------------------------------------------------------------
| Register admin-ajax Endpoint (primary path — bypasses REST API blockers)
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_ezhp_summaries', 'ezhp_summaries_ajax_callback');
add_action('wp_ajax_nopriv_ezhp_summaries', 'ezhp_summaries_ajax_callback');

if (!function_exists('ezhp_summaries_ajax_callback')) {
    function ezhp_summaries_ajax_callback() {
        // Verify nonce
        $ezhp_nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($ezhp_nonce, 'ezhp_summaries')) {
            wp_send_json_error(['message' => 'Invalid nonce.'], 403);
        }

        // Decode attributes from JSON-encoded POST field
        $ezhp_attrs_raw = isset($_POST['attributes']) ? wp_unslash($_POST['attributes']) : '';
        $ezhp_attrs = json_decode($ezhp_attrs_raw, true);

        if (!is_array($ezhp_attrs)) {
            $ezhp_attrs = [];
        }

        $ezhp_html = ezhp_build_summaries_html($ezhp_attrs);
        wp_send_json_success(['html' => $ezhp_html]);
    }
}

/*
|--------------------------------------------------------------------------
| Clear Summaries Cache on Post Save
| Uses a version number approach - no direct database queries needed
|--------------------------------------------------------------------------
*/
add_action('save_post', function($post_id) {
    // Increment cache version - this invalidates all old caches
    $version = (int) get_option('ezhp_summaries_cache_version', 0);
    update_option('ezhp_summaries_cache_version', $version + 1);
});

/*
|--------------------------------------------------------------------------
| REST API Callback - Returns Horoscope Summaries HTML
|--------------------------------------------------------------------------
*/
if (!function_exists('ezhp_summaries_rest_callback')) {
    function ezhp_summaries_rest_callback($request) {
        $params = $request->get_json_params();
        $html = ezhp_build_summaries_html($params);
        return new WP_REST_Response(['html' => $html], 200);
    }
}

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

/*
|--------------------------------------------------------------------------
| Allowed HTML Tags for wp_kses (includes inline styles)
|--------------------------------------------------------------------------
*/
$ezhp_summaries_allowed_html = [
    'div'     => [
        'class'    => true,
        'style'    => true,
        'id'       => true,
        'data-bg'  => true,
        'data-pos' => true,
        'dir'      => true,
        'lang'     => true,
    ],
    'section' => [
        'class' => true,
        'style' => true,
        'dir'   => true,
        'lang'  => true,
    ],
    'img'     => [
        'src'   => true,
        'alt'   => true,
        'style' => true,
        'class' => true,
    ],
    'p'       => [
        'class' => true,
        'style' => true,
        'id'    => true,
    ],
    'a'       => [
        'href'   => true,
        'class'  => true,
        'target' => true,
        'rel'    => true,
    ],
    'span'    => [
        'class' => true,
        'style' => true,
    ],
    'strong'  => [
        'class' => true,
    ],
    'b'       => [
        'class' => true,
    ],
    'em'      => [
        'class' => true,
    ],
    'i'       => [
        'class' => true,
    ],
    'br'      => [],
    'h1'      => [
        'class' => true,
        'style' => true,
    ],
    'h2'      => [
        'class' => true,
        'style' => true,
    ],
    'h3'      => [
        'class' => true,
        'style' => true,
    ],
    'h4'      => [
        'class' => true,
        'style' => true,
    ],
    'ul'      => [
        'class' => true,
    ],
    'ol'      => [
        'class' => true,
    ],
    'li'      => [
        'class' => true,
    ],
];

/*
|--------------------------------------------------------------------------
| "Daily Horoscopes for" Header Translations (45 languages)
|--------------------------------------------------------------------------
*/
$ezhp_summaries_header_translations = [
    'en' => 'Daily Horoscopes for',
    'fr' => 'Horoscopes du jour pour le',
    'it' => 'Oroscopo del giorno per il',
    'de' => 'Tageshoroskop für den',
    'es' => 'Horóscopos diarios para el',
    'ar' => 'الأبراج اليومية ليوم',
    'bn' => 'দৈনিক রাশিফল',
    'cs' => 'Denní horoskopy pro',
    'da' => 'Daglige horoskoper for',
    'el' => 'Ημερήσια ωροσκόπια για',
    'et' => 'Päevased horoskopid kuupäevaks',
    'eu' => 'Eguneroko horoskopoak',
    'fa' => 'فال روزانه برای',
    'fi' => 'Päivittäiset horoskopit',
    'he' => 'הורוסקופ יומי ל',
    'hi' => 'दैनिक राशिफल',
    'hu' => 'Napi horoszkóp',
    'id' => 'Horoskop harian untuk',
    'ja' => '今日の星占い',
    'ko' => '오늘의 운세',
    'lt' => 'Dienos horoskopai',
    'lv' => 'Dienas horoskopi',
    'ms' => 'Horoskop harian untuk',
    'nb' => 'Daglige horoskoper for',
    'nl' => 'Dagelijkse horoscopen voor',
    'pl' => 'Horoskop dzienny na',
    'pt' => 'Horóscopo diário para',
    'ro' => 'Horoscop zilnic pentru',
    'ru' => 'Гороскоп на',
    'sq' => 'Horoskopi ditor për',
    'sv' => 'Dagliga horoskop för',
    'th' => 'ดวงรายวันสำหรับ',
    'tl' => 'Pang-araw-araw na horoscope para sa',
    'tr' => 'Günlük burç yorumları',
    'uk' => 'Гороскоп на',
    'ur' => 'آج کا زائچہ',
    'eo' => 'Ĉiutagaj horoskopoj por',
    'ga' => 'Horoscopes laethúla do',
    'gl' => 'Horóscopo diario para',
    'az' => 'Günlük bürclər',
    'bg' => 'Дневен хороскоп за',
    'ca' => 'Horòscop diari per a',
    'sk' => 'Denný horoskop pre',
    'sl' => 'Dnevni horoskop za',
    'zh' => '今日星座运势',
];

/*
|--------------------------------------------------------------------------
| "More..." Translations (45 languages)
|--------------------------------------------------------------------------
*/
$ezhp_summaries_more_translations = [
    'en' => 'More...',
    'fr' => 'Plus...',
    'it' => 'Altro...',
    'de' => 'Mehr...',
    'es' => 'Más...',
    'ar' => 'المزيد...',
    'bn' => 'আরও...',
    'cs' => 'Více...',
    'da' => 'Mere...',
    'el' => 'Περισσότερα...',
    'et' => 'Rohkem...',
    'eu' => 'Gehiago...',
    'fa' => 'بیشتر...',
    'fi' => 'Lisää...',
    'he' => 'עוד...',
    'hi' => 'और...',
    'hu' => 'Továbbiak...',
    'id' => 'Selengkapnya...',
    'ja' => '続きを読む...',
    'ko' => '더 보기...',
    'lt' => 'Daugiau...',
    'lv' => 'Vairāk...',
    'ms' => 'Lagi...',
    'nb' => 'Mer...',
    'nl' => 'Meer...',
    'pl' => 'Więcej...',
    'pt' => 'Mais...',
    'ro' => 'Mai mult...',
    'ru' => 'Подробнее...',
    'sq' => 'Më shumë...',
    'sv' => 'Mer...',
    'th' => 'เพิ่มเติม...',
    'tl' => 'Higit pa...',
    'tr' => 'Daha fazla...',
    'uk' => 'Детальніше...',
    'ur' => 'مزید...',
    'eo' => 'Pli...',
    'ga' => 'Tuilleadh...',
    'gl' => 'Máis...',
    'az' => 'Daha çox...',
    'bg' => 'Още...',
    'ca' => 'Més...',
    'sk' => 'Viac...',
    'sl' => 'Več...',
    'zh' => '更多...',
];

/*
|--------------------------------------------------------------------------
| Helper: Format Date Based on Language
|--------------------------------------------------------------------------
*/
if (!function_exists('ezhp_format_date_by_language')) {
    function ezhp_format_date_by_language($ezhp_date_str, $ezhp_lang) {
        $ezhp_timestamp = strtotime($ezhp_date_str);
        if ($ezhp_timestamp === false) {
            return $ezhp_date_str;
        }
        
        $ezhp_day   = gmdate('d', $ezhp_timestamp);
        $ezhp_month = gmdate('m', $ezhp_timestamp);
        $ezhp_year  = gmdate('Y', $ezhp_timestamp);
        
        if ($ezhp_lang === 'en') {
            return $ezhp_month . '/' . $ezhp_day . '/' . $ezhp_year;
        }
        
        if (in_array($ezhp_lang, ['ja', 'zh', 'ko'], true)) {
            return $ezhp_year . '/' . $ezhp_month . '/' . $ezhp_day;
        }
        
        return $ezhp_day . '/' . $ezhp_month . '/' . $ezhp_year;
    }
}

/*
|--------------------------------------------------------------------------
| Helper: Build Summaries HTML (used by REST endpoint)
|--------------------------------------------------------------------------
*/
if (!function_exists('ezhp_build_summaries_html')) {
    function ezhp_build_summaries_html($attributes) {
        global $ezhp_summaries_rtl_languages, $ezhp_summaries_allowed_html, $ezhp_summaries_header_translations, $ezhp_summaries_more_translations;
        
        // Sanitize inputs
        $ezhp_language    = sanitize_text_field($attributes['language'] ?? 'en');
        $ezhp_api_key     = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));
        $ezhp_show_header = isset($attributes['showHeader']) ? (bool) $attributes['showHeader'] : true;
        
        $ezhp_is_rtl = in_array($ezhp_language, $ezhp_summaries_rtl_languages, true);
        
        $ezhp_more_text   = $ezhp_summaries_more_translations[$ezhp_language] ?? $ezhp_summaries_more_translations['en'];
        $ezhp_header_text = $ezhp_summaries_header_translations[$ezhp_language] ?? $ezhp_summaries_header_translations['en'];
        
        // 12 zodiac images
        $ezhp_images = [
            'Aries'       => isset($attributes['imageAries']) ? esc_url($attributes['imageAries']) : '',
            'Taurus'      => isset($attributes['imageTaurus']) ? esc_url($attributes['imageTaurus']) : '',
            'Gemini'      => isset($attributes['imageGemini']) ? esc_url($attributes['imageGemini']) : '',
            'Cancer'      => isset($attributes['imageCancer']) ? esc_url($attributes['imageCancer']) : '',
            'Leo'         => isset($attributes['imageLeo']) ? esc_url($attributes['imageLeo']) : '',
            'Virgo'       => isset($attributes['imageVirgo']) ? esc_url($attributes['imageVirgo']) : '',
            'Libra'       => isset($attributes['imageLibra']) ? esc_url($attributes['imageLibra']) : '',
            'Scorpio'     => isset($attributes['imageScorpio']) ? esc_url($attributes['imageScorpio']) : '',
            'Sagittarius' => isset($attributes['imageSagittarius']) ? esc_url($attributes['imageSagittarius']) : '',
            'Capricorn'   => isset($attributes['imageCapricorn']) ? esc_url($attributes['imageCapricorn']) : '',
            'Aquarius'    => isset($attributes['imageAquarius']) ? esc_url($attributes['imageAquarius']) : '',
            'Pisces'      => isset($attributes['imagePisces']) ? esc_url($attributes['imagePisces']) : '',
        ];
        
        // 12 zodiac links
        $ezhp_links = [
            'Aries'       => isset($attributes['linkAries']) ? esc_url($attributes['linkAries']) : '',
            'Taurus'      => isset($attributes['linkTaurus']) ? esc_url($attributes['linkTaurus']) : '',
            'Gemini'      => isset($attributes['linkGemini']) ? esc_url($attributes['linkGemini']) : '',
            'Cancer'      => isset($attributes['linkCancer']) ? esc_url($attributes['linkCancer']) : '',
            'Leo'         => isset($attributes['linkLeo']) ? esc_url($attributes['linkLeo']) : '',
            'Virgo'       => isset($attributes['linkVirgo']) ? esc_url($attributes['linkVirgo']) : '',
            'Libra'       => isset($attributes['linkLibra']) ? esc_url($attributes['linkLibra']) : '',
            'Scorpio'     => isset($attributes['linkScorpio']) ? esc_url($attributes['linkScorpio']) : '',
            'Sagittarius' => isset($attributes['linkSagittarius']) ? esc_url($attributes['linkSagittarius']) : '',
            'Capricorn'   => isset($attributes['linkCapricorn']) ? esc_url($attributes['linkCapricorn']) : '',
            'Aquarius'    => isset($attributes['linkAquarius']) ? esc_url($attributes['linkAquarius']) : '',
            'Pisces'      => isset($attributes['linkPisces']) ? esc_url($attributes['linkPisces']) : '',
        ];
        
        // Hero settings
        $ezhp_hero_mode    = sanitize_text_field($attributes['heroImageDisplayMode'] ?? 'inline');
        $ezhp_hero_wrap    = sanitize_text_field($attributes['heroImageTextWrap'] ?? 'none');
        $ezhp_hero_align   = sanitize_text_field($attributes['heroImageAlignment'] ?? 'center');
        $ezhp_hero_opacity = floatval($attributes['heroImageOverlayOpacity'] ?? 50);
        $ezhp_hero_color   = sanitize_text_field($attributes['heroImageOverlayColor'] ?? 'black');
        $ezhp_hero_max     = sanitize_text_field($attributes['heroImageMaxWidth'] ?? '40%');
        
        /*
        |--------------------------------------------------------------------------
        | Build Cache Key (includes date and version for cache invalidation)
        |--------------------------------------------------------------------------
        */
        $ezhp_cache_version = (int) get_option('ezhp_summaries_cache_version', 0);
        
        $ezhp_cache_parts = [
            'v' . $ezhp_cache_version,
            wp_date('Y-m-d'),
            $ezhp_language,
            $ezhp_show_header ? '1' : '0',
            $ezhp_hero_mode,
            $ezhp_hero_wrap,
            $ezhp_hero_align,
            (string) $ezhp_hero_opacity,
            $ezhp_hero_color,
            $ezhp_hero_max,
        ];
        
        foreach ($ezhp_images as $ezhp_img) {
            $ezhp_cache_parts[] = $ezhp_img;
        }
        
        foreach ($ezhp_links as $ezhp_link) {
            $ezhp_cache_parts[] = $ezhp_link;
        }
        
        $ezhp_cache_key = 'ezhp_summaries_' . md5(implode('|', $ezhp_cache_parts));
        
        // Skip cache in editor context (check for referer or REST request from admin)
        $ezhp_is_editor = false;
        if (defined('REST_REQUEST') && REST_REQUEST) {
            $referer = wp_get_referer();
            if ($referer && strpos($referer, '/wp-admin/') !== false) {
                $ezhp_is_editor = true;
            }
        }
        
        // Check cache (skip if in editor)
        if (!$ezhp_is_editor) {
            $ezhp_maybe_cached = get_transient($ezhp_cache_key);
            if ($ezhp_maybe_cached !== false && !empty($ezhp_maybe_cached) && strpos($ezhp_maybe_cached, 'error') === false) {
                return $ezhp_maybe_cached;
            }
        }
        
        /*
        |--------------------------------------------------------------------------
        | Fetch API Data
        |--------------------------------------------------------------------------
        */
        $ezhp_api_url = sprintf(
            'https://api.ezhoroscope.com/api/HoroscopeSummaries/%s?apikey=%s',
            rawurlencode($ezhp_language),
            rawurlencode($ezhp_api_key)
        );
        
        $ezhp_response = wp_remote_get($ezhp_api_url, [
            'timeout' => 20,
            'headers' => ['Accept' => 'application/json'],
        ]);
        
        if (is_wp_error($ezhp_response)) {
            return '<div class="ez-horoscope-block-error">Unable to load horoscope summaries.</div>';
        }
        
        $ezhp_body = wp_remote_retrieve_body($ezhp_response);
        $ezhp_data = json_decode($ezhp_body, true);
        
        if (empty($ezhp_data) || !is_array($ezhp_data)) {
            return '<div class="ez-horoscope-block-error">No horoscope summaries available.</div>';
        }
        
        /*
        |--------------------------------------------------------------------------
        | Build Output
        |--------------------------------------------------------------------------
        */
        $ezhp_output = '<div class="ez-horoscope-block ez-horoscope-summaries"';
        if ($ezhp_is_rtl) {
            $ezhp_output .= ' dir="rtl" lang="' . esc_attr($ezhp_language) . '"';
        }
        $ezhp_output .= '>';
        
        // Add header if enabled
        if ($ezhp_show_header) {
            $ezhp_horoscope_date = '';
            if (!empty($ezhp_data[0]['horoscopeDate'])) {
                $ezhp_horoscope_date = ezhp_format_date_by_language($ezhp_data[0]['horoscopeDate'], $ezhp_language);
            }
            
            $ezhp_output .= '<h2 class="ezhp-summaries-header">' . esc_html($ezhp_header_text) . ' ' . esc_html($ezhp_horoscope_date) . '</h2>';
        }
        
        foreach ($ezhp_data as $ezhp_item) {
            if (empty($ezhp_item['zodiacSign']) || empty($ezhp_item['horoscopeText'])) {
                continue;
            }
        
            $ezhp_sign     = sanitize_text_field($ezhp_item['zodiacSign']);
            $ezhp_text     = wp_kses($ezhp_item['horoscopeText'], $ezhp_summaries_allowed_html);
            $ezhp_img_url  = $ezhp_images[$ezhp_sign] ?? '';
            $ezhp_link_url = $ezhp_links[$ezhp_sign] ?? '';
        
            $ezhp_output .= '<div class="ezhp-summary-item">';
            $ezhp_output .= '<section class="ez-hero">';
            
            // Background mode
            if (!empty($ezhp_img_url) && $ezhp_hero_mode === 'background') {
                $ezhp_rgb = ($ezhp_hero_color === 'white') ? '255,255,255' : '0,0,0';
                $ezhp_op  = max(0, min(100, $ezhp_hero_opacity)) / 100;
                
                $ezhp_output .= '<div class="ez-hero-bg-wrapper" data-bg="' . esc_attr($ezhp_img_url) . '" data-pos="' . esc_attr($ezhp_hero_align) . '">';
                $ezhp_output .= '<div class="ez-hero-overlay" style="position:absolute;inset:0;background-color:rgba(' . esc_attr($ezhp_rgb) . ',' . esc_attr($ezhp_op) . ');pointer-events:none;"></div>';
            }
            
            $ezhp_output .= '<div class="ez-hero-content">';
            $ezhp_output .= '<div class="ez-hero-text">';
            
            // Inline image - FLOAT APPLIED TO CONTAINER, NOT IMG
            if (!empty($ezhp_img_url) && $ezhp_hero_mode === 'inline') {
                $ezhp_container_style = 'max-width:' . esc_attr($ezhp_hero_max) . ';';
                
                if ($ezhp_hero_wrap === 'left') {
                    // Image floats left, text wraps on right
                    if ($ezhp_is_rtl) {
                        $ezhp_container_style .= 'float:right;margin:0 0 1rem 1rem;';
                    } else {
                        $ezhp_container_style .= 'float:left;margin:0 1rem 1rem 0;';
                    }
                } elseif ($ezhp_hero_wrap === 'right') {
                    // Image floats right, text wraps on left
                    if ($ezhp_is_rtl) {
                        $ezhp_container_style .= 'float:left;margin:0 1rem 1rem 0;';
                    } else {
                        $ezhp_container_style .= 'float:right;margin:0 0 1rem 1rem;';
                    }
                } else {
                    // No wrap - center the image
                    $ezhp_container_style .= 'display:block;margin:0 auto 1rem;';
                }
                
                $ezhp_output .= '<div class="ez-daily-inline-image" style="' . esc_attr($ezhp_container_style) . '">';
                $ezhp_output .= '<img src="' . esc_url($ezhp_img_url) . '" alt="" style="width:100%;height:auto;border-radius:8px;">';
                $ezhp_output .= '</div>';
            }
            
            // Horoscope text
            $ezhp_output .= $ezhp_text;
            
            // "More..." link
            if (!empty($ezhp_link_url)) {
                $ezhp_output .= '<p class="ezhp-more-link"><a href="' . esc_url($ezhp_link_url) . '">' . esc_html($ezhp_more_text) . '</a></p>';
            }
            
            $ezhp_output .= '</div></div>';
            
            if (!empty($ezhp_img_url) && $ezhp_hero_mode === 'background') {
                $ezhp_output .= '</div>';
            }
            
            $ezhp_output .= '</section>';
            $ezhp_output .= '</div>';
        }
        
        $ezhp_output .= '</div>';
        
        // Cache the output (1 hour) - only on frontend, not in editor
        if (!empty($ezhp_output) && !$ezhp_is_editor) {
            set_transient($ezhp_cache_key, $ezhp_output, HOUR_IN_SECONDS);
        }
        
        return $ezhp_output;
    }
}