<?php
// Exit if accessed directly
if (! defined('ABSPATH')) {
    exit;
}

require_once plugin_dir_path(__FILE__) . 'ezhp-automation-messages.php';

// Register AJAX handlers
add_action('wp_ajax_ezhp_create_pages', 'ezhp_ajax_create_pages');
add_action('wp_ajax_ezhp_clear_cache', 'ezhp_ajax_clear_cache');

/**
 * AJAX handler to clear all EZ Horoscope transient caches
 *
 * @return void
 */
function ezhp_ajax_clear_cache() {
    // Verify nonce.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ezhp_clear_cache_nonce' ) ) {
        wp_send_json_error( array( 'message' => __( 'Security check failed.', 'ez-horoscope' ) ) );
    }

    // Check user capability.
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => __( 'Permission denied.', 'ez-horoscope' ) ) );
    }

    global $wpdb;

    // Count transients before deletion.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $ezhp_count = $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE '_transient_ezhp_%'"
    );

    // Delete all EZ Horoscope transients.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ezhp_%' OR option_name LIKE '_transient_timeout_ezhp_%'"
    );

    // Also increment the summaries cache version to invalidate any edge-cached content.
    $ezhp_version = (int) get_option( 'ezhp_summaries_cache_version', 0 );
    update_option( 'ezhp_summaries_cache_version', $ezhp_version + 1 );

    wp_send_json_success(
        array(
            'message' => sprintf(
                /* translators: %d: number of cached items cleared */
                __( 'Successfully cleared %d cached items.', 'ez-horoscope' ),
                (int) $ezhp_count
            ),
            'count'   => (int) $ezhp_count,
        )
    );
}

/**
 * Track block usage (first render only per block type per site)
 *
 * @param string $ezhp_block_name The block name (e.g., "daily-horoscope").
 * @param array  $ezhp_attributes The block attributes.
 * @return void
 */
function ezhp_track_block_usage($ezhp_block_name, $ezhp_attributes = array())
{
    // Option name to track which blocks have been recorded
    $ezhp_option_name = 'ezhp_tracked_blocks';

    // Get already tracked blocks
    $ezhp_tracked_blocks = get_option($ezhp_option_name, array());

    // Skip if this block type has already been tracked
    if (in_array($ezhp_block_name, $ezhp_tracked_blocks, true)) {
        return;
    }

    // Get the activation GUID
    $ezhp_activation_guid = get_option('ezhp_horoscope_activation_guid', '');

    // Skip tracking if no activation GUID
    if (empty($ezhp_activation_guid)) {
        return;
    }

    // Build tracking data based on block type
    $ezhp_event_data = array();

    switch ($ezhp_block_name) {
        case 'daily-horoscope':
        case 'weekly-horoscope':
            $ezhp_event_data = array(
                'sign'     => isset($ezhp_attributes['sign']) ? $ezhp_attributes['sign'] : 'aries',
                'language' => isset($ezhp_attributes['language']) ? $ezhp_attributes['language'] : 'en',
            );
            break;

        case 'horoscope-summaries':
        case 'chinese-horoscope':
        case 'numerology':
        case 'tarot-3card-spread':
        case 'zodiac-compatibility':
        case 'birth-chart':
            $ezhp_event_data = array(
                'language' => isset($ezhp_attributes['language']) ? $ezhp_attributes['language'] : 'en',
            );
            break;

        default:
            $ezhp_event_data = array();
    }

    // Prepare the tracking data
    $ezhp_tracking_data = array(
        'activationGuid' => $ezhp_activation_guid,
        'eventType'      => 'Block',
        'eventAction'    => 'FirstRender',
        'eventValue'     => $ezhp_block_name,
        'eventData'      => wp_json_encode($ezhp_event_data),
        'domainName'     => get_site_url(),
        'pluginVersion'  => defined('EZHP_PLUGIN_VERSION') ? EZHP_PLUGIN_VERSION : null,
    );

    // Send the tracking request (non-blocking)
    $ezhp_response = wp_remote_post('https://www.enneagramzoom.com/api/PluginUsageTracking', array(
        'method'    => 'POST',
        'body'      => wp_json_encode($ezhp_tracking_data),
        'headers'   => array(
            'Content-Type' => 'application/json',
        ),
        'timeout'   => 5,
        'blocking'  => false,
    ));

    // Mark this block as tracked (even if request fails, to avoid repeated attempts)
    $ezhp_tracked_blocks[] = $ezhp_block_name;
    update_option($ezhp_option_name, $ezhp_tracked_blocks);
}

/**
 * Send tracking event to the API
 *
 * @param string $ezhp_event_type The event type (e.g., "Automation").
 * @param string $ezhp_event_action The event action (e.g., "PagesCreated").
 * @param string $ezhp_event_value Optional event value.
 * @param array  $ezhp_event_data Optional additional data.
 * @return bool True if successful, false otherwise.
 */
function ezhp_track_usage_event($ezhp_event_type, $ezhp_event_action, $ezhp_event_value = null, $ezhp_event_data = null)
{
    // Get the activation GUID
    $ezhp_activation_guid = get_option('ezhp_horoscope_activation_guid', '');

    // Skip tracking if no activation GUID
    if (empty($ezhp_activation_guid)) {
        return false;
    }

    // Prepare the tracking data
    $ezhp_tracking_data = array(
        'activationGuid' => $ezhp_activation_guid,
        'eventType'      => $ezhp_event_type,
        'eventAction'    => $ezhp_event_action,
        'eventValue'     => $ezhp_event_value,
        'eventData'      => $ezhp_event_data ? wp_json_encode($ezhp_event_data) : null,
        'domainName'     => get_site_url(),
        'pluginVersion'  => defined('EZHP_PLUGIN_VERSION') ? EZHP_PLUGIN_VERSION : null,
    );

    // Send the tracking request
    $ezhp_response = wp_remote_post('https://www.enneagramzoom.com/api/PluginUsageTracking', array(
        'method'  => 'POST',
        'body'    => wp_json_encode($ezhp_tracking_data),
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
        'timeout' => 10,
    ));

    // Check if request was successful
    if (is_wp_error($ezhp_response)) {
        return false;
    }

    $ezhp_response_code = wp_remote_retrieve_response_code($ezhp_response);
    return $ezhp_response_code >= 200 && $ezhp_response_code < 300;
}


/**
 * Get default zodiac image URL
 *
 * @param string $ezhp_sign The zodiac sign (lowercase).
 * @return string Image URL.
 */
function ezhp_get_default_zodiac_image_url($ezhp_sign)
{
    if (! defined('EZHP_PLUGIN_URL')) {
        return '';
    }

    $ezhp_sign_lower = strtolower($ezhp_sign);
    return EZHP_PLUGIN_URL . 'assets/images/zodiac/ez-' . $ezhp_sign_lower . '.jpg';
}

/**
 * Get translated heading text for automation pages
 *
 * @param string $ezhp_key The heading key (chinese-horoscope, numerology, tarot-reading, zodiac-compatibility).
 * @param string $ezhp_lang The language code.
 * @return string Translated heading text.
 */
