<?php
/**
 * Core plugin bootstrap functions.
 *
 * @package WPR_Translate
 */

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

// Load all plugin modules required for admin and front-end behavior.
require_once WPR_TRANSLATE_PATH . 'includes/admin/menu.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/cache-purge.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/nav-menus-language.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/nav-menus-helpers.php';
require_once WPR_TRANSLATE_PATH . 'includes/nav-menu-translation-sync.php';
require_once WPR_TRANSLATE_PATH . 'includes/nav-menu-locations.php';
require_once WPR_TRANSLATE_PATH . 'includes/nav-menu-locations-frontend.php';
require_once WPR_TRANSLATE_PATH . 'includes/nav-menu-locations-cleanup.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/nav-menus.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/admin-bar-language-switcher.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-meta.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-helpers.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-actions.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-filters.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-columns.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-title.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-badge.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-list-hooks.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/editor-header-language.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/auto-translate-openai.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/auto-translate-google.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/auto-translate-microsoft-azure.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/auto-translate-deepl.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/elementor-translate-builder.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/elementor-translate-text.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/elementor-translate-apply.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/post-editor.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/taxonomy-metabox-filters.php';
require_once WPR_TRANSLATE_PATH . 'includes/widgets/language-switcher.php';
require_once WPR_TRANSLATE_PATH . 'includes/translation-taxonomies.php';
require_once WPR_TRANSLATE_PATH . 'includes/admin/taxonomy-translation.php';
require_once WPR_TRANSLATE_PATH . 'includes/shortcode-compat.php';
require_once WPR_TRANSLATE_PATH . 'includes/elementor-widget-compat.php';
require_once WPR_TRANSLATE_PATH . 'includes/query-filter-helpers.php';
require_once WPR_TRANSLATE_PATH . 'includes/query-filter.php';
require_once WPR_TRANSLATE_PATH . 'includes/adv6-terms-compat.php';
require_once WPR_TRANSLATE_PATH . 'includes/theme-admin-option-filter.php';
require_once WPR_TRANSLATE_PATH . 'includes/seo-tags.php';
require_once WPR_TRANSLATE_PATH . 'includes/debug-frontend.php';

/**
 * Register the plugin hooks and supporting components.
 */
