<?php
/**
 * Public Actions plugin file.
 *
 * @package AMVE\Public\Actions
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

add_action( 'init', 'amve_load_public_filters' );
// Add l and n query vars.
add_action(
	'query_vars',
	function( $vars ) {
		$vars[] = 'l';
		$vars[] = 'n';
		return $vars;
	}
);
// Load out-x.php template when l and n query vars are detected.
add_action(
	'template_include',
	function( $template ) {
		if ( ! get_query_var( 'l' ) || ! get_query_var( 'n' ) ) {
			return $template;

		}
		return __DIR__ . '/out-x.php';
	},
	1,
	1
);

/**
 * Load public filters.
 */
function amve_load_public_filters() {
	add_filter( 'the_content', 'amve_insert_video' );
	add_filter( 'get_post_metadata', 'amve_sandbox_iframes', 11, 4 );
	add_filter( 'get_post_metadata', 'amve_fix_tubecorporate_tracking_url', 10, 4 );
	add_filter( 'post_link', 'amve_change_video_link', 10, 2 );
}

/**
 * Filter on 'the_content' to insert the embed player in the content.
 *
 * @since 1.0.0
 *
 * @param string $content The content before the filter.
 * @return string $content The content after the filter.
 */
function amve_insert_video( $content ) {

	global $post;

	if ( ! is_object( $post ) ) {
		return $content;
	}

	$post_source       = get_post_meta( $post->ID, 'partner', true );
	$current_theme     = wp_get_theme();
	$player_in_content = xbox_get_field_value( 'amve-options', 'player-in-content', 'off' );

	if ( is_single() && 'WP-Script' !== $current_theme->get( 'Author' ) && 'on' === $player_in_content ) {
		$amve_partners = AMVE()->get_partners();
		if ( isset( $amve_partners[ $post_source ] ) ) {
			$embed           = get_post_meta( $post->ID, 'embed', true );
			$player_position = xbox_get_field_value( 'amve-options', 'player-position', 'before' );
			if ( 'before' === $player_position ) {
				$content = $embed . $content;
			} else {
				$content = $content . $embed;
			}
		}
	}
	return $content;
}

/**
 * Sandbox 'post_metadata' iframes to prevent clicks and redirections.
 *
 * @since 1.3.5
 *
 * @param string $meta_value  The content before the filter.
 * @param int    $object_id   The post id.
 * @param string $meta_key    The custom post meta key.
 * @param bool   $single      If custom post single or not.
 *
 * @return mixed $meta_value  The content after the filter. Null if not changed.
 */
function amve_sandbox_iframes( $meta_value, $object_id, $meta_key, $single ) {
	if ( 'embed' !== $meta_key ) {
		return $meta_value;
	}

	$meta_cache = wp_cache_get( $object_id, 'post_meta' );
	if ( ! $meta_cache ) {
		$meta_cache = update_meta_cache( 'post', array( $object_id ) );
		$meta_cache = $meta_cache[ $object_id ];
	}
	if ( isset( $meta_cache[ $meta_key ] ) ) {
		if ( $single ) {
			$meta_value = maybe_unserialize( $meta_cache[ $meta_key ][0] );
		} else {
			$meta_value = array_map( 'maybe_unserialize', $meta_cache[ $meta_key ] );
		}
		$meta_value_html_obj           = str_get_html( $meta_value );
		$excluded_sandbox_partners_ids = array(
			'hclips',
			'hdzog',
			'hotmovs',
			'shemalez',
			'thegay',
			'tubepornclassic',
			'txxx',
			'upornia',
			'vjav',
			'voyeurhit',
		);

		$enable_domain_swapping = xbox_get_field_value( 'amve-options', 'amve-enable-domain-swapping', 'off' );
		$swap_domains_from      = explode( "\n", xbox_get_field_value( 'amve-options', 'swap-domain-from', '' ) );
		$swap_domains_to        = explode( "\n", xbox_get_field_value( 'amve-options', 'swap-domain-to', '' ) );

		if ( false !== $meta_value_html_obj ) {
			foreach ( $meta_value_html_obj->find( 'iframe' ) as $iframe ) {
				if ( ! $iframe->src ) {
					continue;
				}

				// Apply domain swapping.
				if ( 'on' === $enable_domain_swapping ) {
					// TODO: extraire ce code pour l'utiliser dans la classe Dom pour modifier tous les domains détectés dans le contenu. Ce qui permettra d'ajouter des règles avec des regex (qui seront expliquées dans la doc).
					foreach ( $swap_domains_from as $index => $domain_from ) {
						$iframe->src = str_replace( $domain_from, $swap_domains_to[ $index ], $iframe->src );
					}
				}

				// Apply iframe sandboxing.
				$partner_id_from_iframe_url = strtolower( str_replace( array( 'www.', 'embed.' ), '', pathinfo( wp_parse_url( $iframe->src, PHP_URL_HOST ), PATHINFO_FILENAME ) ) );

				if ( in_array( $partner_id_from_iframe_url, $excluded_sandbox_partners_ids, true ) ) {
					continue;
				}

				$sandbox_partner_iframes        = xbox_get_field_value( 'amve-options', 'sandbox-' . $partner_id_from_iframe_url . '-iframes', 'off' );
				$sandbox_partner_mobile_iframes = xbox_get_field_value( 'amve-options', 'sandbox-' . $partner_id_from_iframe_url . '-mobile-iframes', 'off' );

				if ( 'on' === $sandbox_partner_iframes ) {
					$iframe->sandbox = 'allow-same-origin allow-scripts';
				}

				if ( 'on' === $sandbox_partner_mobile_iframes && wp_is_mobile() ) {
					$iframe->sandbox = 'allow-same-origin allow-scripts';
				}
			}
			$meta_value = $meta_value_html_obj->__toString();
		}
	}
	return $meta_value;
}