function ezhp_get_translated_heading($ezhp_key, $ezhp_lang)
{
    $ezhp_translations = array(
        'chinese-horoscope' => array(
            'en' => 'Chinese Horoscope',
            'ar' => 'الأبراج الصينية',
            'az' => 'Çin Horoskopu',
            'bg' => 'Китайски хороскоп',
            'bn' => 'চীনা রাশিফল',
            'ca' => 'Horòscop Xinès',
            'cs' => 'Čínský horoskop',
            'da' => 'Kinesisk Horoskop',
            'de' => 'Chinesisches Horoskop',
            'el' => 'Κινέζικο Ωροσκόπιο',
            'eo' => 'Ĉina Horoskopo',
            'es' => 'Horóscopo Chino',
            'et' => 'Hiina Horoskoop',
            'eu' => 'Txinatar Horoskopoа',
            'fa' => 'طالع‌بینی چینی',
            'fi' => 'Kiinalainen Horoskooppi',
            'fr' => 'Horoscope Chinois',
            'ga' => 'Horoscóp Síneach',
            'gl' => 'Horóscopo Chinés',
            'he' => 'הורוסקופ סיני',
            'hi' => 'चीनी राशिफल',
            'hu' => 'Kínai Horoszkóp',
            'id' => 'Horoskop Cina',
            'it' => 'Oroscopo Cinese',
            'ja' => '中国の星占い',
            'ko' => '중국 운세',
            'lt' => 'Kinų Horoskopas',
            'lv' => 'Ķīniešu Horoskops',
            'ms' => 'Horoskop Cina',
            'nb' => 'Kinesisk Horoskop',
            'nl' => 'Chinees Horoscoop',
            'pl' => 'Horoskop Chiński',
            'pt' => 'Horóscopo Chinês',
            'ro' => 'Horoscop Chinezesc',
            'ru' => 'Китайский гороскоп',
            'sk' => 'Čínsky Horoskop',
            'sl' => 'Kitajski Horoskop',
            'sq' => 'Horoskopi Kinez',
            'sv' => 'Kinesiskt Horoskop',
            'th' => 'ดวงจีน',
            'tl' => 'Horoscope ng Tsina',
            'tr' => 'Çin Burcu',
            'uk' => 'Китайський гороскоп',
            'ur' => 'چینی زائچہ',
            'zh' => '中国生肖运势',
        ),
        'numerology' => array(
            'en' => 'Numerology',
            'ar' => 'علم الأرقام',
            'az' => 'Numerologiya',
            'bg' => 'Нумерология',
            'bn' => 'সংখ্যাতত্ত্ব',
            'ca' => 'Numerologia',
            'cs' => 'Numerologie',
            'da' => 'Numerologi',
            'de' => 'Numerologie',
            'el' => 'Αριθμολογία',
            'eo' => 'Numerologio',
            'es' => 'Numerología',
            'et' => 'Numeroloogia',
            'eu' => 'Numerologia',
            'fa' => 'عددشناسی',
            'fi' => 'Numerologia',
            'fr' => 'Numérologie',
            'ga' => 'Uimhríocht',
            'gl' => 'Numeroloxía',
            'he' => 'נומרולוגיה',
            'hi' => 'अंकज्योतिष',
            'hu' => 'Numerológia',
            'id' => 'Numerologi',
            'it' => 'Numerologia',
            'ja' => '数秘術',
            'ko' => '수비학',
            'lt' => 'Numerologija',
            'lv' => 'Numeroloģija',
            'ms' => 'Numerologi',
            'nb' => 'Numerologi',
            'nl' => 'Numerologie',
            'pl' => 'Numerologia',
            'pt' => 'Numerologia',
            'ro' => 'Numerologie',
            'ru' => 'Нумерология',
            'sk' => 'Numerológia',
            'sl' => 'Numerologija',
            'sq' => 'Numerologjia',
            'sv' => 'Numerologi',
            'th' => 'ตัวเลขศาสตร์',
            'tl' => 'Numerolohiya',
            'tr' => 'Numeroloji',
            'uk' => 'Нумерологія',
            'ur' => 'علم الاعداد',
            'zh' => '数字命理学',
        ),
        'tarot-reading' => array(
            'en' => 'Tarot Reading',
            'ar' => 'قراءة التاروت',
            'az' => 'Tarot Oxunuşu',
            'bg' => 'Таро Четене',
            'bn' => 'ট্যারট রিডিং',
            'ca' => 'Lectura de Tarot',
            'cs' => 'Čtení Tarotu',
            'da' => 'Tarot Læsning',
            'de' => 'Tarot-Lesung',
            'el' => 'Ανάγνωση Ταρώ',
            'eo' => 'Taroka Legado',
            'es' => 'Lectura de Tarot',
            'et' => 'Tarot Lugemine',
            'eu' => 'Tarot Irakurketa',
            'fa' => 'فال تاروت',
            'fi' => 'Tarot-lukeminen',
            'fr' => 'Lecture de Tarot',
            'ga' => 'Léamh Tarot',
            'gl' => 'Lectura de Tarot',
            'he' => 'קריאת טארוט',
            'hi' => 'टैरो रीडिंग',
            'hu' => 'Tarot Olvasás',
            'id' => 'Pembacaan Tarot',
            'it' => 'Lettura dei Tarocchi',
            'ja' => 'タロット占い',
            'ko' => '타로 리딩',
            'lt' => 'Taro Skaitymas',
            'lv' => 'Taro Lasīšana',
            'ms' => 'Pembacaan Tarot',
            'nb' => 'Tarot Lesing',
            'nl' => 'Tarot Lezing',
            'pl' => 'Czytanie Tarota',
            'pt' => 'Leitura de Tarot',
            'ro' => 'Citirea Tarotului',
            'ru' => 'Чтение Таро',
            'sk' => 'Čítanie Tarotu',
            'sl' => 'Branje Tarota',
            'sq' => 'Leximi i Tarotit',
            'sv' => 'Tarot Läsning',
            'th' => 'อ่านไพ่ทาโรต์',
            'tl' => 'Pagbabasa ng Tarot',
            'tr' => 'Tarot Falı',
            'uk' => 'Читання Таро',
            'ur' => 'ٹیرو ریڈنگ',
            'zh' => '塔罗牌阅读',
        ),
        'zodiac-compatibility' => array(
            'en' => 'Zodiac Compatibility',
            'ar' => 'توافق الأبراج',
            'az' => 'Bürc Uyğunluğu',
            'bg' => 'Зодиакална Съвместимост',
            'bn' => 'রাশি সামঞ্জস্য',
            'ca' => 'Compatibilitat del Zodíac',
            'cs' => 'Kompatibilita Znamení',
            'da' => 'Stjernetegn Kompatibilitet',
            'de' => 'Sternzeichen-Kompatibilität',
            'el' => 'Συμβατότητα Ζωδίων',
            'eo' => 'Zodiaka Kongrueco',
            'es' => 'Compatibilidad del Zodiaco',
            'et' => 'Sodiaagi Ühilduvus',
            'eu' => 'Zodiako Bateragarritasuna',
            'fa' => 'سازگاری زودیاک',
            'fi' => 'Horoskooppimerkkien Yhteensopivuus',
            'fr' => 'Compatibilité du Zodiaque',
            'ga' => 'Comhoiriúnacht Stoidiaca',
            'gl' => 'Compatibilidade do Zodíaco',
            'he' => 'תאימות מזלות',
            'hi' => 'राशि अनुकूलता',
            'hu' => 'Csillagjegy Kompatibilitás',
            'id' => 'Kecocokan Zodiak',
            'it' => 'Compatibilità dello Zodiaco',
            'ja' => '星座の相性',
            'ko' => '별자리 궁합',
            'lt' => 'Zodiako Suderinamumas',
            'lv' => 'Zodiaka Saderība',
            'ms' => 'Keserasian Zodiak',
            'nb' => 'Stjernetegn Kompatibilitet',
            'nl' => 'Sterrenbeeld Compatibiliteit',
            'pl' => 'Zgodność Znaków Zodiaku',
            'pt' => 'Compatibilidade do Zodíaco',
            'ro' => 'Compatibilitate Zodiacală',
            'ru' => 'Совместимость знаков зодиака',
            'sk' => 'Kompatibilita Znamení',
            'sl' => 'Združljivost Zodiaka',
            'sq' => 'Përputhshmëria e Zodiakut',
            'sv' => 'Stjärntecken Kompatibilitet',
            'th' => 'ความเข้ากันของราศี',
            'tl' => 'Pagkakatugma ng Zodiac',
            'tr' => 'Burç Uyumu',
            'uk' => 'Сумісність знаків зодіаку',
            'ur' => 'برج کی مطابقت',
            'zh' => '星座配对',
        ),
    );

    // Return the translation or fall back to English
    if (isset($ezhp_translations[$ezhp_key][$ezhp_lang])) {
        return $ezhp_translations[$ezhp_key][$ezhp_lang];
    }

    // Fallback to English
    return $ezhp_translations[$ezhp_key]['en'];
}

