<?php
/**
 * Weekly Horoscope Section Shortcode
 *
 * Displays a single section from the weekly horoscope.
 *
 * Usage: [ezhp_ezhoroscope_weeklysection sign="aries" section="sunday" language="en"]
 *
 * @package EZ_Horoscope
 */

if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Register the weekly section shortcode
 */
add_shortcode('ezhp_ezhoroscope_weeklysection', 'ezhp_weekly_section_shortcode_render');

/**
 * Render the weekly section shortcode
 *
 * @param array $ezhp_atts_input Shortcode attributes.
 * @return string HTML output.
 */
function ezhp_weekly_section_shortcode_render($ezhp_atts_input) {
    $ezhp_atts = shortcode_atts(
        array(
            'sign'     => 'aries',
            'section'  => 'sunday',
            'language' => 'en',
        ),
        $ezhp_atts_input,
        'ezhp_ezhoroscope_weeklysection'
    );

    $ezhp_sign     = sanitize_text_field(strtolower($ezhp_atts['sign']));
    $ezhp_section  = sanitize_text_field(strtolower($ezhp_atts['section']));
    $ezhp_language = sanitize_text_field($ezhp_atts['language']);

    // Validate sign
    $ezhp_valid_signs = array(
        'aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo',
        'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquarius', 'pisces'
    );
    if (!in_array($ezhp_sign, $ezhp_valid_signs, true)) {
        return '<div class="ez-weekly-section ez-weekly-section-error">' .
            esc_html__('Invalid zodiac sign specified.', 'ez-horoscope') .
            '</div>';
    }

    // Map section parameter to HTML element ID
    $ezhp_section_map = array(
        'title'        => 'title',
        'week-ahead'   => 'weekly-week-ahead',
        'weekahead'    => 'weekly-week-ahead',
        'week_ahead'   => 'weekly-week-ahead',
        'sunday'       => 'weekly-sunday',
        'monday'       => 'weekly-monday',
        'tuesday'      => 'weekly-tuesday',
        'wednesday'    => 'weekly-wednesday',
        'thursday'     => 'weekly-thursday',
        'friday'       => 'weekly-friday',
        'saturday'     => 'weekly-saturday',
        'summary'      => 'weekly-summary',
        'weekly-focus' => 'weekly-summary',
        'weeklyfocus'  => 'weekly-summary',
        'weekly_focus' => 'weekly-summary',
        'focus'        => 'weekly-summary',
    );

    if (!isset($ezhp_section_map[$ezhp_section])) {
        return '<div class="ez-weekly-section ez-weekly-section-error">' .
            esc_html__('Invalid section specified. Use: title, week-ahead, sunday, monday, tuesday, wednesday, thursday, friday, saturday, or summary.', 'ez-horoscope') .
            '</div>';
    }

    $ezhp_section_id = $ezhp_section_map[$ezhp_section];

    // Get API key
    $ezhp_api_key = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

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

    // Build unique transient key
    $ezhp_cache_key = 'ezhp_weekly_' . 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, array(
            'timeout' => 20,
            'headers' => array('Accept' => 'application/json'),
        ));

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

        $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 {
        $ezhp_body = $ezhp_cached_body;
    }

    // Validate response
    if (empty($ezhp_body)) {
        return '<div class="ez-weekly-section ez-weekly-section-error">' .
            esc_html__('Empty response from horoscope API.', 'ez-horoscope') .
            '</div>';
    }

    $ezhp_data = json_decode($ezhp_body, true);

    if (!is_array($ezhp_data) || !isset($ezhp_data['horoscopeText']) || empty($ezhp_data['horoscopeText'])) {
        delete_transient($ezhp_cache_key);
        return '<div class="ez-weekly-section ez-weekly-section-error">' .
            esc_html__('Unable to decode horoscope data.', 'ez-horoscope') .
            '</div>';
    }

    $ezhp_html = $ezhp_data['horoscopeText'];

    // Handle title extraction separately
    if ($ezhp_section_id === 'title') {
        $ezhp_extracted = ezhp_extract_weekly_title($ezhp_html);
    } else {
        // Extract the specific section using DOMDocument
        $ezhp_extracted = ezhp_extract_weekly_section($ezhp_html, $ezhp_section_id);
    }

    if (empty($ezhp_extracted)) {
        return '<div class="ez-weekly-section ez-weekly-section-error">' .
            esc_html__('Section not found in horoscope data.', 'ez-horoscope') .
            '</div>';
    }

    // Determine the section name for CSS class (normalize to simple day name)
    $ezhp_section_name = str_replace('weekly-', '', $ezhp_section_id);

    // RTL language detection
    $ezhp_rtl_languages = array('ar', 'he', 'fa', 'ur', 'ps', 'sd', 'yi', 'ku', 'dv', 'ug');
    $ezhp_lang_base = strtolower(explode('-', $ezhp_language)[0]);
    $ezhp_is_rtl = in_array($ezhp_lang_base, $ezhp_rtl_languages, true);

    // Build CSS classes
    $ezhp_classes = array(
        'ez-weekly-section',
        'ez-weekly-section-' . esc_attr($ezhp_section_name),
        'ez-weekly-section-' . esc_attr($ezhp_sign),
    );

    if ($ezhp_is_rtl) {
        $ezhp_classes[] = 'ez-weekly-section-rtl';
    }

    // Build output - no image placeholder for title section
    if ($ezhp_section_id === 'title') {
        $ezhp_output = sprintf(
            '<div class="%s"%s>%s</div>',
            esc_attr(implode(' ', $ezhp_classes)),
            $ezhp_is_rtl ? ' dir="rtl"' : '',
            $ezhp_extracted
        );
    } else {
        $ezhp_output = sprintf(
            '<div class="%s"%s><div class="ez-weekly-section-image"></div>%s</div>',
            esc_attr(implode(' ', $ezhp_classes)),
            $ezhp_is_rtl ? ' dir="rtl"' : '',
            $ezhp_extracted
        );
    }

    return $ezhp_output;
}