function wpr_translate_bootstrap_plugin() {
    // Track whether the bootstrap already ran.
    static $bootstrapped = false;

    if ( $bootstrapped ) {
        // Avoid registering hooks more than once.
        return;
    }

    // Mark the plugin as initialized to avoid registering hooks multiple times.
    $bootstrapped = true;

    if ( function_exists( 'wpr_translate_prime_custom_fields_preferences_cache' ) ) {
        // Load custom field preferences early for downstream consumers.
        wpr_translate_prime_custom_fields_preferences_cache();
    }

    // Register lifecycle hooks that load translation data and respond to gettext calls.
    add_action( 'init', 'wpr_translate_load_textdomain' );
    add_filter( 'load_textdomain_mofile', 'wpr_translate_override_mofile', 10, 2 );
    add_filter( 'override_load_textdomain', 'wpr_translate_override_load_textdomain', 10, 3 );
    add_filter( 'gettext', 'wpr_translate_filter_gettext', 10, 3 );
    add_filter( 'gettext_with_context', 'wpr_translate_filter_gettext_with_context', 10, 4 );
    add_action( 'after_setup_theme', 'wpr_translate_maybe_reload_theme_text_domains', 20 );
    add_action( 'admin_enqueue_scripts', 'wpr_translate_enqueue_admin_assets' );
    add_action( 'wp_enqueue_scripts', 'wpr_translate_enqueue_public_assets' );
    add_action( 'widgets_init', 'wpr_translate_register_widgets' );
    add_action( 'save_post', 'wpr_translate_handle_save_post_meta_sync', 20, 3 );
    add_action( 'added_post_meta', 'wpr_translate_handle_post_meta_change_sync', 20, 4 );
    add_action( 'updated_post_meta', 'wpr_translate_handle_post_meta_change_sync', 20, 4 );
    add_action( 'deleted_post_meta', 'wpr_translate_handle_post_meta_change_sync', 20, 4 );

    if ( function_exists( 'wpr_translate_admin_bootstrap' ) ) {
        // Activate the admin UI components once WordPress confirms they exist.
        wpr_translate_admin_bootstrap();
    }

    if ( function_exists( 'wpr_translate_language_router_bootstrap' ) ) {
        // Initialize routing so front-end requests resolve using the active language context.
        wpr_translate_language_router_bootstrap();
    }

    if ( function_exists( 'wpr_translate_language_permalinks_bootstrap' ) ) {
        // Prepare permalink helpers to rewrite URLs for language-aware navigation.
        wpr_translate_language_permalinks_bootstrap();
    }

    if ( function_exists( 'wpr_translate_bootstrap_query_filters' ) ) {
        // Align front-end queries with the visitor's language context.
        wpr_translate_bootstrap_query_filters();
    }

    if ( function_exists( 'wpr_translate_bootstrap_shortcode_compat' ) ) {
        // Enable shortcode compatibility helpers.
        wpr_translate_bootstrap_shortcode_compat();
    }

    if ( function_exists( 'wpr_translate_bootstrap_elementor_widget_compat' ) ) {
        // Register Elementor widget translation compatibility.
        wpr_translate_bootstrap_elementor_widget_compat();
    }

    if ( function_exists( 'wpr_translate_bootstrap_theme_widget_strings' ) ) {
        // Load theme widget string registrations.
        wpr_translate_bootstrap_theme_widget_strings();
    }

    if ( function_exists( 'wpr_translate_bootstrap_seo_tags' ) ) {
        // Register SEO tag helpers for translated output.
        wpr_translate_bootstrap_seo_tags();
    }

    if ( function_exists( 'wpr_translate_bootstrap_post_editor_integration' ) ) {
        // Attach post editor integrations for translation management.
        wpr_translate_bootstrap_post_editor_integration();
    }

    if ( function_exists( 'wpr_translate_bootstrap_taxonomy_metabox_filters' ) ) {
        // Enable taxonomy metabox filters for translated terms.
        wpr_translate_bootstrap_taxonomy_metabox_filters();
    }
}

/**
 * Load translation files.
 */
function wpr_translate_load_textdomain() {
    // Load translations bundled with the plugin from the languages directory.
    load_plugin_textdomain( 'wpr-translate', false, dirname( WPR_TRANSLATE_BASENAME ) . '/languages' );
}


/**
 * Enqueue admin scripts and styles for plugin screens.
 *
 * @param string $hook Current admin hook.
 */