/**
 * Get translated page titles for automation
 *
 * @param string $ezhp_lang The language code.
 * @return array Array of page configurations with translated titles.
 */
function ezhp_get_translated_page_titles($ezhp_lang = 'en')
{
    $ezhp_translations = array(
        'daily-horoscope' => array(
            'en' => 'Daily Horoscope',
            'ar' => 'الأبراج اليومية',
            'az' => 'Gündəlik Bürc',
            'bg' => 'Дневен хороскоп',
            'bn' => 'দৈনিক রাশিফল',
            'ca' => 'Horòscop Diari',
            'cs' => 'Denní horoskop',
            'da' => 'Daglig Horoskop',
            'de' => 'Tageshoroskop',
            'el' => 'Ημερήσιο Ωροσκόπιο',
            'eo' => 'Ĉiutaga Horoskopo',
            'es' => 'Horóscopo Diario',
            'et' => 'Päevahoroskoop',
            'eu' => 'Eguneko Horoskopoа',
            'fa' => 'طالع‌بینی روزانه',
            'fi' => 'Päivän Horoskooppi',
            'fr' => 'Horoscope du Jour',
            'ga' => 'Horoscóp Laethúil',
            'gl' => 'Horóscopo Diario',
            'he' => 'הורוסקופ יומי',
            'hi' => 'दैनिक राशिफल',
            'hu' => 'Napi Horoszkóp',
            'id' => 'Horoskop Harian',
            'it' => 'Oroscopo del Giorno',
            'ja' => '今日の星占い',
            'ko' => '오늘의 운세',
            'lt' => 'Dienos Horoskopas',
            'lv' => 'Dienas Horoskops',
            'ms' => 'Horoskop Harian',
            'nb' => 'Daglig Horoskop',
            'nl' => 'Daghoroscoop',
            'pl' => 'Horoskop Dzienny',
            'pt' => 'Horóscopo do Dia',
            'ro' => 'Horoscop Zilnic',
            'ru' => 'Гороскоп на сегодня',
            'sk' => 'Denný Horoskop',
            'sl' => 'Dnevni Horoskop',
            'sq' => 'Horoskopi Ditor',
            'sv' => 'Dagens Horoskop',
            'th' => 'ดวงรายวัน',
            'tl' => 'Pang-araw-araw na Horoscope',
            'tr' => 'Günlük Burç Yorumu',
            'uk' => 'Гороскоп на сьогодні',
            'ur' => 'آج کا زائچہ',
            'zh' => '今日星座运势',
        ),
        'weekly-horoscope' => array(
            'en' => 'Weekly Horoscope',
            'ar' => 'الأبراج الأسبوعية',
            'az' => 'Həftəlik Bürc',
            'bg' => 'Седмичен хороскоп',
            'bn' => 'সাপ্তাহিক রাশিফল',
            'ca' => 'Horòscop Setmanal',
            'cs' => 'Týdenní horoskop',
            'da' => 'Ugentlig Horoskop',
            'de' => 'Wochenhoroskop',
            'el' => 'Εβδομαδιαίο Ωροσκόπιο',
            'eo' => 'Semajna Horoskopo',
            'es' => 'Horóscopo Semanal',
            'et' => 'Nädalahoroskoop',
            'eu' => 'Asteko Horoskopoа',
            'fa' => 'طالع‌بینی هفتگی',
            'fi' => 'Viikkohoroskooppi',
            'fr' => 'Horoscope de la Semaine',
            'ga' => 'Horoscóp Seachtainiúil',
            'gl' => 'Horóscopo Semanal',
            'he' => 'הורוסקופ שבועי',
            'hi' => 'साप्ताहिक राशिफल',
            'hu' => 'Heti Horoszkóp',
            'id' => 'Horoskop Mingguan',
            'it' => 'Oroscopo della Settimana',
            'ja' => '週間星占い',
            'ko' => '주간 운세',
            'lt' => 'Savaitės Horoskopas',
            'lv' => 'Nedēļas Horoskops',
            'ms' => 'Horoskop Mingguan',
            'nb' => 'Ukentlig Horoskop',
            'nl' => 'Weekhoroscoop',
            'pl' => 'Horoskop Tygodniowy',
            'pt' => 'Horóscopo da Semana',
            'ro' => 'Horoscop Săptămânal',
            'ru' => 'Гороскоп на неделю',
            'sk' => 'Týždenný Horoskop',
            'sl' => 'Tedenski Horoskop',
            'sq' => 'Horoskopi Javor',
            'sv' => 'Veckans Horoskop',
            'th' => 'ดวงรายสัปดาห์',
            'tl' => 'Lingguhang Horoscope',
            'tr' => 'Haftalık Burç Yorumu',
            'uk' => 'Гороскоп на тиждень',
            'ur' => 'ہفتہ وار زائچہ',
            'zh' => '本周星座运势',
        ),
        'aries' => array(
            'en' => 'Aries',
            'ar' => 'الحمل',
            'az' => 'Qoç',
            'bg' => 'Овен',
            'bn' => 'মেষ',
            'ca' => 'Àries',
            'cs' => 'Beran',
            'da' => 'Vædderen',
            'de' => 'Widder',
            'el' => 'Κριός',
            'eo' => 'Ŝafo',
            'es' => 'Aries',
            'et' => 'Jäär',
            'eu' => 'Aharia',
            'fa' => 'حمل',
            'fi' => 'Oinas',
            'fr' => 'Bélier',
            'ga' => 'An Reithe',
            'gl' => 'Aries',
            'he' => 'טלה',
            'hi' => 'मेष',
            'hu' => 'Kos',
            'id' => 'Aries',
            'it' => 'Ariete',
            'ja' => '牡羊座',
            'ko' => '양자리',
            'lt' => 'Avinas',
            'lv' => 'Auns',
            'ms' => 'Aries',
            'nb' => 'Væren',
            'nl' => 'Ram',
            'pl' => 'Baran',
            'pt' => 'Áries',
            'ro' => 'Berbec',
            'ru' => 'Овен',
            'sk' => 'Baran',
            'sl' => 'Oven',
            'sq' => 'Dashi',
            'sv' => 'Väduren',
            'th' => 'ราศีเมษ',
            'tl' => 'Aries',
            'tr' => 'Koç',
            'uk' => 'Овен',
            'ur' => 'حمل',
            'zh' => '白羊座',
        ),
        'taurus' => array(
            'en' => 'Taurus',
            'ar' => 'الثور',
            'az' => 'Buğa',
            'bg' => 'Телец',
            'bn' => 'বৃষ',
            'ca' => 'Taure',
            'cs' => 'Býk',
            'da' => 'Tyren',
            'de' => 'Stier',
            'el' => 'Ταύρος',
            'eo' => 'Taŭro',
            'es' => 'Tauro',
            'et' => 'Sõnn',
            'eu' => 'Tauroa',
            'fa' => 'ثور',
            'fi' => 'Härkä',
            'fr' => 'Taureau',
            'ga' => 'An Tarbh',
            'gl' => 'Tauro',
            'he' => 'שור',
            'hi' => 'वृषभ',
            'hu' => 'Bika',
            'id' => 'Taurus',
            'it' => 'Toro',
            'ja' => '牡牛座',
            'ko' => '황소자리',
            'lt' => 'Jautis',
            'lv' => 'Vērsis',
            'ms' => 'Taurus',
            'nb' => 'Oksen',
            'nl' => 'Stier',
            'pl' => 'Byk',
            'pt' => 'Touro',
            'ro' => 'Taur',
            'ru' => 'Телец',
            'sk' => 'Býk',
            'sl' => 'Bik',
            'sq' => 'Demi',
            'sv' => 'Oxen',
            'th' => 'ราศีพฤษภ',
            'tl' => 'Taurus',
            'tr' => 'Boğa',
            'uk' => 'Телець',
            'ur' => 'ثور',
            'zh' => '金牛座',
        ),
        'gemini' => array(
            'en' => 'Gemini',
            'ar' => 'الجوزاء',
            'az' => 'Əkizlər',
            'bg' => 'Близнаци',
            'bn' => 'মিথুন',
            'ca' => 'Bessons',
            'cs' => 'Blíženci',
            'da' => 'Tvillingerne',
            'de' => 'Zwillinge',
            'el' => 'Δίδυμοι',
            'eo' => 'Ĝemeloj',
            'es' => 'Géminis',
            'et' => 'Kaksikud',
            'eu' => 'Bikiak',
            'fa' => 'جوزا',
            'fi' => 'Kaksoset',
            'fr' => 'Gémeaux',
            'ga' => 'An Cúpla',
            'gl' => 'Xéminis',
            'he' => 'תאומים',
            'hi' => 'मिथुन',
            'hu' => 'Ikrek',
            'id' => 'Gemini',
            'it' => 'Gemelli',
            'ja' => '双子座',
            'ko' => '쌍둥이자리',
            'lt' => 'Dvyniai',
            'lv' => 'Dvīņi',
            'ms' => 'Gemini',
            'nb' => 'Tvillingene',
            'nl' => 'Tweelingen',
            'pl' => 'Bliźnięta',
            'pt' => 'Gêmeos',
            'ro' => 'Gemeni',
            'ru' => 'Близнецы',
            'sk' => 'Blíženci',
            'sl' => 'Dvojčka',
            'sq' => 'Binjakët',
            'sv' => 'Tvillingarna',
            'th' => 'ราศีเมถุน',
            'tl' => 'Gemini',
            'tr' => 'İkizler',
            'uk' => 'Близнюки',
            'ur' => 'جوزا',
            'zh' => '双子座',
        ),
        'cancer' => array(
            'en' => 'Cancer',
            'ar' => 'السرطان',
            'az' => 'Xərçəng',
            'bg' => 'Рак',
            'bn' => 'কর্কট',
            'ca' => 'Càncer',
            'cs' => 'Rak',
            'da' => 'Krebsen',
            'de' => 'Krebs',
            'el' => 'Καρκίνος',
            'eo' => 'Kankro',
            'es' => 'Cáncer',
            'et' => 'Vähk',
            'eu' => 'Karramarroa',
            'fa' => 'سرطان',
            'fi' => 'Rapu',
            'fr' => 'Cancer',
            'ga' => 'An Portán',
            'gl' => 'Cancro',
            'he' => 'סרטן',
            'hi' => 'कर्क',
            'hu' => 'Rák',
            'id' => 'Cancer',
            'it' => 'Cancro',
            'ja' => '蟹座',
            'ko' => '게자리',
            'lt' => 'Vėžys',
            'lv' => 'Vēzis',
            'ms' => 'Cancer',
            'nb' => 'Krepsen',
            'nl' => 'Kreeft',
            'pl' => 'Rak',
            'pt' => 'Câncer',
            'ro' => 'Rac',
            'ru' => 'Рак',
            'sk' => 'Rak',
            'sl' => 'Rak',
            'sq' => 'Gaforrja',
            'sv' => 'Kräftan',
            'th' => 'ราศีกรกฎ',
            'tl' => 'Cancer',
            'tr' => 'Yengeç',
            'uk' => 'Рак',
            'ur' => 'سرطان',
            'zh' => '巨蟹座',
        ),
        'leo' => array(
            'en' => 'Leo',
            'ar' => 'الأسد',
            'az' => 'Şir',
            'bg' => 'Лъв',
            'bn' => 'সিংহ',
            'ca' => 'Lleó',
            'cs' => 'Lev',
            'da' => 'Løven',
            'de' => 'Löwe',
            'el' => 'Λέων',
            'eo' => 'Leono',
            'es' => 'Leo',
            'et' => 'Lõvi',
            'eu' => 'Lehoia',
            'fa' => 'اسد',
            'fi' => 'Leijona',
            'fr' => 'Lion',
            'ga' => 'An Leon',
            'gl' => 'Leo',
            'he' => 'אריה',
            'hi' => 'सिंह',
            'hu' => 'Oroszlán',
            'id' => 'Leo',
            'it' => 'Leone',
            'ja' => '獅子座',
            'ko' => '사자자리',
            'lt' => 'Liūtas',
            'lv' => 'Lauva',
            'ms' => 'Leo',
            'nb' => 'Løven',
            'nl' => 'Leeuw',
            'pl' => 'Lew',
            'pt' => 'Leão',
            'ro' => 'Leu',
            'ru' => 'Лев',
            'sk' => 'Lev',
            'sl' => 'Lev',
            'sq' => 'Luani',
            'sv' => 'Lejonet',
            'th' => 'ราศีสิงห์',
            'tl' => 'Leo',
            'tr' => 'Aslan',
            'uk' => 'Лев',
            'ur' => 'اسد',
            'zh' => '狮子座',
        ),
        'virgo' => array(
            'en' => 'Virgo',
            'ar' => 'العذراء',
            'az' => 'Qız',
            'bg' => 'Дева',
            'bn' => 'কন্যা',
            'ca' => 'Verge',
            'cs' => 'Panna',
            'da' => 'Jomfruen',
            'de' => 'Jungfrau',
            'el' => 'Παρθένος',
            'eo' => 'Virgulino',
            'es' => 'Virgo',
            'et' => 'Neitsi',
            'eu' => 'Birjina',
            'fa' => 'سنبله',
            'fi' => 'Neitsyt',
            'fr' => 'Vierge',
            'ga' => 'An Mhaighdean',
            'gl' => 'Virgo',
            'he' => 'בתולה',
            'hi' => 'कन्या',
            'hu' => 'Szűz',
            'id' => 'Virgo',
            'it' => 'Vergine',
            'ja' => '乙女座',
            'ko' => '처녀자리',
            'lt' => 'Mergelė',
            'lv' => 'Jaunava',
            'ms' => 'Virgo',
            'nb' => 'Jomfruen',
            'nl' => 'Maagd',
            'pl' => 'Panna',
            'pt' => 'Virgem',
            'ro' => 'Fecioară',
            'ru' => 'Дева',
            'sk' => 'Panna',
            'sl' => 'Devica',
            'sq' => 'Virgjëresha',
            'sv' => 'Jungfrun',
            'th' => 'ราศีกันย์',
            'tl' => 'Virgo',
            'tr' => 'Başak',
            'uk' => 'Діва',
            'ur' => 'سنبلہ',
            'zh' => '处女座',
        ),
        'libra' => array(
            'en' => 'Libra',
            'ar' => 'الميزان',
            'az' => 'Tərəzi',
            'bg' => 'Везни',
            'bn' => 'তুলা',
            'ca' => 'Balança',
            'cs' => 'Váhy',
            'da' => 'Vægten',
            'de' => 'Waage',
            'el' => 'Ζυγός',
            'eo' => 'Pesilo',
            'es' => 'Libra',
            'et' => 'Kaalud',
            'eu' => 'Libra',
            'fa' => 'میزان',
            'fi' => 'Vaaka',
            'fr' => 'Balance',
            'ga' => 'An Mheá',
            'gl' => 'Libra',
            'he' => 'מאזניים',
            'hi' => 'तुला',
            'hu' => 'Mérleg',
            'id' => 'Libra',
            'it' => 'Bilancia',
            'ja' => '天秤座',
            'ko' => '천칭자리',
            'lt' => 'Svarstyklės',
            'lv' => 'Svari',
            'ms' => 'Libra',
            'nb' => 'Vekten',
            'nl' => 'Weegschaal',
            'pl' => 'Waga',
            'pt' => 'Libra',
            'ro' => 'Balanță',
            'ru' => 'Весы',
            'sk' => 'Váhy',
            'sl' => 'Tehtnica',
            'sq' => 'Peshorja',
            'sv' => 'Vågen',
            'th' => 'ราศีตุลย์',
            'tl' => 'Libra',
            'tr' => 'Terazi',
            'uk' => 'Терези',
            'ur' => 'میزان',
            'zh' => '天秤座',
        ),
        'scorpio' => array(
            'en' => 'Scorpio',
            'ar' => 'العقرب',
            'az' => 'Əqrəb',
            'bg' => 'Скорпион',
            'bn' => 'বৃশ্চিক',
            'ca' => 'Escorpí',
            'cs' => 'Štír',
            'da' => 'Skorpionen',
            'de' => 'Skorpion',
            'el' => 'Σκορπιός',
            'eo' => 'Skorpio',
            'es' => 'Escorpio',
            'et' => 'Skorpion',
            'eu' => 'Skorpioa',
            'fa' => 'عقرب',
            'fi' => 'Skorpioni',
            'fr' => 'Scorpion',
            'ga' => 'An Scairp',
            'gl' => 'Escorpión',
            'he' => 'עקרב',
            'hi' => 'वृश्चिक',
            'hu' => 'Skorpió',
            'id' => 'Scorpio',
            'it' => 'Scorpione',
            'ja' => '蠍座',
            'ko' => '전갈자리',
            'lt' => 'Skorpionas',
            'lv' => 'Skorpions',
            'ms' => 'Scorpio',
            'nb' => 'Skorpionen',
            'nl' => 'Schorpioen',
            'pl' => 'Skorpion',
            'pt' => 'Escorpião',
            'ro' => 'Scorpion',
            'ru' => 'Скорпион',
            'sk' => 'Škorpión',
            'sl' => 'Škorpijon',
            'sq' => 'Akrepi',
            'sv' => 'Skorpionen',
            'th' => 'ราศีพิจิก',
            'tl' => 'Scorpio',
            'tr' => 'Akrep',
            'uk' => 'Скорпіон',
            'ur' => 'عقرب',
            'zh' => '天蝎座',
        ),
        'sagittarius' => array(
            'en' => 'Sagittarius',
            'ar' => 'القوس',
            'az' => 'Oxatan',
            'bg' => 'Стрелец',
            'bn' => 'ধনু',
            'ca' => 'Sagitari',
            'cs' => 'Střelec',
            'da' => 'Skytten',
            'de' => 'Schütze',
            'el' => 'Τοξότης',
            'eo' => 'Sagitario',
            'es' => 'Sagitario',
            'et' => 'Ambur',
            'eu' => 'Sagitario',
            'fa' => 'قوس',
            'fi' => 'Jousimies',
            'fr' => 'Sagittaire',
            'ga' => 'An Saighdeoir',
            'gl' => 'Saxitario',
            'he' => 'קשת',
            'hi' => 'धनु',
            'hu' => 'Nyilas',
            'id' => 'Sagitarius',
            'it' => 'Sagittario',
            'ja' => '射手座',
            'ko' => '궁수자리',
            'lt' => 'Šaulys',
            'lv' => 'Strēlnieks',
            'ms' => 'Sagittarius',
            'nb' => 'Skytten',
            'nl' => 'Boogschutter',
            'pl' => 'Strzelec',
            'pt' => 'Sagitário',
            'ro' => 'Săgetător',
            'ru' => 'Стрелец',
            'sk' => 'Strelec',
            'sl' => 'Strelec',
            'sq' => 'Shigjetari',
            'sv' => 'Skytten',
            'th' => 'ราศีธนู',
            'tl' => 'Sagittarius',
            'tr' => 'Yay',
            'uk' => 'Стрілець',
            'ur' => 'قوس',
            'zh' => '射手座',
        ),
        'capricorn' => array(
            'en' => 'Capricorn',
            'ar' => 'الجدي',
            'az' => 'Oğlaq',
            'bg' => 'Козирог',
            'bn' => 'মকর',
            'ca' => 'Capricorn',
            'cs' => 'Kozoroh',
            'da' => 'Stenbukken',
            'de' => 'Steinbock',
            'el' => 'Αιγόκερως',
            'eo' => 'Kaprikorno',
            'es' => 'Capricornio',
            'et' => 'Kaljukits',
            'eu' => 'Capricornio',
            'fa' => 'جدی',
            'fi' => 'Kauris',
            'fr' => 'Capricorne',
            'ga' => 'An Gabhar',
            'gl' => 'Capricornio',
            'he' => 'גדי',
            'hi' => 'मकर',
            'hu' => 'Bak',
            'id' => 'Capricorn',
            'it' => 'Capricorno',
            'ja' => '山羊座',
            'ko' => '염소자리',
            'lt' => 'Ožiaragis',
            'lv' => 'Mežāzis',
            'ms' => 'Capricorn',
            'nb' => 'Steinbukken',
            'nl' => 'Steenbok',
            'pl' => 'Koziorożec',
            'pt' => 'Capricórnio',
            'ro' => 'Capricorn',
            'ru' => 'Козерог',
            'sk' => 'Kozorožec',
            'sl' => 'Kozorog',
            'sq' => 'Bricjapi',
            'sv' => 'Stenbocken',
            'th' => 'ราศีมังกร',
            'tl' => 'Capricorn',
            'tr' => 'Oğlak',
            'uk' => 'Козеріг',
            'ur' => 'جدی',
            'zh' => '摩羯座',
        ),
        'aquarius' => array(
            'en' => 'Aquarius',
            'ar' => 'الدلو',
            'az' => 'Dolça',
            'bg' => 'Водолей',
            'bn' => 'কুম্ভ',
            'ca' => 'Aquari',
            'cs' => 'Vodnář',
            'da' => 'Vandmanden',
            'de' => 'Wassermann',
            'el' => 'Υδροχόος',
            'eo' => 'Akvisto',
            'es' => 'Acuario',
            'et' => 'Veevalaja',
            'eu' => 'Akuario',
            'fa' => 'دلو',
            'fi' => 'Vesimies',
            'fr' => 'Verseau',
            'ga' => 'An tUisceadóir',
            'gl' => 'Acuario',
            'he' => 'דלי',
            'hi' => 'कुंभ',
            'hu' => 'Vízöntő',
            'id' => 'Aquarius',
            'it' => 'Acquario',
            'ja' => '水瓶座',
            'ko' => '물병자리',
            'lt' => 'Vandenis',
            'lv' => 'Ūdensvīrs',
            'ms' => 'Aquarius',
            'nb' => 'Vannmannen',
            'nl' => 'Waterman',
            'pl' => 'Wodnik',
            'pt' => 'Aquário',
            'ro' => 'Vărsător',
            'ru' => 'Водолей',
            'sk' => 'Vodnár',
            'sl' => 'Vodnar',
            'sq' => 'Ujori',
            'sv' => 'Vattumannen',
            'th' => 'ราศีกุมภ์',
            'tl' => 'Aquarius',
            'tr' => 'Kova',
            'uk' => 'Водолій',
            'ur' => 'دلو',
            'zh' => '水瓶座',
        ),
        'pisces' => array(
            'en' => 'Pisces',
            'ar' => 'الحوت',
            'az' => 'Balıqlar',
            'bg' => 'Риби',
            'bn' => 'মীন',
            'ca' => 'Peixos',
            'cs' => 'Ryby',
            'da' => 'Fiskene',
            'de' => 'Fische',
            'el' => 'Ιχθύες',
            'eo' => 'Fiŝoj',
            'es' => 'Piscis',
            'et' => 'Kalad',
            'eu' => 'Arrainak',
            'fa' => 'حوت',
            'fi' => 'Kalat',
            'fr' => 'Poissons',
            'ga' => 'Na hÉisc',
            'gl' => 'Piscis',
            'he' => 'דגים',
            'hi' => 'मीन',
            'hu' => 'Halak',
            'id' => 'Pisces',
            'it' => 'Pesci',
            'ja' => '魚座',
            'ko' => '물고기자리',
            'lt' => 'Žuvys',
            'lv' => 'Zivis',
            'ms' => 'Pisces',
            'nb' => 'Fiskene',
            'nl' => 'Vissen',
            'pl' => 'Ryby',
            'pt' => 'Peixes',
            'ro' => 'Pești',
            'ru' => 'Рыбы',
            'sk' => 'Ryby',
            'sl' => 'Ribi',
            'sq' => 'Peshqit',
            'sv' => 'Fiskarna',
            'th' => 'ราศีมีน',
            'tl' => 'Pisces',
            'tr' => 'Balık',
            'uk' => 'Риби',
            'ur' => 'حوت',
            'zh' => '双鱼座',
        ),
    );

    // Return translation or fall back to English
    return $ezhp_translations;
}