/**
 * Extract a specific section from the weekly horoscope HTML
 *
 * @param string $ezhp_html       The full horoscope HTML.
 * @param string $ezhp_section_id The section ID to extract (e.g., 'weekly-sunday').
 * @return string The extracted section HTML, or empty string if not found.
 */
function ezhp_extract_weekly_section($ezhp_html, $ezhp_section_id) {
    if (empty($ezhp_html) || empty($ezhp_section_id)) {
        return '';
    }

    // Use DOMDocument to parse the HTML
    $ezhp_dom = new DOMDocument();

    // Suppress warnings for malformed HTML and set encoding
    libxml_use_internal_errors(true);
    $ezhp_dom->loadHTML('<?xml encoding="UTF-8">' . $ezhp_html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();

    // Find the element with the matching ID
    $ezhp_element = $ezhp_dom->getElementById($ezhp_section_id);

    if (!$ezhp_element) {
        return '';
    }

    // Get the inner HTML of the flexbox-content div
    $ezhp_content_divs = $ezhp_element->getElementsByTagName('div');
    $ezhp_extracted_html = '';

    foreach ($ezhp_content_divs as $ezhp_div) {
        if ($ezhp_div->getAttribute('class') === 'eztype-flexbox-content') {
            // Extract inner HTML
            $ezhp_inner_html = '';
            foreach ($ezhp_div->childNodes as $ezhp_child) {
                $ezhp_inner_html .= $ezhp_dom->saveHTML($ezhp_child);
            }
            $ezhp_extracted_html = $ezhp_inner_html;
            break;
        }
    }

    if (empty($ezhp_extracted_html)) {
        // Fallback: return the entire element's inner HTML
        $ezhp_inner_html = '';
        foreach ($ezhp_element->childNodes as $ezhp_child) {
            $ezhp_inner_html .= $ezhp_dom->saveHTML($ezhp_child);
        }
        $ezhp_extracted_html = $ezhp_inner_html;
    }

    // Transform <strong> to heading with class
    $ezhp_extracted_html = preg_replace(
        '/<strong>(.*?)<\/strong>/is',
        '<h3 class="ez-weekly-section-heading">$1</h3>',
        $ezhp_extracted_html,
        1 // Only replace the first occurrence (the day header)
    );

    // Add class to paragraph
    $ezhp_extracted_html = preg_replace(
        '/<p>/i',
        '<p class="ez-weekly-section-content">',
        $ezhp_extracted_html
    );

    return $ezhp_extracted_html;
}

/**
 * Extract the title heading from the weekly horoscope HTML
 *
 * @param string $ezhp_html The full horoscope HTML.
 * @return string The extracted title HTML, or empty string if not found.
 */
function ezhp_extract_weekly_title($ezhp_html) {
    if (empty($ezhp_html)) {
        return '';
    }

    // Use DOMDocument to parse the HTML
    $ezhp_dom = new DOMDocument();

    // Suppress warnings for malformed HTML and set encoding
    libxml_use_internal_errors(true);
    $ezhp_dom->loadHTML('<?xml encoding="UTF-8">' . $ezhp_html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();

    // Find the h2 heading with class eztype-flexbox-heading
    $ezhp_headings = $ezhp_dom->getElementsByTagName('h2');

    foreach ($ezhp_headings as $ezhp_heading) {
        if (strpos($ezhp_heading->getAttribute('class'), 'eztype-flexbox-heading') !== false) {
            $ezhp_title_text = $ezhp_heading->textContent;
            return '<h2 class="ez-weekly-section-heading">' . esc_html($ezhp_title_text) . '</h2>';
        }
    }

    return '';
}