function wpr_translate_enqueue_admin_assets( $hook ) {
    // Exit early when the current admin page is unrelated to the plugin.
    if ( false === strpos( (string) $hook, 'wpr-translate' ) ) {
        return;
    }

    // Use file modification times as cache busters so updated assets are reloaded by browsers.
    $style_path     = WPR_TRANSLATE_PLUGIN_ROOT . 'assets/css/admin.css';
    $script_path    = WPR_TRANSLATE_PLUGIN_ROOT . 'assets/js/admin.js';
    $style_version  = file_exists( $style_path ) ? filemtime( $style_path ) : WPR_TRANSLATE_VERSION;
    $script_version = file_exists( $script_path ) ? filemtime( $script_path ) : WPR_TRANSLATE_VERSION;

    // Register the stylesheet that styles the plugin's admin screens.
    wp_enqueue_style(
        'wpr-translate-admin',
        WPR_TRANSLATE_PLUGIN_URL . 'assets/css/admin.css',
        array(),
        $style_version
    );

    // Register the JavaScript bundle that powers admin interactions.
    wp_enqueue_script(
        'wpr-translate-admin',
        WPR_TRANSLATE_PLUGIN_URL . 'assets/js/admin.js',
        array( 'jquery', 'wp-util' ),
        $script_version,
        true
    );

    if ( false !== strpos( (string) $hook, 'wpr-translate-languages' ) ) {
        // Allow users to sort languages via drag and drop in the languages screen.
        wp_enqueue_script( 'jquery-ui-sortable' );

        // Provide UI strings and defaults to the languages management interface.
        $localized = array(
            'strings'  => array(
                'duplicateLanguage'       => __( 'This language is already added.', 'wpr-translate' ),
                'missingCode'             => __( 'Please provide a language code before saving.', 'wpr-translate' ),
                'cannotRemoveLastLanguage' => __( 'At least one language must remain active.', 'wpr-translate' ),
            ),
            'defaults' => array(
                'date_format' => get_option( 'date_format' ),
                'time_format' => get_option( 'time_format' ),
            ),
        );

        wp_localize_script( 'wpr-translate-admin', 'wprTranslateLanguages', $localized );
    }

    if ( false !== strpos( (string) $hook, 'wpr-translate-strings' ) ) {
        // Pass AJAX configuration and messaging for the string translation editor.
        $strings_localized = array(
            'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'wpr_translate_update_string' ),
            'messages' => array(
                'saved' => __( 'Translation saved.', 'wpr-translate' ),
                'error' => __( 'Failed to save translation. Please try again.', 'wpr-translate' ),
            ),
            'saveDelay' => 2000,
            'autoTranslate' => array(
                'ajaxUrl' => admin_url( 'admin-ajax.php' ),
                'nonce'   => wp_create_nonce( 'wpr_translate_auto_translate_strings' ),
                'action'  => 'wpr_translate_auto_translate_strings',
                'strings' => array(
                    'running'         => __( 'Automatic translation is running...', 'wpr-translate' ),
                    'success'         => __( 'Automatic string translation completed.', 'wpr-translate' ),
                    'error'           => __( 'Automatic string translation failed. Please try again.', 'wpr-translate' ),
                    'missingLanguage' => __( 'Please select a target language.', 'wpr-translate' ),
                ),
            ),
        );

        wp_localize_script( 'wpr-translate-admin', 'wprTranslateStrings', $strings_localized );
    }

    if (
        false !== strpos( (string) $hook, 'wpr-translate-settings' )
        || false !== strpos( (string) $hook, 'wpr-translate-custom-fields' )
    ) {
        // Provide AJAX settings for custom field rule updates.
        $custom_fields_localized = array(
            'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'wpr_translate_save_cf_rule' ),
            'messages' => array(
                'saving'   => __( 'Saving…', 'wpr-translate' ),
                'saved'    => __( 'Action updated.', 'wpr-translate' ),
                'reverted' => __( 'Reverted to default action.', 'wpr-translate' ),
                'error'    => __( 'Failed to save action. Please try again.', 'wpr-translate' ),
            ),
        );

        wp_localize_script( 'wpr-translate-admin', 'wprTranslateCustomFields', $custom_fields_localized );
    }

    if ( false !== strpos( (string) $hook, 'wpr-translate-automatic-translation' ) ) {
        // Load and sanitize automatic translation settings.
        $auto_translation_settings = get_option( 'wpr_translate_auto_translation', array() );
        $auto_translation_settings = is_array( $auto_translation_settings ) ? $auto_translation_settings : array();
        $target_language           = isset( $auto_translation_settings['target_language'] ) ? strtolower( sanitize_text_field( $auto_translation_settings['target_language'] ) ) : '';

        // Localize settings so the UI can trigger auto-translation requests.
        $auto_translation_localized = array(
            'ajax'    => array(
                'url'   => admin_url( 'admin-ajax.php' ),
                'nonce' => wp_create_nonce( 'wpr_translate_save_post_types' ),
            ),
            'strings' => array(
                'saving' => __( 'Saving…', 'wpr-translate' ),
                'saved'  => __( 'Preferences saved.', 'wpr-translate' ),
                'error'  => __( 'Could not save preferences. Please try again.', 'wpr-translate' ),
                'running' => __( 'Translating…', 'wpr-translate' ),
                'preparing' => __( 'Collecting posts to translate…', 'wpr-translate' ),
                'complete' => __( 'Automatic translation completed.', 'wpr-translate' ),
                'noPosts' => __( 'No published posts found for the selected post types.', 'wpr-translate' ),
                'translationError' => __( 'Automatic translation failed. Please try again.', 'wpr-translate' ),
                'stopped' => __( 'Automatic translation stopped.', 'wpr-translate' ),
            ),
            'translation' => array(
                'ajax'         => admin_url( 'admin-ajax.php' ),
                'nonce'        => wp_create_nonce( 'wpr_translate_auto_translate_post' ),
                'publishNonce' => wp_create_nonce( 'wpr_translate_auto_translate_post_publish' ),
                'language'     => $target_language,
                'action'       => 'wpr_translate_auto_translate_post_publish',
            ),
            'postsNonce' => wp_create_nonce( 'wpr_translate_get_auto_posts' ),
        );

        wp_localize_script( 'wpr-translate-admin', 'wprTranslateAutoPostTypes', $auto_translation_localized );
    }
}