/**
 * Get a single translated page title
 *
 * @param string $ezhp_key The translation key.
 * @param string $ezhp_lang The language code.
 * @return string Translated title.
 */
function ezhp_get_page_title($ezhp_key, $ezhp_lang = 'en')
{
    $ezhp_translations = ezhp_get_translated_page_titles();

    if (isset($ezhp_translations[$ezhp_key][$ezhp_lang])) {
        return $ezhp_translations[$ezhp_key][$ezhp_lang];
    }

    // Fallback to English
    if (isset($ezhp_translations[$ezhp_key]['en'])) {
        return $ezhp_translations[$ezhp_key]['en'];
    }

    return $ezhp_key;
}

/**
 * Check if a language uses non-Latin script
 *
 * @param string $ezhp_lang The language code.
 * @return bool True if non-Latin, false otherwise.
 */
function ezhp_is_non_latin_language($ezhp_lang)
{
    $ezhp_non_latin_languages = array(
        'ar', // Arabic
        'bn', // Bengali
        'bg', // Bulgarian (Cyrillic)
        'el', // Greek
        'fa', // Persian/Farsi
        'he', // Hebrew
        'hi', // Hindi
        'ja', // Japanese
        'ko', // Korean
        'ru', // Russian (Cyrillic)
        'th', // Thai
        'uk', // Ukrainian (Cyrillic)
        'ur', // Urdu
        'zh', // Chinese
    );

    return in_array($ezhp_lang, $ezhp_non_latin_languages, true);
}

