<?php
/**
 * UTM tagging helper for outbound tncflipbook.com links (Lite).
 *
 * @package TNC_FlipBook_3D_Lite
 */

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

if ( ! function_exists( 'tncfb3d_utm' ) ) {
	/**
	 * Append UTM tracking parameters to outbound tncflipbook.com /
	 * ideas.tncflipbook.com links. No-op for other hosts and for
	 * non-clickable URLs (REST APIs, asset CDN, JSON-LD) so it is
	 * safe to wrap any URL with this helper.
	 *
	 * @param string $url       Full URL to tag.
	 * @param string $campaign  utm_campaign value (e.g. 'upgrade', 'addons', 'welcome').
	 * @param string $content   Optional utm_content value (specific surface, e.g. 'seo-metabox').
	 * @param string $medium    Optional utm_medium override (defaults to 'wp-admin').
	 * @return string Tagged URL, or the original URL when tagging does not apply.
	 */
	function tncfb3d_utm( $url, $campaign, $content = '', $medium = 'wp-admin' ) {
		if ( empty( $url ) || ! is_string( $url ) ) {
			return $url;
		}

		$host = wp_parse_url( $url, PHP_URL_HOST );
		if ( ! $host ) {
			return $url;
		}

		$host    = strtolower( $host );
		$allowed = array( 'tncflipbook.com', 'www.tncflipbook.com', 'ideas.tncflipbook.com' );
		if ( ! in_array( $host, $allowed, true ) ) {
			return $url;
		}

		// Skip non-clickable surfaces.
		$path = (string) wp_parse_url( $url, PHP_URL_PATH );
		if (
			0 === strpos( $path, '/api/' )
			|| 0 === strpos( $path, '/wp-json/' )
			|| 0 === strpos( $path, '/wp-content/' )
		) {
			return $url;
		}

		$params = array(
			'utm_source'   => 'tnc-flipbook-3d-lite',
			'utm_medium'   => sanitize_key( $medium ),
			'utm_campaign' => sanitize_key( $campaign ),
		);
		if ( '' !== $content ) {
			$params['utm_content'] = sanitize_key( $content );
		}

		return add_query_arg( $params, $url );
	}
}
