<?php
defined( 'ABSPATH' ) || exit();

class WPCP_Pro_Features {
	/**
	 * The single instance of the class.
	 *
	 * @var WPCP_Pro_Features
	 * @since 1.0.0
	 */
	protected static $_instance = null;

	/**
	 * @since 1.2.0
	 * WPCP_Pro_Features constructor.
	 */
	public function __construct() {
		add_filter( 'wpcp_acceptance_check', array( __CLASS__, 'acceptance_check' ), 10, 3 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'keywords_to_category' ), 10, 2 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'keywords_to_tags' ), 10, 2 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'maybe_set_canonical_tag' ), 10, 3 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'maybe_set_external_post' ), 10, 3 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'maybe_translate_post' ), 10, 2 );
		add_action( 'wpcp_after_post_publish', array( __CLASS__, 'maybe_set_random_featured_image' ), 10, 2 );

		add_filter( 'wpcp_post_content', array( __CLASS__, 'maybe_search_replace_content' ), 10, 2 );
		add_filter( 'wpcp_post_title', array( __CLASS__, 'maybe_search_replace_content' ), 10, 2 );
		add_action( 'wpcp_post_meta', array( __CLASS__, 'maybe_set_postmeta' ), 10, 3 );

		add_filter( 'wpcp_post_content', array( __CLASS__, 'maybe_set_nofollow' ), 10, 2 );
		add_filter( 'wpcp_feed_article', array( __CLASS__, 'maybe_set_full_content' ), 10, 3 );
		add_filter( 'wpcp_article_search_args', array( __CLASS__, 'wpcp_pro_include_article_search_language' ), 10, 2 );

		add_filter( 'post_link', array( __CLASS__, 'maybe_redirect_external_post' ), 10, 2 );

		add_filter( 'wpcp_article', array( __CLASS__, 'youtube_add_transcript' ), 10, 3 );

		//translate
		add_action( 'wpcp_translate_post_yandex', array( __CLASS__, 'wpcp_translate_post_yandex' ), 10, 3 );
	}

	/**
	 * Acceptance check
	 *
	 * @param $acceptance
	 * @param $article
	 * @param $campaign_id
	 *
	 * @return bool
	 * @since 1.2.0
	 */
	public static function acceptance_check( $acceptance, $article, $campaign_id ) {
		$article        = wp_parse_args( $article, array( 'content' => '' ) );
		$min_words      = wpcp_get_post_meta( $campaign_id, '_min_words', '0' );
		$required_words = wpcp_get_post_meta( $campaign_id, '_required_words', '0' );
		$banned_words   = wpcp_get_post_meta( $campaign_id, '_banned_words', '0' );
		$content        = $article['content'];


		//min words

		if ( ! empty( $min_words ) && str_word_count( $content ) < intval( $min_words ) ) {
			wpcp_logger()->error( sprintf( __( 'Rejecting article because of not having required words count Required [%s] contains [%s]', 'wp-content-pilot-pro' ), $min_words, str_word_count( $content ) ), $campaign_id );

			return false;
		}


		//required words
		$required_words_arr = wpcp_string_to_array( $required_words );
		if ( ! empty( $required_words ) && ! empty( $required_words_arr ) ) {
			foreach ( $required_words_arr as $required_word ) {
				if ( ! wpcp_content_contains_word( $content, $required_word ) ) {
					wpcp_logger()->error( sprintf( __( 'Rejecting for not containing required word [%s]', 'wp-content-pilot-pro' ), $required_word ) );

					return false;
				}
			}
		}

		//banned words
		$banned_words_arr = wpcp_string_to_array( $banned_words );
		if ( ! empty( $banned_words ) && ! empty( $banned_words_arr ) ) {
			foreach ( $banned_words_arr as $banned_word ) {
				if ( wpcp_content_contains_word( $content, $banned_word ) ) {
					wpcp_logger()->error( sprintf( __( 'Rejecting for containing banned word [%s]', 'wp-content-pilot-pro' ), $banned_word ) );

					return false;
				}
			}
		}

		return $acceptance;
	}

	/**
	 * @param $post_id
	 * @param $campaign_id
	 *
	 * @return bool|void
	 * @since 1.2.0
	 */
	public static function keywords_to_category( $post_id, $campaign_id ) {
		$keywords = wpcp_get_post_meta( $campaign_id, '_keyword_to_category', '' );
		$keywords = wpcp_string_to_array( $keywords );
		if ( empty( $keywords ) ) {
			return false;
		}

		$content    = get_post_field( 'post_content', $post_id );
		$categories = [];
		foreach ( $keywords as $keyword ) {
			if ( wpcp_content_contains_word( $content, $keyword ) ) {
				$categories[] = $keyword;
			}
		}

		$terms = wpcp_get_terms( $categories );
		$terms = array_map( 'intval', $terms );
		foreach ( $terms as $term ) {
			wp_set_post_terms( $post_id, $term, 'category', true );
		}
	}

	/**
	 * @param $post_id
	 * @param $campaign_id
	 *
	 * @return bool|void
	 * @since 1.2.0
	 */
	public static function keywords_to_tags( $post_id, $campaign_id ) {
		$keywords = wpcp_get_post_meta( $campaign_id, '_keyword_to_tag', [] );
		$keywords = wpcp_string_to_array( $keywords );
		if ( empty( $keywords ) ) {
			return false;
		}

		$content = get_post_field( 'post_content', $post_id );
		//if(empty( $content) )
		$tags = [];
		foreach ( $keywords as $keyword ) {
			if ( wpcp_content_contains_word( $content, $keyword ) ) {
				$tags[] = $keyword;
			}
		}

		$terms = wpcp_get_terms( $tags, 'post_tag' );

		wp_set_post_terms( $post_id, $terms, 'post_tag', true );
	}

	/**
	 * @param $post_id
	 * @param $campaign_id
	 *
	 * @return bool|void
	 * @since 1.2.0
	 */
	public static function maybe_set_canonical_tag( $post_id, $campaign_id, $article ) {
		$article    = wp_parse_args( $article, array( 'source_url' => '' ) );
		$source_url = $article['source_url'];

		if ( 'on' == wpcp_get_post_meta( $campaign_id, '_canonical_tag', '' ) && ! empty( $source_url ) ) {
			if ( defined( 'WPSEO_VERSION' ) ) {
				add_post_meta( $post_id, '_yoast_wpseo_canonical', $source_url );
			} else {
				add_post_meta( $post_id, 'canonical_url', $source_url );
			}
		}
	}

	/**
	 * @param $post_id
	 * @param $campaign_id
	 *
	 * @return void
	 * @since 1.2.0
	 */
	public static function maybe_set_external_post( $post_id, $campaign_id, $article ) {
		$article    = wp_parse_args( $article, array( 'source_url' => '' ) );
		$source_url = $article['source_url'];

		if ( 'on' == wpcp_get_post_meta( $campaign_id, '_external_post', '' ) && ! empty( $source_url ) ) {
			update_post_meta( $post_id, '_wpcp_external_post', 'on' );
			update_post_meta( $post_id, '_wpcp_external_url', $source_url );
		}
	}

	/**
	 * @param $post_id
	 * @param $campaign_id
	 *
	 * @return bool
	 * @since 1.2.0
	 */
	public static function maybe_translate_post( $post_id, $campaign_id ) {
		$translate_to = wpcp_get_post_meta( $campaign_id, '_translate_to', '' );
		if ( empty( $translate_to ) ) {
			return false;
		}

		$translator = wpcp_get_post_meta( $campaign_id, '_translator', 'yandex' );
		if ( empty( $translator ) ) {
			return false;
		}

		wpcp_logger()->info( __( 'Translating post', 'wp-content-pilot-pro' ), $campaign_id );

		$post = get_post( $post_id );

		$title = wpcp_translate_post( $post->post_title, $translate_to, $translator );

		//if translation is failed no need to proceed
		if ( is_wp_error( $title ) ) {
			return false;
		}

		$content = wpcp_translate_post( $post->post_content, $translate_to, $translator );

		if ( 'on' == wpcp_get_post_meta( $campaign_id, '_excerpt', '' ) ) {
			$excerpt = wpcp_translate_post( $post->post_excerpt, $translate_to, $translator );
		} else {
			$excerpt = $post->post_excerpt;
		}

		if ( $title && $content ) {
			wp_update_post( [
				'ID'           => $post_id,
				'post_title'   => $title,
				'post_content' => $content,
				'post_excerpt' => $excerpt,
			] );
		}

		return true;
	}


	public static function wpcp_translate_post_yandex( $translate_to, $post_id, $campaign_id ) {
		$api_key = wpcp_get_settings( 'yandex_translate_api_key', 'wpcp_settings_misc' );


	}

	public static function wpcp_translate_post_deepl( $post_id, $campaign_id ) {
	}


	/**
	 * @param $content
	 * @param $campaign_id
	 *
	 * @return string
	 * @since 1.2.0
	 */
	public static function maybe_search_replace_content( $content, $campaign_id ) {
		$search_replaces = wpcp_get_post_meta( $campaign_id, '_wpcp_search_replaces', '' );
		if ( is_array( $search_replaces ) && count( $search_replaces ) ) {
			wpcp_logger()->info( __('Running search replace','wp-content-pilot-pro') );

			return wpcp_pro_search_replace( $content, $search_replaces );
		}

		return $content;
	}

	/**
	 * since 1.2.0
	 *
	 * @param $metas
	 * @param $campaign_id
	 * @param $article
	 *
	 * @return mixed
	 */
	public static function maybe_set_postmeta( $metas, $campaign_id, $article ) {
		$post_metas = wpcp_get_post_meta( $campaign_id, '_wpcp_custom_meta_fields', [] );

		$article_tags = [];
		foreach ( $article as $prop => $value ) {
			$article_tags[ '{' . $prop . '}' ] = $value;
		}

		foreach ( $post_metas as $meta_key => $meta_value ) {
			if ( empty( $meta_key ) ) {
				continue;
			}
			$metas[ $meta_key ] = wpcp_pro_search_replace( $meta_value, $article_tags );
		}

		return $metas;
	}

	/**
	 * @param $content
	 * @param $campaign_id
	 *
	 * @return mixed
	 * @since 1.2.0
	 */
	public static function maybe_set_nofollow( $content, $campaign_id ) {
		if ( 'on' == get_post_meta( $campaign_id, '_add_rel_no_follow_target', true ) ) {

			$dom = wpcp_str_get_html( $content );
			foreach ( $dom->find( 'a' ) as $a ) {
				/* @var simple_html_dom_node */
				$a->setAttribute( 'target', '_blank' );
				$a->setAttribute( 'rel', 'nofollow' );
			}

			$content = $dom;
		}

		return $content;
	}

	/**
	 * @param $article
	 * @param $readability WPCP_Readability
	 * @param $campaign_id
	 *
	 * @return mixed
	 * @since 1.2.0
	 */
	public static function maybe_set_full_content( $article, $readability, $campaign_id ) {
		if ( 'on' == get_post_meta( $campaign_id, '_fetch_full_content', true ) ) {
			$article['content'] = $readability->get_content();
		}

		return $article;
	}

	/**
	 * @param $args
	 * @param $campaign_id
	 *
	 * @return mixed
	 * @since 1.2.0
	 */
	public static function wpcp_pro_include_article_search_language( $args, $campaign_id ) {

		$campaign_region = wpcp_get_post_meta( $campaign_id, '_article_region', 'global' );

		if ( $campaign_region != 'global' ) {
			$args['mkt'] = $campaign_region;
			unset( $args['loc'] );
		}

		return $args;
	}

	/**
	 * @param $permalink
	 * @param $post
	 *
	 * @return string
	 * @since 1.2.0
	 */
	public static function maybe_redirect_external_post( $permalink, $post ) {
		if ( 'on' == get_post_meta( $post->ID, '_wpcp_external_post', true ) ) {
			$url = wpcp_get_post_meta( $post->ID, '_wpcp_external_url', true );
			if ( ! empty( $url ) ) {
				return $url;
			}
		}

		return $permalink;
	}

	/**
	 * @param $campaign_id
	 * @param $post_id
	 *
	 *
	 * @since 1.2.0
	 */
	public static function maybe_set_random_featured_image( $post_id, $campaign_id ) {
		global $wpdb;
		if ( true == has_post_thumbnail( $post_id ) ) {
			return;
		}
		if ( 'on' === wpcp_get_post_meta( $campaign_id, '_random_featured_image', 'off' ) ) {
			$post_type     = 'attachment';
			$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}posts WHERE post_type=%s ORDER BY RAND() LIMIT 1", $post_type ) );
			if ( ! empty( $attachment_id ) ) {
				set_post_thumbnail( $post_id, (int) $attachment_id );
			}
		}
	}

	/**
	 * since 1.0.0
	 *
	 * @param $article
	 * @param $campaign_id
	 * @param $campaign_type
	 *
	 * @return mixed
	 * @throws ErrorException
	 */
	public static function youtube_add_transcript( $article, $campaign_id, $campaign_type ) {
		//https://www.youtube.com/watch?v=JBIyPCSV9_M
		if ( 'youtube' == $campaign_type ) {
			$url = $article['source_url'];
			parse_str( parse_url( $url, PHP_URL_QUERY ), $url_arr );
			parse_str( parse_url( $url, PHP_URL_QUERY ), $url_arr );
			$video_id        = $url_arr['v'];
			$video_info_link = 'http://video.google.com/timedtext?type=list&v=' . $video_id . '&id=0&lang=en';
			$curl            = new Curl\Curl();
			$curl->setOpt( CURLOPT_FOLLOWLOCATION, true );
			$curl->setOpt( CURLOPT_TIMEOUT, 30 );
			$curl->setOpt( CURLOPT_RETURNTRANSFER, true );
			$curl->setOpt( CURLOPT_REFERER, 'http://www.bing.com/' );
			$curl->setOpt( CURLOPT_USERAGENT, wpcp_get_random_user_agent() );
			$curl->get( $video_info_link );
			$response = $curl->getResponse();

			if ( isset( $response->track ) ) {
				$curl->setDefaultJsonDecoder();
				$cc_response           = $curl->get( 'http://video.google.com/timedtext?type=track&v=' . $video_id . '&id=0&lang=en' );
				$article['transcript'] = $cc_response && $cc_response->asXML() ? strip_tags( $cc_response->asXML() ) : '';
			}
		}

		return $article;
	}

	/**
	 * Main WPCP_Pro_Features Instance.
	 *
	 * Ensures only one instance of WPCP_Admin is loaded or can be loaded.
	 *
	 * @return WPCP_Pro_Features - Main instance.
	 * @since 1.0.0
	 * @static
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}
}

WPCP_Pro_Features::instance();
