<?php
/**
 * Helpers to clear theme transients after option string updates.
 *
 * @package WPR_Translate
 */

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

/**
 * Clear cached select list transients when theme admin strings change.
 *
 * @param string $context String domain context.
 *
 * @return void
 */
function wpr_translate_admin_clear_theme_search_transients( $context ) {
    $context = sanitize_key( (string) $context );

    if ( '' === $context ) {
        return;
    }

    $admin_domain = get_option( 'wpr_translate_theme_admin_strings_domain', '' );
    $admin_domain = is_string( $admin_domain ) ? sanitize_key( $admin_domain ) : '';

    if ( '' === $admin_domain ) {
        $admin_domain = 'wpresidence_admin';
    }

    if ( $context !== $admin_domain && 'wpresidence_admin' !== $context ) {
        // Only clear caches for theme admin strings.
        return;
    }

    $keys = array(
        'wpestate_get_action_select_list',
        'wpestate_get_category_select_list',
        'wpestate_get_city_select_list',
        'wpestate_get_area_select_list',
        'wpestate_get_county_state_select_list',
        'wpestate_get_status_select_list',
        'wpestate_get_features_select_list',
    );

    $language_ids = array();

    if ( function_exists( 'wpr_translate_get_active_languages' ) ) {
        $languages = wpr_translate_get_active_languages( false );

        foreach ( $languages as $language ) {
            if ( ! is_array( $language ) ) {
                continue;
            }

            $slug = '';

            if ( function_exists( 'wpr_translate_get_language_slug' ) ) {
                $slug = wpr_translate_get_language_slug( $language );
            }

            if ( '' === $slug && ! empty( $language['code'] ) ) {
                $slug = sanitize_title( $language['code'] );
            }

            if ( '' !== $slug ) {
                $language_ids[] = sanitize_key( $slug );
            }

            if ( ! empty( $language['code'] ) ) {
                $language_ids[] = sanitize_key( $language['code'] );
            }
        }
    }

    if ( defined( 'ICL_LANGUAGE_CODE' ) && '' !== ICL_LANGUAGE_CODE ) {
        $language_ids[] = sanitize_key( ICL_LANGUAGE_CODE );
    }

    $language_ids = array_values( array_unique( array_filter( $language_ids ) ) );

    foreach ( $keys as $key ) {
        // Clear the base transient without language suffix.
        delete_transient( $key );

        foreach ( $language_ids as $language_id ) {
            delete_transient( $key . '_' . $language_id );
        }
    }
}