/**
 * Generate a slug from a translated title
 *
 * @param string $ezhp_title The title to convert to slug.
 * @param string $ezhp_lang The language code (optional).
 * @param string $ezhp_english_slug The English fallback slug (optional).
 * @return string The generated slug.
 */
function ezhp_generate_slug_from_title($ezhp_title, $ezhp_lang = 'en', $ezhp_english_slug = '')
{
    // For non-Latin languages, use language code prefix with English slug
    if (ezhp_is_non_latin_language($ezhp_lang) && !empty($ezhp_english_slug)) {
        return $ezhp_lang . '-' . $ezhp_english_slug;
    }

    // Transliterate non-ASCII characters
    $ezhp_slug = remove_accents($ezhp_title);

    // Convert to lowercase
    $ezhp_slug = strtolower($ezhp_slug);

    // Replace spaces and underscores with hyphens
    $ezhp_slug = preg_replace('/[\s_]+/', '-', $ezhp_slug);

    // Remove any character that isn't alphanumeric or hyphen
    $ezhp_slug = preg_replace('/[^a-z0-9\-]/', '', $ezhp_slug);

    // Remove multiple consecutive hyphens
    $ezhp_slug = preg_replace('/-+/', '-', $ezhp_slug);

    // Trim hyphens from beginning and end
    $ezhp_slug = trim($ezhp_slug, '-');

    // If slug is empty after processing (shouldn't happen for Latin languages, but just in case)
    if (empty($ezhp_slug) && !empty($ezhp_english_slug)) {
        return $ezhp_lang . '-' . $ezhp_english_slug;
    }

    return $ezhp_slug;
}

