<?php
/**
 * Per-post / per-category geo targeting (falls back to site default).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_geo_country_choices' ) ) {
	/**
	 * ISO 3166-1 alpha-2 choices for geo selects.
	 *
	 * @return array<string, string> code => label
	 */
	function newsai_geo_country_choices( $site_default = '' ) {
		$site_default = newsai_normalize_geo_code( (string) $site_default );
		if ( $site_default === '' && function_exists( 'newsai_get_target_geo' ) ) {
			$site_default = newsai_normalize_geo_code( newsai_get_target_geo() );
		}
		$default_label = $site_default !== ''
			? sprintf(
				/* translators: %s: site-wide default geo code from Settings */
				__( 'Site default (%s)', 'newsroom-ai-assistant' ),
				$site_default
			)
			: __( 'Site default', 'newsroom-ai-assistant' );
		$choices = [
			''   => $default_label,
			'GR' => 'Greece (GR)',
			'CY' => 'Cyprus (CY)',
			'US' => 'USA (US)',
			'GB' => 'UK (GB)',
			'CA' => 'Canada (CA)',
			'AU' => 'Australia (AU)',
			'DE' => 'Germany (DE)',
			'FR' => 'France (FR)',
			'IT' => 'Italy (IT)',
			'ES' => 'Spain (ES)',
			'NL' => 'Netherlands (NL)',
			'BE' => 'Belgium (BE)',
			'CH' => 'Switzerland (CH)',
			'SE' => 'Sweden (SE)',
			'PT' => 'Portugal (PT)',
			'BR' => 'Brazil (BR)',
			'MX' => 'Mexico (MX)',
			'RU' => 'Russia (RU)',
			'JP' => 'Japan (JP)',
			'IN' => 'India (IN)',
			'ID' => 'Indonesia (ID)',
			'ZA' => 'South Africa (ZA)',
			'IL' => 'Israel (IL)',
		];
		return (array) apply_filters( 'newsai_geo_country_choices', $choices );
	}
}

if ( ! function_exists( 'newsai_normalize_geo_code' ) ) {
	/**
	 * @param string $geo Raw geo code.
	 * @return string Uppercase ISO code or empty.
	 */
	function newsai_normalize_geo_code( $geo ) {
		$geo = strtoupper( trim( (string) $geo ) );
		if ( $geo !== '' && preg_match( '/^[A-Z]{2}$/', $geo ) ) {
			return $geo;
		}
		return '';
	}
}

if ( ! function_exists( 'newsai_get_post_target_geo' ) ) {
	/**
	 * Effective market for a post: post meta → primary category → site default.
	 *
	 * @param int $post_id Post ID (0 = current post in editor).
	 * @return string ISO 3166-1 alpha-2.
	 */
	function newsai_get_post_target_geo( $post_id = 0 ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 ) {
			global $post;
			if ( $post instanceof WP_Post ) {
				$post_id = (int) $post->ID;
			}
		}

		if ( $post_id > 0 ) {
			$post_geo = newsai_normalize_geo_code( (string) get_post_meta( $post_id, '_newsai_target_geo', true ) );
			if ( $post_geo !== '' ) {
				return (string) apply_filters( 'newsai_post_target_geo', $post_geo, $post_id );
			}

			$cat_geo = newsai_get_primary_category_geo( $post_id );
			if ( $cat_geo !== '' ) {
				return (string) apply_filters( 'newsai_post_target_geo', $cat_geo, $post_id );
			}
		}

		$site = function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US';
		return (string) apply_filters( 'newsai_post_target_geo', newsai_normalize_geo_code( $site ) ?: 'US', $post_id );
	}
}

if ( ! function_exists( 'newsai_get_primary_category_geo' ) ) {
	/**
	 * @param int $post_id Post ID.
	 * @return string Geo code or empty.
	 */
	function newsai_get_primary_category_geo( $post_id ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 ) {
			return '';
		}

		$term_id = 0;
		if ( class_exists( 'WPSEO_Primary_Term' ) ) {
			$primary = new WPSEO_Primary_Term( 'category', $post_id );
			$term_id = (int) $primary->get_primary_term();
		}
		if ( $term_id < 1 && function_exists( 'rank_math_get_primary_term_id' ) ) {
			$term_id = (int) rank_math_get_primary_term_id( 'category', $post_id );
		}
		if ( $term_id < 1 ) {
			$cats = get_the_category( $post_id );
			if ( ! empty( $cats ) && $cats[0] instanceof WP_Term ) {
				$term_id = (int) $cats[0]->term_id;
			}
		}
		if ( $term_id < 1 ) {
			return '';
		}

		return newsai_normalize_geo_code( (string) get_term_meta( $term_id, '_newsai_target_geo', true ) );
	}
}

