<?php
/**
 * Frontend Canonical URL Output
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Frontend;

use SEOvaultSEO\Utils\Formatter;

/**
 * Handles canonical URL output
 */
class Canonical {

	/**
	 * Output canonical URL
	 */
	public static function output() {
		$canonical = self::get_canonical();

		if ( empty( $canonical ) ) {
			return;
		}

		echo '<link rel="canonical" href="' . esc_url( $canonical ) . '" />' . "\n";
	}

	/**
	 * Get canonical URL for current context
	 *
	 * @return string
	 */
	public static function get_canonical() {
		// Singular posts/pages
		if ( is_singular() ) {
			return self::get_singular_canonical();
		}

		// Homepage
		if ( is_front_page() ) {
			return home_url( '/' );
		}

		// Archives
		if ( is_archive() || is_home() ) {
			return self::get_archive_canonical();
		}

		// Default to current URL
		return self::get_current_url();
	}

	/**
	 * Get singular post/page canonical
	 *
	 * @return string
	 */
	private static function get_singular_canonical() {
		$post_id = get_queried_object_id();

		if ( ! $post_id ) {
			return '';
		}

		$custom_canonical = Formatter::get_effective_canonical( $post_id );

		if ( ! empty( $custom_canonical ) ) {
			return $custom_canonical;
		}

		// In manual mode, do not auto-generate — return empty.
		if ( ! \SEOvaultSEO\Compatibility\Detector::is_auto_generation() ) {
			return '';
		}

		return get_permalink( $post_id );
	}

	/**
	 * Get archive canonical URL
	 *
	 * @return string
	 */
	private static function get_archive_canonical() {
		if ( is_category() || is_tag() || is_tax() ) {
			$term_id = get_queried_object_id();
			if ( $term_id ) {
				$custom = \SEOvaultSEO\Core\TermMeta::get_canonical_url( $term_id );
				if ( '' !== $custom ) {
					return $custom;
				}
			}
		}

		if ( is_category() ) {
			return get_category_link( get_queried_object_id() );
		}

		if ( is_tag() ) {
			return get_tag_link( get_queried_object_id() );
		}

		if ( is_tax() ) {
			$link = get_term_link( get_queried_object() );
			return is_wp_error( $link ) ? self::get_current_url() : $link;
		}

		if ( is_author() ) {
			return get_author_posts_url( get_queried_object_id() );
		}

		if ( is_date() ) {
			$year  = (int) get_query_var( 'year' );
			$month = (int) get_query_var( 'monthnum' );
			$day   = (int) get_query_var( 'day' );

			// Pretty permalinks use year/monthnum/day; `?m=YYYYMMDD` uses `m`.
			if ( ! $year ) {
				$m = preg_replace( '/\D/', '', (string) get_query_var( 'm' ) );
				if ( strlen( $m ) >= 4 ) {
					$year = (int) substr( $m, 0, 4 );
				}
				if ( strlen( $m ) >= 6 ) {
					$month = (int) substr( $m, 4, 2 );
				}
				if ( strlen( $m ) >= 8 ) {
					$day = (int) substr( $m, 6, 2 );
				}
			}

			if ( $year && $month && $day ) {
				return get_day_link( $year, $month, $day );
			}
			if ( $year && $month ) {
				return get_month_link( $year, $month );
			}
			if ( $year ) {
				return get_year_link( $year );
			}
		}

		if ( is_post_type_archive() ) {
			return get_post_type_archive_link( get_queried_object()->name );
		}

		return self::get_current_url();
	}

	/**
	 * Get current page URL using the site host (never client-controlled HTTP_HOST).
	 *
	 * @return string
	 */
	private static function get_current_url() {
		$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '/';
		$path        = wp_parse_url( $request_uri, PHP_URL_PATH );

		if ( ! is_string( $path ) || '' === $path ) {
			$path = '/';
		}

		return home_url( $path );
	}
}