/**
 * Build the full page title for a zodiac sign daily horoscope
 *
 * @param string $ezhp_sign The zodiac sign key.
 * @param string $ezhp_lang The language code.
 * @return string Full page title.
 */
function ezhp_build_zodiac_page_title($ezhp_sign, $ezhp_lang = 'en')
{
    $ezhp_sign_name = ezhp_get_page_title($ezhp_sign, $ezhp_lang);
    $ezhp_daily_horoscope = ezhp_get_page_title('daily-horoscope', $ezhp_lang);

    // Format: "Aries Daily Horoscope" or localized equivalent
    return $ezhp_sign_name . ' ' . $ezhp_daily_horoscope;
}

/**
 * Build the full page title for a zodiac sign weekly horoscope
 *
 * @param string $ezhp_sign The zodiac sign key.
 * @param string $ezhp_lang The language code.
 * @return string Full page title.
 */
function ezhp_build_weekly_zodiac_page_title($ezhp_sign, $ezhp_lang = 'en')
{
    $ezhp_sign_name = ezhp_get_page_title($ezhp_sign, $ezhp_lang);
    $ezhp_weekly_horoscope = ezhp_get_page_title('weekly-horoscope', $ezhp_lang);

    // Format: "Aries Weekly Horoscope" or localized equivalent
    return $ezhp_sign_name . ' ' . $ezhp_weekly_horoscope;
}

/**
 * Get all automation pages configuration for a language
 *
 * @param string $ezhp_lang The language code.
 * @return array Array of page configurations.
 */
