<?php
if (! defined('ABSPATH')) {
    exit;
} final class PufferGo_Languages_Admin
{
    public const PAGE_SLUG = 'puffergo-languages';

    public const ACTION_INSTALL = 'puffergo_install_polylang';

    public const ACTION_ADD = 'puffergo_add_language';

    public const ACTION_REMOVE = 'puffergo_remove_language';

    public const NOTICE_TRANSIENT = 'puffergo_languages_notice';

    public const AUTO_INSTALL_FAILED_STORAGE_KEY = 'puffergoPolylangAutoInstallFailed';

    public const POLYLANG_PLUGIN_FILE = 'polylang/polylang.php';

    public const COMMON_LOCALES = array(array('locale' => 'en_US', 'name' => 'English', 'slug' => 'en'), array('locale' => 'zh_CN', 'name' => 'Chinese (Simplified)', 'slug' => 'zh'), array('locale' => 'zh_TW', 'name' => 'Chinese (Traditional)','slug' => 'zh-tw'), array('locale' => 'ja', 'name' => 'Japanese', 'slug' => 'ja'), array('locale' => 'ko_KR', 'name' => 'Korean', 'slug' => 'ko'), array('locale' => 'es_ES', 'name' => 'Spanish', 'slug' => 'es'), array('locale' => 'fr_FR', 'name' => 'French', 'slug' => 'fr'), array('locale' => 'de_DE', 'name' => 'German', 'slug' => 'de'), array('locale' => 'it_IT', 'name' => 'Italian', 'slug' => 'it'), array('locale' => 'pt_BR', 'name' => 'Portuguese (Brazil)', 'slug' => 'pt-br'), array('locale' => 'ru_RU', 'name' => 'Russian', 'slug' => 'ru'), array('locale' => 'ar', 'name' => 'Arabic', 'slug' => 'ar'), array('locale' => 'nl_NL', 'name' => 'Dutch', 'slug' => 'nl'), );

    public static function init(): void
    {
        add_action('admin_post_' . self::ACTION_INSTALL, array(__CLASS__, 'handle_install'));
        add_action('admin_post_' . self::ACTION_ADD, array(__CLASS__, 'handle_add_language'));
        add_action('admin_post_' . self::ACTION_REMOVE, array(__CLASS__, 'handle_remove_language'));
        add_action('admin_notices', array(__CLASS__, 'maybe_render_notice'));
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_translate_center'));
    }

    public static function enqueue_translate_center(string $hook): void
    {
        if (false === strpos((string) $hook, self::PAGE_SLUG) || ! PufferGo_Polylang::is_active()) {
            return;
        } $plugin_dir = plugin_dir_path(PUFFERGO_PLUGIN_FILE);
        $plugin_url = plugin_dir_url(PUFFERGO_PLUGIN_FILE);
        $asset_file = $plugin_dir . 'build/blocks/translate-center-app/index.asset.php';
        $script_path = $plugin_url . 'build/blocks/translate-center-app/index.js';
        $style_path = $plugin_dir . 'build/blocks/translate-center-app/index.css';
        $asset = file_exists($asset_file) ? include $asset_file : array();
        $dependencies = $asset['dependencies'] ?? array('wp-element', 'wp-api-fetch', 'wp-i18n');
        $version = $asset['version'] ?? (string) filemtime(__FILE__);
        wp_enqueue_script('puffergo-translate-center', $script_path, $dependencies, $version, true);

        if (file_exists($style_path)) {
            wp_enqueue_style('puffergo-translate-center-styles', $plugin_url . 'build/blocks/translate-center-app/index.css', array('puffergo-admin-tailwind', 'wp-components'), $version);
        } wp_localize_script('puffergo-translate-center', 'puffergoTranslateCenter', array('nonce' => wp_create_nonce('wp_rest'), 'restUrl' => rest_url(), ));
    }

    public static function render_page(): void
    {
        echo '<div class="wrap puffergo-admin-wrapper">';
        echo '<h1>' . esc_html__('Languages', 'puffergo') . '</h1>';
        echo '<hr class="wp-header-end" />';

        if (PufferGo_Polylang::is_active()) {
            self::render_active_state();
        } else {
            self::render_install_state();
        } echo '</div>';
    }

    private static function site_profile_locale(): string
    {
        $profile = get_option(PufferGo_Site_Profile::OPTION_KEY, array());
        $lang = is_array($profile) && ! empty($profile['language']) ? (string) $profile['language'] : '';
        $map = array('en' => 'en_US', 'ko' => 'ko_KR', 'es' => 'es_ES', 'fr' => 'fr_FR', 'de' => 'de_DE', 'pt' => 'pt_BR', 'ru' => 'ru_RU', );

        if ('' !== $lang) {
            return $map[ $lang ] ?? $lang;
        }

return 'en_US';
    }

    private static function render_install_state(): void
    {
        $can_install = current_user_can('install_plugins');
        $saved_config = get_option(PufferGo_Polylang_Setup::DEFAULT_LANG_OPTION);
        $saved_locale = is_array($saved_config) ? ($saved_config['locale'] ?? '') : '';
        $is_locked = '' !== $saved_locale;
        $install_just_failed = isset($_GET['puffergo_install_failed']);
        $saved_lang_name = $saved_locale;
        $preselect = $saved_locale ?: self::site_profile_locale();

        foreach (self::COMMON_LOCALES as $l) {
            if ($l['locale'] === $saved_locale) {
                $saved_lang_name = $l['name'];
                break;
            }
        } ?>
		<div style="margin-top:1rem;max-width:760px;background:#fff;border:1px solid #c3c4c7;border-left:4px solid #72aee6;padding:0.5rem 1rem;">
			<p><strong><?php esc_html_e('Multilingual support requires the Polylang plugin.', 'puffergo'); ?></strong></p>
			<ul style="list-style:disc;margin-left:1.5rem;">
				<li><?php esc_html_e('After activation, your existing pages and content are automatically tagged with the primary language — that language becomes the source for translations into every other language.', 'puffergo'); ?></li>
				<li><?php esc_html_e('We recommend completing and polishing all your primary-language content first, then enabling multilingual support and translating everything at once for best results.', 'puffergo'); ?></li>
			</ul>
		</div>

		<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="puffergo-install-polylang-form" style="margin-top:1.5rem;">
			<input type="hidden" name="action" value="<?php echo esc_attr(self::ACTION_INSTALL); ?>" />
			<?php wp_nonce_field(self::ACTION_INSTALL); ?>

			<table class="form-table" role="presentation">
				<tr>
					<th scope="row"><?php esc_html_e('Primary language', 'puffergo'); ?></th>
					<td>
						<?php if ($is_locked) : ?>
							<?php
						    ?>
							<input type="hidden" name="locale" value="<?php echo esc_attr($saved_locale); ?>" />
							<strong><?php echo esc_html($saved_lang_name); ?></strong>
							<p class="description" style="color:#b32d2e;">
								<span class="dashicons dashicons-lock" style="font-size:0.9rem;width:0.9rem;height:0.9rem;vertical-align:middle;" aria-hidden="true"></span>
								<?php esc_html_e('Already configured — cannot be changed.', 'puffergo'); ?>
							</p>
						<?php else : ?>
							<select name="locale" id="puffergo-primary-language" required>
								<option value="" disabled <?php selected('', $preselect); ?>><?php esc_html_e('— Select a language —', 'puffergo'); ?></option>
								<?php foreach (self::COMMON_LOCALES as $lang) : ?>
									<option value="<?php echo esc_attr($lang['locale']); ?>" <?php selected($preselect, $lang['locale']); ?>>
										<?php echo esc_html($lang['name']); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e('You cannot change the primary language after installation, so choose carefully.', 'puffergo'); ?></p>
						<?php endif; ?>
					</td>
				</tr>
			</table>

			<?php if ($can_install) : ?>
				<p class="submit">
					<button type="button" id="puffergo-install-trigger" class="button button-primary">
						<?php esc_html_e('Install & Activate Polylang', 'puffergo'); ?>
					</button>
					<a href="<?php echo esc_url(self::manual_install_url()); ?>" target="_blank" rel="noopener noreferrer" class="button" style="margin-left:0.5rem;">
						<?php esc_html_e('Or install manually →', 'puffergo'); ?>
					</a>
				</p>
				<p class="description" id="puffergo-install-failed-hint" style="display:none;color:#b32d2e;">
					<span class="dashicons dashicons-warning" style="font-size:0.9rem;width:0.9rem;height:0.9rem;vertical-align:middle;" aria-hidden="true"></span>
					<?php esc_html_e('Automatic install failed here before, so this button is disabled. Click "Install manually" — it only takes a moment, then come back to this page and it will pick up automatically.', 'puffergo'); ?>
					<button type="button" id="puffergo-install-failed-reset" class="button-link" style="margin-left:0.25rem;">
						<?php esc_html_e('Try automatic install again', 'puffergo'); ?>
					</button>
				</p>
			<?php else : ?>
				<p>
					<button type="button" class="button button-primary" disabled="disabled"><?php esc_html_e('Install & Activate Polylang', 'puffergo'); ?></button>
				</p>
				<p class="description"><?php esc_html_e('You do not have permission to install plugins. Ask an administrator to install Polylang.', 'puffergo'); ?></p>
			<?php endif; ?>
		</form>

		<dialog id="puffergo-install-confirm-dialog" style="border:1px solid #dba617;border-radius:4px;padding:0;max-width:480px;width:100%;">
			<div style="padding:1.25rem 1.5rem 0;">
				<h2 style="margin:0 0 1rem;font-size:1.1rem;display:flex;align-items:center;gap:0.4rem;">
					<span class="dashicons dashicons-warning" style="color:#dba617;font-size:1.2rem;width:1.2rem;height:1.2rem;" aria-hidden="true"></span>
					<?php
						    echo $is_locked ? esc_html__('Reinstall Polylang', 'puffergo') : esc_html__('Confirm primary language', 'puffergo'); ?>
				</h2>
				<?php if ($is_locked) : ?>
					<p style="margin:0 0 0.75rem;">
						<?php esc_html_e('Your primary language is already configured and locked:', 'puffergo'); ?>
						<strong><?php echo esc_html($saved_lang_name); ?></strong>
					</p>
					<ul style="list-style:disc;margin:0 0 1rem 1.5rem;color:#3c434a;line-height:1.6;">
						<li><?php esc_html_e('Reinstalling Polylang will restore your existing multilingual configuration with the same primary language.', 'puffergo'); ?></li>
						<li>
							<?php
						    echo wp_kses(sprintf(__('The primary language %s. To use a different primary language, you must manually delete all translated content, then reinstall.', 'puffergo'), '<strong>' . esc_html__('cannot be changed', 'puffergo') . '</strong>'), array('strong' => array())); ?>
						</li>
					</ul>
				<?php else : ?>
					<p style="margin:0 0 0.75rem;">
						<?php esc_html_e('You have selected:', 'puffergo'); ?>
						<strong id="puffergo-confirm-lang-name" style="font-size:1rem;"></strong>
					</p>
					<ul style="list-style:disc;margin:0 0 1rem 1.5rem;color:#3c434a;line-height:1.6;">
						<li><?php esc_html_e('All translations will be based on the primary language. Choose the language you are most familiar with and whose content is the most complete.', 'puffergo'); ?></li>
						<li>
							<?php
						    echo wp_kses(sprintf(__('The primary language %s. To use a different primary language, you must manually delete all translated content, then reinstall.', 'puffergo'), '<strong>' . esc_html__('cannot be changed', 'puffergo') . '</strong>'), array('strong' => array())); ?>
						</li>
						<li><?php esc_html_e('For best results, finish and polish all your content in the primary language before enabling multilingual support and translating at once.', 'puffergo'); ?></li>
					</ul>
				<?php endif; ?>
			</div>
			<div style="display:flex;justify-content:flex-end;gap:0.5rem;padding:1rem 1.5rem;border-top:1px solid #f0d080;background:#fef9e7;">
				<button type="button" id="puffergo-install-cancel" class="button">
					<?php esc_html_e('Cancel', 'puffergo'); ?>
				</button>
				<button type="button" id="puffergo-install-confirm" class="button button-primary">
					<?php esc_html_e('Confirm and Install', 'puffergo'); ?>
				</button>
			</div>
		</dialog>

		<script>
		( function () {
			var trigger     = document.getElementById( 'puffergo-install-trigger' );
			var dialog      = document.getElementById( 'puffergo-install-confirm-dialog' );
			var cancel      = document.getElementById( 'puffergo-install-cancel' );
			var confirmBtn  = document.getElementById( 'puffergo-install-confirm' );
			var select      = document.getElementById( 'puffergo-primary-language' );
			var langName    = document.getElementById( 'puffergo-confirm-lang-name' );
			var form        = document.getElementById( 'puffergo-install-polylang-form' );
			var failedHint  = document.getElementById( 'puffergo-install-failed-hint' );
			var failedReset = document.getElementById( 'puffergo-install-failed-reset' );
			var STORAGE_KEY = <?php echo wp_json_encode(self::AUTO_INSTALL_FAILED_STORAGE_KEY); ?>;

			// This page load is the redirect right after a real, just-happened
			// failure — persist it so the button stays disabled on future visits too.
			<?php if ($install_just_failed) : ?>
			try { window.localStorage.setItem( STORAGE_KEY, '1' ); } catch ( e ) {}
			// Drop the query arg so refreshing this page doesn't keep re-announcing
			// "just failed" — the localStorage flag alone carries that forward now.
			if ( window.history && window.history.replaceState ) {
				var cleanUrl = window.location.href.replace( /[?&]puffergo_install_failed=[^&]*/, '' ).replace( /\?&/, '?' ).replace( /\?$/, '' );
				window.history.replaceState( {}, '', cleanUrl );
			}
			<?php endif; ?>

			function isMarkedFailed() {
				try {
					return window.localStorage.getItem( STORAGE_KEY ) === '1';
				} catch ( e ) {
					return false;
				}
			}

			function applyFailedState( failed ) {
				if ( ! trigger ) { return; }
				trigger.disabled = failed;
				trigger.title = failed
					? <?php echo wp_json_encode(__('Automatic install already failed on this browser — use manual install instead.', 'puffergo')); ?>
					: '';
				if ( failedHint ) {
					failedHint.style.display = failed ? '' : 'none';
				}
			}

			applyFailedState( isMarkedFailed() );

			if ( failedReset ) {
				failedReset.addEventListener( 'click', function () {
					try { window.localStorage.removeItem( STORAGE_KEY ); } catch ( e ) {}
					applyFailedState( false );
				} );
			}

			if ( ! trigger || ! dialog ) { return; }

			trigger.addEventListener( 'click', function () {
				// Fresh-install state has a <select>; previously-done state does not.
				if ( langName && select ) {
					langName.textContent = select.options[ select.selectedIndex ].text;
				}
				dialog.showModal();
			} );

			cancel.addEventListener( 'click', function () {
				dialog.close();
			} );

			confirmBtn.addEventListener( 'click', function () {
				dialog.close();

				// Lock the UI so the user can't re-trigger while installing.
				if ( select ) { select.disabled = true; }
				trigger.disabled = true;
				trigger.textContent = '<?php echo esc_js(__('Installing…', 'puffergo')); ?>';
				trigger.style.opacity = '0.7';
				trigger.style.cursor = 'not-allowed';

				form.submit();
			} );

			dialog.addEventListener( 'click', function ( e ) {
				if ( e.target === dialog ) { dialog.close(); }
			} );
		} )();
		</script>
		<?php
    }

    private static function render_active_state(): void
    {
        $default = PufferGo_Polylang::default_language();
        $languages = PufferGo_Polylang::languages(); ?>
		<div style="display:flex;flex-wrap:wrap;gap:3rem;margin-top:1rem;">
			<div style="flex:1 1 420px;min-width:0;">
				<p>
					<strong><?php esc_html_e('Default language:', 'puffergo'); ?></strong>
					<?php echo esc_html(self::language_label($default, $languages)); ?>
					<em>(<?php esc_html_e('read-only', 'puffergo'); ?>)</em>
				</p>

				<h2><?php esc_html_e('Enabled languages', 'puffergo'); ?></h2>
				<table class="wp-list-table widefat striped">
					<tbody>
					<?php foreach ($languages as $lang) : ?>
						<tr>
							<td><?php echo esc_html($lang['name']); ?> <code><?php echo esc_html($lang['slug']); ?></code></td>
							<td style="text-align:right;">
								<?php if ($lang['slug'] === $default) : ?>
									<span class="dashicons dashicons-yes" aria-hidden="true"></span> <?php esc_html_e('Default', 'puffergo'); ?>
								<?php else : ?>
									<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
										onsubmit="return confirm('<?php echo esc_js(__('Remove this language? Its translated pages will be moved to Trash and its translated menus deleted.', 'puffergo')); ?>');"
										style="display:inline;">
										<input type="hidden" name="action" value="<?php echo esc_attr(self::ACTION_REMOVE); ?>" />
										<input type="hidden" name="slug" value="<?php echo esc_attr($lang['slug']); ?>" />
										<?php wp_nonce_field(self::ACTION_REMOVE . '_' . $lang['slug']); ?>
										<button type="submit" class="button-link delete"><?php esc_html_e('Remove', 'puffergo'); ?></button>
									</form>
								<?php endif; ?>
							</td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>

				<?php
        $available = self::addable_languages($languages);

        if (! empty($available)) : ?>
					<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="margin-top:1rem;">
						<input type="hidden" name="action" value="<?php echo esc_attr(self::ACTION_ADD); ?>" />
						<?php wp_nonce_field(self::ACTION_ADD); ?>
						<select name="locale" aria-label="<?php esc_attr_e('Language to add', 'puffergo'); ?>">
							<?php foreach ($available as $lang) : ?>
								<option value="<?php echo esc_attr($lang['locale']); ?>"><?php echo esc_html($lang['name']); ?></option>
							<?php endforeach; ?>
						</select>
						<?php submit_button(__('Add Language', 'puffergo'), 'secondary', 'submit', false); ?>
					</form>
				<?php endif; ?>
			</div>

			<div style="flex:1 1 320px;min-width:0;">
				<h2><?php esc_html_e('String Translation', 'puffergo'); ?></h2>
				<p><?php esc_html_e('Bulk-translate Polylang’s string-translation table (SEO templates, plugin strings, etc.).', 'puffergo'); ?></p>
				<p>
					<a class="button" href="<?php echo esc_url(admin_url('admin.php?page=mlang_strings')); ?>">
						<?php esc_html_e('Go to String Translation page', 'puffergo'); ?> ↗
					</a>
				</p>
			</div>
		</div>

		<?php
        ?>
		<div id="puffergo-translation-context-root" style="display:block;width:100%;margin-top:1.5rem;"></div>

		<hr style="margin:2rem 0;" />

		<?php
        ?>
		<div id="puffergo-translate-center-root" style="display:block;width:100%;"></div>
		<?php
    }

    public static function handle_install(): void
    {
        check_admin_referer(self::ACTION_INSTALL);

        if (! current_user_can('install_plugins')) {
            wp_die(esc_html__('You do not have permission to install plugins.', 'puffergo'));
        } $locale = isset($_POST['locale']) ? sanitize_text_field(wp_unslash($_POST['locale'])) : '';
        $saved = get_option(PufferGo_Polylang_Setup::DEFAULT_LANG_OPTION);
        $is_locked = is_array($saved) && ! empty($saved['locale']);

        if ('' === $locale && ! $is_locked) {
            self::set_notice('error', __('Please select a primary language before installing.', 'puffergo'));
            self::redirect_back();

            return;
        }

if (! $is_locked) {
            update_option(PufferGo_Polylang_Setup::DEFAULT_LANG_OPTION, array('locale' => $locale));
        } $error = self::install_polylang();

        if ('' !== $error) {
            self::set_notice('error', sprintf(__('Could not install Polylang automatically: %s', 'puffergo'), $error), array('url' => self::manual_install_url(), 'label' => __('Install manually from the Plugins screen →', 'puffergo'), ));
            self::redirect_back(array('puffergo_install_failed' => '1'));
        } self::set_notice('success', __('Polylang installed and activated.', 'puffergo'));
        self::redirect_back();
    }

    public static function handle_add_language(): void
    {
        check_admin_referer(self::ACTION_ADD);

        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to manage languages.', 'puffergo'));
        }

if (! PufferGo_Polylang::is_language_admin_ready()) {
            self::set_notice('error', __('Polylang is not fully loaded; please try again.', 'puffergo'));
            self::redirect_back();
        } $locale = isset($_POST['locale']) ? sanitize_text_field(wp_unslash($_POST['locale'])) : '';

        if ('' === $locale) {
            self::set_notice('error', __('No language selected.', 'puffergo'));
            self::redirect_back();
        } $added = PufferGo_Polylang::add_language(array('locale' => $locale));

        if ($added) {
            self::set_notice('success', __('Language added.', 'puffergo'));
        } else {
            self::set_notice('error', __('Could not add that language.', 'puffergo'));
        } self::redirect_back();
    }

    public static function handle_remove_language(): void
    {
        $slug = isset($_POST['slug']) ? sanitize_text_field(wp_unslash($_POST['slug'])) : '';
        check_admin_referer(self::ACTION_REMOVE . '_' . $slug);

        if (! current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to manage languages.', 'puffergo'));
        }

if (! PufferGo_Polylang::is_language_admin_ready() || '' === $slug) {
            self::set_notice('error', __('Polylang is not fully loaded; please try again.', 'puffergo'));
            self::redirect_back();
        }

if ($slug === PufferGo_Polylang::default_language()) {
            self::set_notice('error', __('The default language cannot be removed.', 'puffergo'));
            self::redirect_back();
        } self::cleanup_language($slug);
        self::set_notice('success', sprintf(__('Language “%s” removed. Its translated pages were moved to Trash and can be restored.', 'puffergo'), $slug));
        self::redirect_back();
    }

    private static function cleanup_language(string $slug): void
    {
        $posts = get_posts(array('post_type' => 'any', 'post_status' => 'any', 'posts_per_page' => -1, 'fields' => 'ids', 'lang' => $slug, 'no_found_rows' => true, 'meta_query' => array(array('key' => PufferGo_Page_Translator::META_SOURCE, 'compare' => 'EXISTS', ), ), ));

        foreach ((array) $posts as $post_id) {
            wp_trash_post((int) $post_id);
        } $menus = get_terms(array('taxonomy' => 'nav_menu', 'hide_empty' => false, 'fields' => 'ids', 'meta_query' => array(array('key' => '_puffergo_menu_lang', 'value' => $slug, ), ), ));

        if (is_array($menus)) {
            foreach ($menus as $menu_id) {
                wp_delete_nav_menu((int) $menu_id);
            }
        } $status = get_option(PufferGo_Nav_Menu_Translator::STATUS_OPTION, array());

        if (is_array($status) && isset($status[ $slug ])) {
            unset($status[ $slug ]);
            update_option(PufferGo_Nav_Menu_Translator::STATUS_OPTION, $status, false);
        }

foreach (array_keys(PufferGo_Nav_Menu_Translator::LOCATIONS) as $location) {
            PufferGo_Polylang::set_nav_menu_location($location, $slug, 0);
        } $term_id = PufferGo_Polylang::language_term_id($slug);

        if ($term_id > 0) {
            PufferGo_Polylang::delete_language($term_id);
        }
    }

    private static function install_polylang(): string
    {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        if (is_plugin_active(self::POLYLANG_PLUGIN_FILE)) {
            return '';
        } require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/misc.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

        if (! self::is_polylang_installed()) {
            $api = plugins_api('plugin_information', array('slug' => 'polylang'));

            if (is_wp_error($api)) {
                return $api->get_error_message();
            } $skin = new Automatic_Upgrader_Skin();
            $upgrader = new Plugin_Upgrader($skin);
            $result = $upgrader->install($api->download_link);

            if (is_wp_error($result)) {
                return $result->get_error_message();
            }

if (null === $result || false === $result) {
                $messages = $skin->get_upgrade_messages();

                return ! empty($messages) ? implode(' ', $messages) : __('installation failed (check filesystem permissions).', 'puffergo');
            }
        } $activated = activate_plugin(self::POLYLANG_PLUGIN_FILE);

        if (is_wp_error($activated)) {
            return $activated->get_error_message();
        }

return '';
    }

    private static function is_polylang_installed(): bool
    {
        if (! function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

return array_key_exists(self::POLYLANG_PLUGIN_FILE, get_plugins());
    }

    private static function set_notice(string $type, string $message, ?array $action = null): void
    {
        set_transient(self::NOTICE_TRANSIENT, array('type' => $type, 'message' => $message, 'action' => $action), MINUTE_IN_SECONDS);
    }

    public static function maybe_render_notice(): void
    {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;

        if (! $screen || false === strpos((string) $screen->id, self::PAGE_SLUG)) {
            return;
        } $notice = get_transient(self::NOTICE_TRANSIENT);

        if (! is_array($notice) || empty($notice['message'])) {
            return;
        } delete_transient(self::NOTICE_TRANSIENT);
        $class = ('error' === ($notice['type'] ?? '')) ? 'notice-error' : 'notice-success';
        $action = $notice['action'] ?? null;
        printf('<div class="notice %1$s is-dismissible"><p>%2$s</p>', esc_attr($class), esc_html((string) $notice['message']));

        if (is_array($action) && ! empty($action['url']) && ! empty($action['label'])) {
            printf('<p><a href="%1$s" target="_blank" rel="noopener noreferrer" class="button button-primary">%2$s</a></p>', esc_url($action['url']), esc_html($action['label']));
        } echo '</div>';
    }

    private static function manual_install_url(): string
    {
        return admin_url('plugin-install.php?s=polylang&tab=search&type=term');
    }

    private static function redirect_back(array $extra_query_args = array()): void
    {
        $url = admin_url('admin.php?page=' . self::PAGE_SLUG);

        if (! empty($extra_query_args)) {
            $url = add_query_arg($extra_query_args, $url);
        } wp_safe_redirect($url);
        exit;
    }

    private static function language_label(string $slug, array $languages): string
    {
        foreach ($languages as $lang) {
            if ($lang['slug'] === $slug) {
                return $lang['name'] . ' (' . $lang['slug'] . ')';
            }
        }

return $slug;
    }

    private static function addable_languages(array $enabled): array
    {
        $catalog = PufferGo_Polylang::predefined_languages();

        if (empty($catalog)) {
            $catalog = self::COMMON_LOCALES;
        } $enabled_locales = array();
        $enabled_slugs = array();

        foreach ($enabled as $lang) {
            $enabled_locales[ $lang['locale'] ] = true;
            $enabled_slugs[ $lang['slug'] ] = true;
        } $available = array();

        foreach ($catalog as $lang) {
            if (isset($enabled_locales[ $lang['locale'] ]) || isset($enabled_slugs[ $lang['slug'] ])) {
                continue;
            } $available[] = $lang;
        }

return $available;
    }
}