/**
 * Enqueue public-facing assets needed by the plugin.
 */
function wpr_translate_enqueue_public_assets() {
    // Build asset version from the file modification time.
    $style_path    = WPR_TRANSLATE_PLUGIN_ROOT . 'assets/css/language-switcher.css';
    $style_version = file_exists( $style_path ) ? filemtime( $style_path ) : WPR_TRANSLATE_VERSION;

    // Enqueue styles for the front-end language switcher output.
    wp_enqueue_style(
        'wpr-translate-language-switcher',
        WPR_TRANSLATE_PLUGIN_URL . 'assets/css/language-switcher.css',
        array(),
        $style_version
    );

    // Enqueue the script that appends language data to front-end AJAX requests.
    $script_path    = WPR_TRANSLATE_PLUGIN_ROOT . 'assets/js/public-ajax-language.js';
    $script_version = file_exists( $script_path ) ? filemtime( $script_path ) : WPR_TRANSLATE_VERSION;

    wp_enqueue_script(
        'wpr-translate-ajax-language',
        WPR_TRANSLATE_PLUGIN_URL . 'assets/js/public-ajax-language.js',
        array( 'jquery' ),
        $script_version,
        true
    );

    // Provide the current language code and admin-ajax URL to the script.
    $language_code = '';

    if ( function_exists( 'wpr_translate_get_current_language' ) ) {
        $current_language = wpr_translate_get_current_language();

        if ( is_array( $current_language ) && ! empty( $current_language['code'] ) ) {
            $language_code = sanitize_key( $current_language['code'] );
        }
    }

    if ( '' === $language_code && function_exists( 'wpr_translate_get_context_language' ) ) {
        $context_language = wpr_translate_get_context_language();

        if ( is_array( $context_language ) && ! empty( $context_language['code'] ) ) {
            $language_code = sanitize_key( $context_language['code'] );
        }
    }

    if ( '' === $language_code && function_exists( 'wpestate_get_current_language' ) ) {
        $language_code = sanitize_key( wpestate_get_current_language() );
    }

    if ( '' === $language_code && function_exists( 'wpr_translate_get_default_language' ) ) {
        $default_language = wpr_translate_get_default_language();

        if ( is_array( $default_language ) && ! empty( $default_language['code'] ) ) {
            $language_code = sanitize_key( $default_language['code'] );
        }
    }

    wp_localize_script(
        'wpr-translate-ajax-language',
        'wprTranslateAjaxLang',
        array(
            'lang'    => $language_code,
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        )
    );
}

/**
 * Register the language switcher widget.
 */
function wpr_translate_register_widgets() {
    // Register plugin widgets when the module is available.
    if ( function_exists( 'wpr_translate_register_language_switcher_widget' ) ) {
        // Delegate to the widget module to register its own widget classes.
        wpr_translate_register_language_switcher_widget();
    }
}

// Register a debug filter that can log translation changes.
add_filter( 'gettext', 'wpr_debug_translations', 999, 3 );

/**
 * Record translated strings for the WPResidence domain when debugging translation flows.
 *
 * @param string $translation The translated string value.
 * @param string $text        The original untranslated string.
 * @param string $domain      The domain associated with the string.
 *
 * @return string The translation passed through to WordPress.
 */
function wpr_debug_translations( $translation, $text, $domain ) {
    // Only log when a WPResidence string is altered, keeping the debug log readable.
    if ( $translation !== $text && 'wpresidence' === $domain ) {
        // Only log when a WPResidence string is altered, keeping the debug log readable.
    }
    return $translation;
}