function ezhp_get_automation_pages_config($ezhp_lang = 'en')
{
    $ezhp_daily_horoscope_title = ezhp_get_page_title('daily-horoscope', $ezhp_lang);
    $ezhp_chinese_horoscope_title = ezhp_get_translated_heading('chinese-horoscope', $ezhp_lang);
    $ezhp_numerology_title = ezhp_get_translated_heading('numerology', $ezhp_lang);
    $ezhp_tarot_title = ezhp_get_translated_heading('tarot-reading', $ezhp_lang);
    $ezhp_compatibility_title = ezhp_get_translated_heading('zodiac-compatibility', $ezhp_lang);

    $ezhp_pages = array(
        array(
            'title' => $ezhp_daily_horoscope_title,
            'slug'  => ezhp_generate_slug_from_title($ezhp_daily_horoscope_title, $ezhp_lang, 'daily-horoscope'),
            'block' => 'horoscope-summaries',
            'sign'  => '',
        ),
    );

    // Add zodiac sign pages
    $ezhp_signs = array('aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquarius', 'pisces');

    foreach ($ezhp_signs as $ezhp_sign) {
        $ezhp_title = ezhp_build_zodiac_page_title($ezhp_sign, $ezhp_lang);
        $ezhp_english_slug = $ezhp_sign . '-daily-horoscope';
        $ezhp_pages[] = array(
            'title' => $ezhp_title,
            'slug'  => ezhp_generate_slug_from_title($ezhp_title, $ezhp_lang, $ezhp_english_slug),
            'block' => 'daily-horoscope',
            'sign'  => $ezhp_sign,
        );
    }

    // Add weekly horoscope pages for each zodiac sign
    foreach ($ezhp_signs as $ezhp_sign) {
        $ezhp_title = ezhp_build_weekly_zodiac_page_title($ezhp_sign, $ezhp_lang);
        $ezhp_english_slug = $ezhp_sign . '-weekly-horoscope';
        $ezhp_pages[] = array(
            'title' => $ezhp_title,
            'slug'  => ezhp_generate_slug_from_title($ezhp_title, $ezhp_lang, $ezhp_english_slug),
            'block' => 'weekly-horoscope',
            'sign'  => $ezhp_sign,
        );
    }

    // Add other pages
    $ezhp_pages[] = array(
        'title' => $ezhp_chinese_horoscope_title,
        'slug'  => ezhp_generate_slug_from_title($ezhp_chinese_horoscope_title, $ezhp_lang, 'chinese-horoscope'),
        'block' => 'chinese-horoscope',
        'sign'  => '',
    );

    $ezhp_pages[] = array(
        'title' => $ezhp_numerology_title,
        'slug'  => ezhp_generate_slug_from_title($ezhp_numerology_title, $ezhp_lang, 'numerology'),
        'block' => 'numerology',
        'sign'  => '',
    );

    $ezhp_pages[] = array(
        'title' => $ezhp_tarot_title,
        'slug'  => ezhp_generate_slug_from_title($ezhp_tarot_title, $ezhp_lang, 'tarot-reading'),
        'block' => 'tarot-3card-spread',
        'sign'  => '',
    );

    $ezhp_pages[] = array(
        'title' => $ezhp_compatibility_title,
        'slug'  => ezhp_generate_slug_from_title($ezhp_compatibility_title, $ezhp_lang, 'zodiac-compatibility'),
        'block' => 'zodiac-compatibility',
        'sign'  => '',
    );

    return $ezhp_pages;
}

/**
 * AJAX handler for creating pages
 */
function ezhp_ajax_create_pages()
{
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ezhp_automation_nonce')) {
        wp_send_json_error(array('message' => __('Security check failed.', 'ez-horoscope')));
    }

    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'ez-horoscope')));
    }

    // Get and validate pages data
    if (!isset($_POST['pages']) || !is_array($_POST['pages'])) {
        wp_send_json_error(array('message' => __('No pages data received.', 'ez-horoscope')));
    }

    // Sanitize the pages array - each element is sanitized by ezhp_sanitize_page_data
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each array element is sanitized via ezhp_sanitize_page_data callback
    $ezhp_pages_data = array_map('ezhp_sanitize_page_data', wp_unslash($_POST['pages']));

    // Get the selected language, default to English
    $ezhp_language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en';

    $ezhp_results = array();
    $ezhp_created_count = 0;
    $ezhp_skipped_count = 0;
    $ezhp_error_count = 0;

    // First pass: collect all slugs for the horoscope-summaries block links
    $ezhp_sign_slugs = array();
    foreach ($ezhp_pages_data as $ezhp_page) {
        if (!empty($ezhp_page['sign']) && !empty($ezhp_page['slug']) && $ezhp_page['block'] === 'daily-horoscope') {
            $ezhp_sign_slugs[$ezhp_page['sign']] = $ezhp_page['slug'];
        }
    }

    // Second pass: create pages
    foreach ($ezhp_pages_data as $ezhp_page) {
        // Skip if not marked for creation
        if (empty($ezhp_page['create'])) {
            continue;
        }

        // Validate required fields
        if (empty($ezhp_page['slug'])) {
            $ezhp_results[] = array(
                'title'   => $ezhp_page['title'],
                'status'  => 'error',
                'message' => __('Slug is required.', 'ez-horoscope'),
            );
            $ezhp_error_count++;
            continue;
        }

        if (empty($ezhp_page['title'])) {
            $ezhp_results[] = array(
                'title'   => $ezhp_page['slug'],
                'status'  => 'error',
                'message' => __('Title is required.', 'ez-horoscope'),
            );
            $ezhp_error_count++;
            continue;
        }

        // Generate unique slug if needed
        $ezhp_final_slug = ezhp_get_unique_slug($ezhp_page['slug']);

        // Build the block content
        $ezhp_block_content = ezhp_build_block_content($ezhp_page['block'], $ezhp_page['sign'], $ezhp_sign_slugs, $ezhp_language);

        // Create the page
        $ezhp_post_data = array(
            'post_title'   => sanitize_text_field($ezhp_page['title']),
            'post_name'    => $ezhp_final_slug,
            'post_content' => $ezhp_block_content,
            'post_status'  => 'publish',
            'post_type'    => 'page',
        );

        $ezhp_post_id = wp_insert_post($ezhp_post_data, true);

        if (is_wp_error($ezhp_post_id)) {
            $ezhp_results[] = array(
                'title'   => $ezhp_page['title'],
                'status'  => 'error',
                'message' => $ezhp_post_id->get_error_message(),
            );
            $ezhp_error_count++;
        } else {
            $ezhp_results[] = array(
                'title'   => $ezhp_page['title'],
                'slug'    => $ezhp_final_slug,
                'status'  => 'created',
                'message' => __('Page created successfully.', 'ez-horoscope'),
                'url'     => get_permalink($ezhp_post_id),
                'edit'    => get_edit_post_link($ezhp_post_id, 'raw'),
            );
            $ezhp_created_count++;

            // Throttle between page creations to prevent API rate limiting
            // Default: 500ms (500000 microseconds). Filterable for customization.
            $ezhp_throttle_delay = apply_filters('ezhp_automation_throttle_delay', 500000);
            if ($ezhp_throttle_delay > 0) {
                usleep($ezhp_throttle_delay);
            }
        }
    }

    // Track usage if pages were created
    if ($ezhp_created_count > 0) {
        // Collect created page slugs for tracking
        $ezhp_created_slugs = array();
        foreach ($ezhp_results as $ezhp_result) {
            if ($ezhp_result['status'] === 'created' && !empty($ezhp_result['slug'])) {
                $ezhp_created_slugs[] = $ezhp_result['slug'];
            }
        }

        // Send tracking event
        ezhp_track_usage_event(
            'Automation',
            'PagesCreated',
            $ezhp_language,
            array(
                'pagesCreated' => $ezhp_created_count,
                'language'     => $ezhp_language,
                'pages'        => $ezhp_created_slugs,
            )
        );
    }

    wp_send_json_success(array(
    'results' => $ezhp_results,
    'summary' => array(
        'created' => $ezhp_created_count,
        'skipped' => $ezhp_skipped_count,
        'errors'  => $ezhp_error_count,
    ),
    'successMessage' => ezhp_get_automation_success_message($ezhp_language),
));
}