/**
 * Change the link of a video post depending on the outgoing_link option of its saved feed.
 *
 * @param string  $permalink The post's permalink.
 * @param WP_Post $post The post in question.
 * @return string The outgoing link if possible, or the default permalink if not.
 */
function amve_change_video_link( $permalink, $post ) {
	// Return if there is no tracking url.
	$tracking_url = get_post_meta( $post->ID, 'tracking_url', true );
	if ( false === $tracking_url || '' === $tracking_url ) {
		return $permalink;
	}

	// Return if the post doesn't belong to a AMVE saved feed.
	$feed_id = get_post_meta( $post->ID, 'feed', true );
	if ( '' === $feed_id ) {
		return $permalink;
	}

	// Return if the outgoing_links status of the saved feed is not set to true.
	$feed = AMVE()->get_feed( $feed_id );
	if ( ! is_array( $feed ) ) {
		return $permalink;
	}
	if ( ! isset( $feed['outgoing_links'] ) ) {
		return $permalink;
	}
	if ( true !== $feed['outgoing_links'] ) {
		return $permalink;
	}

	$base_url     = get_site_url() . '/out/?&l=' . $post->ID;
	$nonce_action = 'out_' . $post->ID;
	$nonce_name   = 'n';
	return wp_nonce_url( $base_url, $nonce_action, $nonce_name );
}

/**
 * Fix tracking link on videos already imported from TubeCorporate sites.
 *
 * @param mixed  $meta_value The value to return, either a single metadata value or an array of values depending on the value of $single. Default null.
 * @param int    $object_id ID of the object metadata is for.
 * @param string $meta_key Metadata key.
 * @param bool   $single Whether to return only the first value of the specified $meta_key.
 *
 * @return mixed The updated tracking url (string), the original trackink url (string) or any mixed value if meta_key !== 'tracking_url'.
 */
function amve_fix_tubecorporate_tracking_url( $meta_value, $object_id, $meta_key, $single ) {
	if ( 'tracking_url' !== $meta_key ) {
		return $meta_value;
	}

	// Return if partner meta doesn't exist.
	$partner_id = get_post_meta( $object_id, 'partner', true );
	if ( '' === $partner_id ) {
		return $meta_value;
	}

	// Return if partner is not from TubeCorporate.
	$tube_corporate_sites = array(
		'hclips',
		'hdzog',
		'hotmovs',
		'shemalez',
		'thegay',
		'tubepornclassic',
		'txxx',
		'upornia',
		'vjav',
		'voyeurhit',
	);
	if ( ! in_array( $partner_id, $tube_corporate_sites, true ) ) {
		return $meta_value;
	}

	// Return if the affiliate_id TubeCorporate option is not set.
	$partner_option = WPSCORE()->get_product_option( 'AMVE', $partner_id . '_options' );
	if ( ! isset( $partner_option['affiliate_id'] ) ) {
		return $meta_value;
	}

	// Load tracking_url value from the cache.
	$meta_cache = wp_cache_get( $object_id, 'post_meta' );
	if ( ! $meta_cache ) {
		$meta_cache = update_meta_cache( 'post', array( $object_id ) );
		$meta_cache = $meta_cache[ $object_id ];
	}

	if ( ! isset( $meta_cache[ $meta_key ] ) ) {
		return $meta_value;
	}

	if ( $single ) {
		$tracking_url = maybe_unserialize( $meta_cache[ $meta_key ][0] );
	} else {
		$tracking_url = array_map( 'maybe_unserialize', $meta_cache[ $meta_key ] );
	}

	// Fix the tracking url.
	$parsed_url = wp_parse_url( $tracking_url );
	if ( isset( $parsed_url['query'] ) ) {

		parse_str( $parsed_url['query'], $parsed_query );

		if ( ! isset( $parsed_query['source'] ) && isset( $parsed_query['promo'] ) ) {
			return $tracking_url;
		}

		// Remove source param.
		if ( isset( $parsed_query['source'] ) ) {
			unset( $parsed_query['source'] );
		}
		// Add promo param.
		if ( ! isset( $parsed_query['promo'] ) ) {
			$parsed_query['promo'] = sanitize_text_field( $partner_option['affiliate_id'] );
		}
	}
	$scheme             = isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : '//';
	$host               = $parsed_url['host'];
	$path               = $parsed_url['path'];
	$query              = '?' . http_build_query( $parsed_query );
	$fixed_tracking_url = $scheme . $host . $path . $query;

	// Update the tracking url with the fixed one, removing filter to prevent endless loops.
	remove_filter( 'get_post_metadata', 'amve_fix_tubecorporate_tracking_url' );
	update_post_meta( $object_id, 'tracking_url', $fixed_tracking_url );
	add_filter( 'get_post_metadata', 'amve_fix_tubecorporate_tracking_url', 10, 4 );

	// Return the fixed tracking url.
	return $fixed_tracking_url;
}
