<?php
/**
 * Contentosapp Studio — locale for the contentosapp-studio text domain (admin UI).
 *
 * Must register before any __()/esc_html__() for the domain runs — typically
 * plugins_loaded priority 1. Reads default_language from costudio_settings or
 * contentos_settings.
 *
 * @package Contentosapp_Studio
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'costudio_map_wp_locale_to_supported' ) ) {
	/**
	 * Maps any WordPress locale string to the nearest Contentosapp Studio-supported locale.
	 *
	 * Rules:
	 *  - pt_* → pt_BR
	 *  - es_* → es_ES
	 *  - en_* or anything else → en_US
	 *
	 * @param string $wp_locale
	 * @return string One of: en_US | pt_BR | es_ES
	 */
	function costudio_map_wp_locale_to_supported( string $wp_locale ): string {
		$prefix = strtolower( substr( $wp_locale, 0, 2 ) );
		if ( $prefix === 'pt' ) {
			return 'pt_BR';
		}
		if ( $prefix === 'es' ) {
			return 'es_ES';
		}
		return 'en_US';
	}
}

if ( ! function_exists( 'costudio_seed_language_on_activation' ) ) {
	/**
	 * Seeds default_language in costudio_settings based on the WP site locale.
	 * Called once on plugin activation — does nothing if already set.
	 */
	function costudio_seed_language_on_activation(): void {
		$option  = get_option( 'costudio_settings', array() );
		if ( ! is_array( $option ) ) {
			$option = array();
		}

		// Only seed if not already explicitly set.
		if ( ! empty( $option['default_language'] ) ) {
			return;
		}

		$locale  = get_locale(); // WP site locale at activation time.
		$lang    = costudio_map_wp_locale_to_supported( $locale );

		$option['default_language'] = $lang;
		// Also seed content language to the same value so AI writes in the site language.
		if ( empty( $option['default_content_language'] ) ) {
			$option['default_content_language'] = $lang;
		}

		update_option( 'costudio_settings', $option, false );
	}
}

if ( ! function_exists( 'costudio_resolve_ui_locale_from_options' ) ) {
	/**
	 * @return string Locale like pt_BR, en_US, es_ES, or WP user/site locale.
	 */
	function costudio_resolve_ui_locale_from_options(): string {
		$allowed = array( 'en_US', 'es_ES', 'pt_BR' );
		// Com ContentOS Core ativo, o AJAX de configurações grava em contentos_settings.
		// costudio_settings pode ficar legado (ex.: pt_BR) e não deve prevalecer.
		if ( defined( 'CONTENTOS_VERSION' ) ) {
			$sources = array( 'contentos_settings', 'costudio_settings' );
		} else {
			$sources = array( 'costudio_settings', 'contentos_settings' );
		}
		foreach ( $sources as $opt_key ) {
			// Use false sentinel to distinguish "option doesn't exist" from "option is empty array".
			$opt = get_option( $opt_key, false );
			if ( false === $opt || ! is_array( $opt ) ) {
				continue; // Option not saved yet — try next source.
			}

			// Option exists. Check for an explicit language value.
			if ( isset( $opt['default_language'] ) && '' !== (string) $opt['default_language'] ) {
				$lang = sanitize_text_field( (string) $opt['default_language'] );
				if ( in_array( $lang, $allowed, true ) ) {
					return $lang;
				}
			}

			// Option exists but default_language absent or invalid — use English (plugin default),
			// do NOT fall through to the WP site/user locale.
			return 'en_US';
		}

		// No Contentosapp Studio settings found at all (fresh install) — defer to WP locale.
		return is_admin() ? get_user_locale() : get_locale();
	}

	/**
	 * @param string $locale Current locale from WordPress.
	 * @param string $domain Text domain.
	 * @return string
	 */
	function costudio_filter_plugin_locale_for_domain( $locale, $domain ) {
		if ( 'contentosapp-studio' !== $domain ) {
			return $locale;
		}

		return costudio_resolve_ui_locale_from_options();
	}

	/**
	 * Register plugin_locale filter once.
	 */
	function costudio_register_ui_locale_filter(): void {
		static $registered = false;
		if ( $registered ) {
			return;
		}
		$registered = true;
		add_filter( 'plugin_locale', 'costudio_filter_plugin_locale_for_domain', 10, 2 );
	}
}