/**
 * Sanitize page data array
 *
 * @param array $ezhp_page_data Raw page data.
 * @return array Sanitized page data.
 */
function ezhp_sanitize_page_data($ezhp_page_data)
{
    return array(
        'create' => !empty($ezhp_page_data['create']),
        'title'  => isset($ezhp_page_data['title']) ? sanitize_text_field($ezhp_page_data['title']) : '',
        'slug'   => isset($ezhp_page_data['slug']) ? sanitize_title($ezhp_page_data['slug']) : '',
        'block'  => isset($ezhp_page_data['block']) ? sanitize_text_field($ezhp_page_data['block']) : '',
        'sign'   => isset($ezhp_page_data['sign']) ? sanitize_text_field($ezhp_page_data['sign']) : '',
    );
}

/**
 * Get a unique slug, appending -2, -3, etc. if needed
 *
 * @param string $ezhp_slug Desired slug.
 * @return string Unique slug.
 */
function ezhp_get_unique_slug($ezhp_slug)
{
    $ezhp_original_slug = $ezhp_slug;
    $ezhp_counter = 1;

    while (ezhp_slug_exists($ezhp_slug)) {
        $ezhp_counter++;
        $ezhp_slug = $ezhp_original_slug . '-' . $ezhp_counter;
    }

    return $ezhp_slug;
}

/**
 * Check if a slug already exists
 *
 * @param string $ezhp_slug Slug to check.
 * @return bool True if exists, false otherwise.
 */
function ezhp_slug_exists($ezhp_slug)
{
    $ezhp_existing = get_page_by_path($ezhp_slug, OBJECT, 'page');
    return !empty($ezhp_existing);
}

/**
 * Build block content for a page
 *
 * @param string $ezhp_block_type Block type name.
 * @param string $ezhp_sign Zodiac sign (if applicable).
 * @param array  $ezhp_sign_slugs Array of sign => slug mappings for links.
 * @param string $ezhp_language Language code for the block content.
 * @return string Block content.
 */
function ezhp_build_block_content($ezhp_block_type, $ezhp_sign, $ezhp_sign_slugs, $ezhp_language = 'en')
{
    switch ($ezhp_block_type) {
        case 'horoscope-summaries':
            $ezhp_attributes = array('language' => $ezhp_language);

            // Add link attributes for each zodiac sign
            $ezhp_signs = array(
                'aries',
                'taurus',
                'gemini',
                'cancer',
                'leo',
                'virgo',
                'libra',
                'scorpio',
                'sagittarius',
                'capricorn',
                'aquarius',
                'pisces'
            );

            foreach ($ezhp_signs as $ezhp_sign_name) {
                // Add link attribute
                $ezhp_link_key = 'link' . ucfirst($ezhp_sign_name);
                if (isset($ezhp_sign_slugs[$ezhp_sign_name])) {
                    $ezhp_attributes[$ezhp_link_key] = '/' . $ezhp_sign_slugs[$ezhp_sign_name] . '/';
                }

                // Add image attribute
                $ezhp_image_key = 'image' . ucfirst($ezhp_sign_name);
                $ezhp_attributes[$ezhp_image_key] = ezhp_get_default_zodiac_image_url($ezhp_sign_name);
            }

            return '<!-- wp:ezhoroscope/horoscope-summaries ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'daily-horoscope':
            $ezhp_attributes = array(
                'sign'        => $ezhp_sign,
                'language'    => $ezhp_language,
                'heroImageUrl' => ezhp_get_default_zodiac_image_url($ezhp_sign),
            );
            return '<!-- wp:ezhoroscope/daily-horoscope ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'weekly-horoscope':
            $ezhp_attributes = array(
                'sign'        => $ezhp_sign,
                'language'    => $ezhp_language,
                'heroImageUrl' => ezhp_get_default_zodiac_image_url($ezhp_sign),
            );
            return '<!-- wp:ezhoroscope/weekly-horoscope ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'chinese-horoscope':
            $ezhp_attributes = array('language' => $ezhp_language);
            $ezhp_heading_text = ezhp_get_translated_heading('chinese-horoscope', $ezhp_language);
            return '<!-- wp:heading {"level":1} -->' . "\n" .
                '<h1 class="wp-block-heading">' . esc_html($ezhp_heading_text) . '</h1>' . "\n" .
                '<!-- /wp:heading -->' . "\n\n" .
                '<!-- wp:ezhoroscope/chinese-horoscope ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'numerology':
            $ezhp_attributes = array('language' => $ezhp_language);
            $ezhp_heading_text = ezhp_get_translated_heading('numerology', $ezhp_language);
            return '<!-- wp:heading {"level":1} -->' . "\n" .
                '<h1 class="wp-block-heading">' . esc_html($ezhp_heading_text) . '</h1>' . "\n" .
                '<!-- /wp:heading -->' . "\n\n" .
                '<!-- wp:ezhoroscope/numerology ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'tarot-3card-spread':
            $ezhp_attributes = array('language' => $ezhp_language);
            $ezhp_heading_text = ezhp_get_translated_heading('tarot-reading', $ezhp_language);
            return '<!-- wp:heading {"level":1} -->' . "\n" .
                '<h1 class="wp-block-heading">' . esc_html($ezhp_heading_text) . '</h1>' . "\n" .
                '<!-- /wp:heading -->' . "\n\n" .
                '<!-- wp:ezhoroscope/tarot-3card-spread ' . wp_json_encode($ezhp_attributes) . ' /-->';

        case 'zodiac-compatibility':
            $ezhp_attributes = array('language' => $ezhp_language);
            $ezhp_heading_text = ezhp_get_translated_heading('zodiac-compatibility', $ezhp_language);
            return '<!-- wp:heading {"level":1} -->' . "\n" .
                '<h1 class="wp-block-heading">' . esc_html($ezhp_heading_text) . '</h1>' . "\n" .
                '<!-- /wp:heading -->' . "\n\n" .
                '<!-- wp:ezhoroscope/zodiac-compatibility ' . wp_json_encode($ezhp_attributes) . ' /-->';

        default:
            return '';
    }
}

/**
 * Get existing pages that match our automation slugs
 *
 * @param array $ezhp_slugs Array of slugs to check.
 * @return array Array of existing pages with slug as key and page data as value.
 */
function ezhp_get_existing_automation_pages($ezhp_slugs)
{
    $ezhp_existing_pages = array();

    foreach ($ezhp_slugs as $ezhp_slug) {
        $ezhp_page = get_page_by_path($ezhp_slug, OBJECT, 'page');

        if ($ezhp_page) {
            $ezhp_existing_pages[$ezhp_slug] = array(
                'id'    => $ezhp_page->ID,
                'title' => $ezhp_page->post_title,
                'slug'  => $ezhp_page->post_name,
                'url'   => get_permalink($ezhp_page->ID),
                'edit'  => get_edit_post_link($ezhp_page->ID, 'raw'),
            );
        }
    }

    return $ezhp_existing_pages;
}

/**
 * Get all default automation slugs for a language
 *
 * @param string $ezhp_lang The language code.
 * @return array Array of default slugs.
 */
function ezhp_get_default_automation_slugs($ezhp_lang = 'en')
{
    $ezhp_config = ezhp_get_automation_pages_config($ezhp_lang);
    return array_column($ezhp_config, 'slug');
}