if ( ! function_exists( 'newsai_render_geo_select' ) ) {
	/**
	 * @param string $name     Field name.
	 * @param string $selected Selected code.
	 * @param string $id       Optional id attribute.
	 * @param bool   $include_site_default Include empty = site default option.
	 */
	function newsai_render_geo_select( $name, $selected = '', $id = '', $include_site_default = true, $site_default = '' ) {
		$choices = newsai_geo_country_choices( $site_default );
		if ( ! $include_site_default ) {
			unset( $choices[''] );
		}
		$selected = newsai_normalize_geo_code( $selected );
		$id_attr  = $id !== '' ? ' id="' . esc_attr( $id ) . '"' : '';
		echo '<select name="' . esc_attr( $name ) . '"' . $id_attr . ' class="nros-geo-select">';
		foreach ( $choices as $code => $label ) {
			if ( $code === '' && ! $include_site_default ) {
				continue;
			}
			echo '<option value="' . esc_attr( $code ) . '" ' . selected( $selected, $code, false ) . '>' . esc_html( $label ) . '</option>';
		}
		echo '</select>';
	}
}

if ( ! function_exists( 'newsai_category_geo_fields' ) ) {
	function newsai_category_geo_fields( $term ) {
		$val = '';
		if ( $term instanceof WP_Term ) {
			$val = newsai_normalize_geo_code( (string) get_term_meta( $term->term_id, '_newsai_target_geo', true ) );
		}
		?>
		<tr class="form-field">
			<th scope="row"><label for="newsai_category_geo"><?php esc_html_e( 'Target market (Newsroom OS)', 'newsroom-ai-assistant' ); ?></label></th>
			<td>
				<?php newsai_render_geo_select( 'newsai_category_geo', $val, 'newsai_category_geo', true, function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US' ); ?>
				<p class="description"><?php esc_html_e( 'Optional. Posts in this category inherit this market when no per-post override is set.', 'newsroom-ai-assistant' ); ?></p>
			</td>
		</tr>
		<?php
	}
}
add_action( 'category_edit_form_fields', 'newsai_category_geo_fields' );
add_action( 'category_add_form_fields', 'newsai_category_geo_fields' );

if ( ! function_exists( 'newsai_save_category_geo' ) ) {
	function newsai_save_category_geo( $term_id ) {
		if ( ! current_user_can( 'manage_categories' ) ) {
			return;
		}
		$geo = isset( $_POST['newsai_category_geo'] ) ? newsai_normalize_geo_code( wp_unslash( (string) $_POST['newsai_category_geo'] ) ) : '';
		if ( $geo !== '' ) {
			update_term_meta( (int) $term_id, '_newsai_target_geo', $geo );
		} else {
			delete_term_meta( (int) $term_id, '_newsai_target_geo' );
		}
	}
}
add_action( 'created_category', 'newsai_save_category_geo' );
add_action( 'edited_category', 'newsai_save_category_geo' );

if ( ! function_exists( 'nros_get_trend_tokens_for_geo' ) ) {
	/**
	 * Trend tokens for Discover momentum, keyed by geo (transient cache).
	 *
	 * @param string $geo ISO code.
	 * @return list<string>
	 */
	function nros_get_trend_tokens_for_geo( $geo ) {
		$geo = newsai_normalize_geo_code( $geo );
		if ( $geo === '' ) {
			$geo = function_exists( 'newsai_get_target_geo' ) ? newsai_get_target_geo() : 'US';
		}

		$global = get_option( function_exists( 'nros_discover_score_option_key' ) ? nros_discover_score_option_key() : 'nros_discover_trend_tokens', [] );
		if ( is_array( $global ) && ( $global['geo'] ?? '' ) === $geo && ! empty( $global['tokens'] ) && is_array( $global['tokens'] ) ) {
			return array_values( $global['tokens'] );
		}

		$tkey   = 'nros_trend_tokens_' . strtolower( $geo );
		$cached = get_transient( $tkey );
		if ( is_array( $cached ) && $cached !== [] ) {
			return $cached;
		}

		$titles = [];
		if ( function_exists( 'newsai_google_trends_get_items' ) ) {
			$result = newsai_google_trends_get_items( $geo, 20 );
			if ( ! is_wp_error( $result ) && ! empty( $result['items'] ) ) {
				foreach ( (array) $result['items'] as $item ) {
					$t = trim( (string) ( $item['title'] ?? '' ) );
					if ( $t !== '' ) {
						$titles[] = $t;
					}
				}
			}
		} elseif ( function_exists( 'newsai_ai_fetch_trends_titles' ) ) {
			$titles = newsai_ai_fetch_trends_titles( $geo );
		}
		if ( ! is_array( $titles ) ) {
			$titles = [];
		}

		$tokens = function_exists( 'nros_discover_build_trend_tokens' ) ? nros_discover_build_trend_tokens( $titles ) : [];
		if ( count( $tokens ) > 80 ) {
			$tokens = array_slice( $tokens, 0, 80 );
		}
		if ( $tokens !== [] ) {
			set_transient( $tkey, $tokens, 5 * MINUTE_IN_SECONDS );
		}
		return $tokens;
	}
}
