<?php
/**
 * Frontend Twitter Card Output
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Frontend;

use SEOvaultSEO\Utils\Formatter;
use SEOvaultSEO\Core\Options;

/**
 * Handles Twitter card tags output
 */
class Twitter {

	/**
	 * Output Twitter card tags
	 */
	public static function output() {
		if ( ! Options::is_twitter_enabled() ) {
			return;
		}

		// Singular and homepage only.
		if ( ! is_singular() && ! is_front_page() ) {
			return;
		}

		$twitter_card        = self::get_twitter_card();
		$twitter_title       = self::get_twitter_title();
		$twitter_description = self::get_twitter_description();
		$twitter_image       = self::get_twitter_image();
		$twitter_site        = self::get_twitter_site_handle();

		if ( empty( $twitter_title ) && empty( $twitter_description ) && empty( $twitter_image ) ) {
			return;
		}

		echo '<!-- SEOvault AI Twitter Cards -->' . "\n";

		if ( ! empty( $twitter_card ) ) {
			echo '<meta name="twitter:card" content="' . esc_attr( $twitter_card ) . '" />' . "\n";
		}

		if ( ! empty( $twitter_title ) ) {
			echo '<meta name="twitter:title" content="' . esc_attr( $twitter_title ) . '" />' . "\n";
		}

		if ( ! empty( $twitter_description ) ) {
			echo '<meta name="twitter:description" content="' . esc_attr( $twitter_description ) . '" />' . "\n";
		}

		if ( ! empty( $twitter_image ) ) {
			echo '<meta name="twitter:image" content="' . esc_url( $twitter_image ) . '" />' . "\n";
		}

		if ( ! empty( $twitter_site ) ) {
			echo '<meta name="twitter:site" content="' . esc_attr( $twitter_site ) . '" />' . "\n";
		}
	}

	/**
	 * Normalize stored profile URL / username to a Twitter Cards @handle.
	 *
	 * @return string Handle like `@username`, or empty string.
	 */
	public static function get_twitter_site_handle() {
		$value = trim( (string) Options::get_twitter_profile_username() );
		if ( '' === $value ) {
			return '';
		}

		if ( 0 === strpos( $value, '@' ) ) {
			$handle = ltrim( $value, '@' );
			return '' !== $handle ? '@' . sanitize_text_field( $handle ) : '';
		}

		$path = wp_parse_url( $value, PHP_URL_PATH );
		if ( is_string( $path ) && '' !== $path && '/' !== $path ) {
			$segment = strtok( trim( $path, '/' ), '/' );
			$blocked = array( 'home', 'i', 'intent', 'share', 'search', 'explore' );
			if ( is_string( $segment ) && '' !== $segment && ! in_array( strtolower( $segment ), $blocked, true ) ) {
				return '@' . sanitize_text_field( $segment );
			}
		}

		if ( preg_match( '/^[A-Za-z0-9_]{1,15}$/', $value ) ) {
			return '@' . $value;
		}

		return '';
	}

	/**
	 * Get Twitter card type
	 *
	 * @return string
	 */
	private static function get_twitter_card() {
		$card_type     = Options::get_twitter_card_type();
		$twitter_image = self::get_twitter_image();

		// If user selected summary_large_image but no image is available, fall back to summary.
		if ( 'summary_large_image' === $card_type && empty( $twitter_image ) ) {
			return 'summary';
		}

		return $card_type;
	}

	/**
	 * Get Twitter title
	 *
	 * @return string
	 */
	private static function get_twitter_title() {
		if ( is_front_page() ) {
			$home_title = \SEOvaultSEO\Core\Options::get_home_title();
			if ( ! empty( $home_title ) ) {
				return $home_title;
			}
			// In manual mode, do not auto-generate.
			if ( ! \SEOvaultSEO\Compatibility\Detector::is_auto_generation() ) {
				return '';
			}
			return get_bloginfo( 'name' );
		}

		if ( is_singular() ) {
			$post_id = get_queried_object_id();
			if ( $post_id ) {
				return Formatter::get_effective_social_title( $post_id );
			}
		}

		if ( is_category() || is_tag() || is_tax() ) {
			$term_id = get_queried_object_id();
			if ( $term_id ) {
				$og_title = \SEOvaultSEO\Core\TermMeta::get_og_title( $term_id );
				if ( '' !== $og_title ) {
					return \SEOvaultSEO\ReplaceVariables\Manager::do_replace( $og_title );
				}
			}
			return Title::get_title();
		}

		return '';
	}

	/**
	 * Get Twitter description
	 *
	 * @return string
	 */
	private static function get_twitter_description() {
		if ( is_front_page() ) {
			$home_description = \SEOvaultSEO\Core\Options::get_home_description();
			if ( ! empty( $home_description ) ) {
				return $home_description;
			}
			// In manual mode, do not auto-generate.
			if ( ! \SEOvaultSEO\Compatibility\Detector::is_auto_generation() ) {
				return '';
			}
			return get_bloginfo( 'description' );
		}

		if ( is_singular() ) {
			$post_id = get_queried_object_id();
			if ( $post_id ) {
				return Formatter::get_effective_og_description( $post_id );
			}
		}

		if ( is_category() || is_tag() || is_tax() ) {
			$term_id = get_queried_object_id();
			if ( $term_id ) {
				$og_description = \SEOvaultSEO\Core\TermMeta::get_og_description( $term_id );
				if ( '' !== $og_description ) {
					return \SEOvaultSEO\ReplaceVariables\Manager::do_replace( $og_description );
				}
			}
			return Description::get_description();
		}

		return '';
	}

	/**
	 * Get Twitter image
	 *
	 * @return string
	 */
	private static function get_twitter_image() {
		if ( is_singular() ) {
			$post_id = get_queried_object_id();
			if ( $post_id ) {
				return Formatter::get_effective_og_image( $post_id );
			}
		}

		if ( is_front_page() ) {
			return Formatter::get_effective_og_image( 0 );
		}

		if ( is_category() || is_tag() || is_tax() ) {
			$term_id = get_queried_object_id();
			if ( $term_id ) {
				$og_image = \SEOvaultSEO\Core\TermMeta::get_og_image( $term_id );
				if ( '' !== $og_image ) {
					return $og_image;
				}
			}
			return Formatter::get_effective_og_image( 0 );
		}

		return '';
	}
}
