<?php
/**
 * Itunes Class
 *
 * @package     WP Content Pilot Pro
 * @subpackage  Feed
 * @copyright   Copyright (c) 2019, MD Sultan Nasir Uddin(manikdrmc@gmail.com)
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.1.0
 */

defined( 'ABSPATH' ) || exit();

class WPCP_Itunes extends WPCP_Module {
	/**
	 * The single instance of the class
	 *
	 * @var $this ;
	 */
	protected static $_instance = null;

	/**
	 * WPCP_Itunes constructor.
	 */
	public function __construct() {
		add_action( 'wpcp_itunes_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
		add_action( 'wpcp_itunes_campaign_options_meta_fields', 'wpcp_keyword_field' );
		parent::__construct( 'itunes' );
	}

	/**
	 * @return string
	 */
	public function get_module_icon() {
		return '';
	}

	/**
	 * @return array
	 * @since 1.1.0
	 */
	public function get_template_tags() {
		return array(
			'title'                  => __( 'Title', 'wp-content-pilot-pro' ),
			'excerpt'                => __( 'Summary', 'wp-content-pilot-pro' ),
			'content'                => __( 'Content', 'wp-content-pilot-pro' ),
			'image_url'              => __( 'Main image url', 'wp-content-pilot-pro' ),
			'source_url'             => __( 'Source link', 'wp-content-pilot-pro' ),
			'affiliate_url'          => __( 'Affiliate Url', 'wp-content-pilot-pro' ),
			'date'                   => __( 'Published date', 'wp-content-pilot-pro' ),
			'item_id'                => __( 'Item ID', 'wp-content-pilot-pro' ),
			'item_previewUrl'        => __( 'Item preview URL', 'wp-content-pilot-pro' ),
			'item_artistName'        => __( 'Item artist name', 'wp-content-pilot-pro' ),
			'item_trackName'         => __( 'Item track name', 'wp-content-pilot-pro' ),
			'item_price'             => __( 'Item price', 'wp-content-pilot-pro' ),
			'item_country'           => __( 'Item country', 'wp-content-pilot-pro' ),
			'item_currency'          => __( 'Item currency', 'wp-content-pilot-pro' ),
			'item_rating'            => __( 'Item rating', 'wp-content-pilot-pro' ),
			'item_rating_counts'     => __( 'Item rating counts', 'wp-content-pilot-pro' ),
			'item_releaseDate'       => __( 'Item release date', 'wp-content-pilot-pro' ),
			'item_time'              => __( 'Item time', 'wp-content-pilot-pro' ),
			'item_collectionId'      => __( 'Item collection ID. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_collectionName'    => __( 'Item collection name. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_collectionViewUrl' => __( 'Item collection view URL. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_artistId'          => __( 'Item artist ID. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_collectionPrice'   => __( 'Item collection price. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_trackCount'        => __( 'Item track count. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_trackNumber'       => __( 'Item track number. Only for song media type.', 'wp-content-pilot-pro' ),
			'item_artistViewUrl'     => __( 'Item artist view URL. Only for song and software media type.', 'wp-content-pilot-pro' ),
			'item_supportedDevices'  => __( 'Item supported devices. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_fileSize'          => __( 'Item file size. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_sellerUrl'         => __( 'Item seller URL. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_version'           => __( 'Item version. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_primaryGenreName'  => __( 'Item primary genre name. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_screenshotUrls'    => __( 'Item screenshot URLs. Only for software media type.', 'wp-content-pilot-pro' ),
			'item_screenshot'        => __( 'Item screenshot. Only for software media type.', 'wp-content-pilot-pro' ),
		);
	}

	/**
	 * @return string
	 * @since 1.1.0
	 */
	public function get_default_template() {
		$template
			= <<<EOT
[embed]{item_previewUrl}[/embed]<br>
Title: {title}<br>
Price: {item_price}<br>
{content}<br>
<a href="{source_url}">Source</a>
EOT;

		return $template;
	}

	/**
	 * @param $post
	 */
	public function add_campaign_option_fields( $post ) {
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Media Type', 'wp-content-pilot-pro' ),
			'name'    => '_media_type',
			'options' => array(
				'music'      => __( 'Music', 'wp-content-pilot-pro' ),
				'movie'      => __( 'Movie', 'wp-content-pilot-pro' ),
				'podcast'    => __( 'Podcast', 'wp-content-pilot-pro' ),
				'musicVideo' => __( 'Music Video', 'wp-content-pilot-pro' ),
				'audiobook'  => __( 'Audio Book', 'wp-content-pilot-pro' ),
				'shortFilm'  => __( 'Short Film', 'wp-content-pilot-pro' ),
				'tvShow'     => __( 'TV Show', 'wp-content-pilot-pro' ),
				'software'   => __( 'Software', 'wp-content-pilot-pro' ),
				'ebook'      => __( 'eBook', 'wp-content-pilot-pro' ),
			)
		) );
	}

	/**
	 * @param $campaign_id
	 * @param $posted
	 */
	public function save_campaign_meta( $campaign_id, $posted ) {
		update_post_meta( $campaign_id, '_media_type', empty( $posted['_media_type'] ) ? '' : sanitize_text_field( $posted['_media_type'] ) );

	}

	/**
	 * @param $sections
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_section( $sections ) {
		$sections[] = [
			'id'    => 'wpcp_settings_itunes',
			'title' => __( 'Itunes Settings', 'wp-content-pilot-pro' )
		];

		return $sections;
	}

	/**
	 * @param $fields
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_fields( $fields ) {
		$fields['wpcp_settings_itunes'] = [
			[
				'name'    => 'affiliate_id',
				'label'   => __( 'Affiliate ID (Token)', 'wp-content-pilot-pro' ),
				'desc'    => sprintf( __( 'Learn to create your ITunes Affiliate ID(Token) <a href="%s" target="_blank">here</a>.', 'wp-content-pilot-pro' ), 'https://www.pluginever.com/docs/wp-content-pilot/itunes-campaign-settings/' ),
				'type'    => 'password',
				'default' => ''
			]
		];

		return $fields;
	}


	/**
	 * @param $campaign_id
	 *
	 * @return mixed|void
	 * @since 1.1.0
	 */
	public function get_post( $campaign_id ) {
		wpcp_logger()->info( __( 'Loaded Itunes Campaign', 'wp-content-pilot-pro' ), $campaign_id );
		$affiliate_id = wpcp_get_settings( 'affiliate_id', 'wpcp_settings_itunes' );

		wpcp_logger()->info( __( 'Checking Itunes affiliate id for affiliation', 'wp-content-pilot-pro' ), $campaign_id );
		if ( empty( $affiliate_id ) ) {

			$itunes_settings_url = admin_url( '/edit.php?post_type=wp_content_pilot&page=wpcp-settings#wpcp_settings_itunes' );

			$notice = __( sprintf( 'Itnues affiliate id is not set.So, the campaign won\'t get any revenue. To get revenue please set affiliate id from <a href="%s">here</a>', $itunes_settings_url ), 'wp-content-pilot-pro' );

			wpcp_admin_notice( $notice );
		}

		$keywords = $this->get_campaign_meta( $campaign_id );
		if ( empty( $keywords ) ) {
			return new WP_Error( 'missing-data', __( 'Campaign do not have keyword to proceed, please set keyword', 'wp-content-pilot-pro' ) );
		}

		foreach ( $keywords as $keyword ) {

			wpcp_logger()->info( sprintf( __( 'Looping through keywords [ %s ]', 'wp-content-pilot-pro' ), $keyword ) );

			wpcp_logger()->info( __( 'Check either the keyword is already deactivated.', 'wp-content-pilot-pro' ), $campaign_id );
			if ( $this->is_deactivated_key( $campaign_id, $keyword ) ) {
				wpcp_logger()->info( sprintf( __( 'The keyword is deactivated for 1 hr because last time could not find any article with keyword [%s]', 'wp-content-pilot-pro' ), $keyword ), $campaign_id );
				continue;
			}

			$page_key    = sanitize_key( '_page_' . $campaign_id . '_' . md5( $keyword ) );
			$page_number = wpcp_get_post_meta( $campaign_id, $page_key, 0 );
			$api_url     = 'https://itunes.apple.com/search';
			$query_args  = array(
				'term'   => $keyword,
				'media'  => wpcp_get_post_meta( $this->campaign_id, '_media_type', 'all' ),
				'offset' => $page_number,
				'limit'  => 1,
			);
			$endpoint    = add_query_arg( $query_args, $api_url );

			wpcp_logger()->info( sprintf( __( 'Searching page url [%s]', 'wp-content-pilot-pro' ), $endpoint ), $campaign_id );
			$curl = $this->setup_curl();
			$curl->setDefaultJsonDecoder( true );
			$curl->setHeader( 'Content-Type', 'application/json' );
			$curl->get( $endpoint );

			wpcp_logger()->info( __( 'Getting response from request', 'wp-content-pilot-pro' ), $campaign_id );
			$response = (object) json_decode( $curl->getResponse(), true );

			if ( $curl->isError() ) {
				wpcp_logger()->error( $curl->getErrorMessage(), $campaign_id );
				$this->deactivate_key( $campaign_id, $keyword );
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				continue;
			}

			if ( empty( $response->results ) || ! is_array( $response->results ) ) {
				$notice = __( 'Could find any items, disabling keyword for an hour', 'wp-content-pilot-pro' );
				wpcp_logger()->error( $notice, $campaign_id );
				$this->deactivate_key( $campaign_id, $keyword );
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				continue;
			}

			wpcp_logger()->info( __( 'Getting valid content from response', 'wp-content-pilot-pro' ), $campaign_id );
			$item = (object) reset( $response->results );

			$article = [];

			wpcp_logger()->info( __( 'Extracting source url', 'wp-content-pilot-pro' ), $campaign_id );
			if ( ! ( isset( $item->wrapperType ) && $item->wrapperType == 'audiobook' ) ) {

				$source_url = $item->trackViewUrl;
				$id         = $item->trackId;

				$article['source_url'] = $item->trackViewUrl;

			} else {

				$source_url = $item->collectionViewUrl;
				$id         = $item->collectionId;

				$article['source_url'] = $item->collectionViewUrl;

			}


			$article['item_id']       = $id;
			$article['source_url']    = $source_url;
			$article['affiliate_url'] = ( ! empty( $affiliate_id ) ) ? $source_url . '&at=' . $affiliate_id : $source_url;


			//check if the clean title is checked and perform title cleaning
			$check_clean_title = wpcp_get_post_meta( $campaign_id, '_clean_title', 'off' );

			if ( 'on' == $check_clean_title ) {
				wpcp_logger()->info( __( 'Cleaning title', 'wp-content-pilot-pro' ), $campaign_id );

				if ( isset( $item->kind ) && ( ( $item->kind == 'song' ) || ( $item->kind == 'feature-movie' ) || ( $item->kind == 'podcast' ) || ( $item->kind == 'music-video' ) || ( $item->kind == 'tv-episode' ) || ( $item->kind == 'ebook' ) || ( $item->kind == 'software' ) ) ) {

					$title = wpcp_clean_title( $item->trackName );

				} elseif ( isset( $item->kind ) && $item->kind == 'audiobook' ) {

					$title = wpcp_clean_title( $item->collectionName );
				}
			} else {
				if ( isset( $item->kind ) && ( ( $item->kind == 'song' ) || ( $item->kind == 'feature-movie' ) || ( $item->kind == 'podcast' ) || ( $item->kind == 'music-video' ) || ( $item->kind == 'tv-episode' ) || ( $item->kind == 'ebook' ) || ( $item->kind == 'software' ) ) ) {

					$title = html_entity_decode( $item->trackName, ENT_QUOTES );

				} elseif ( isset( $item->kind ) && $item->kind == 'audiobook' ) {

					$title = html_entity_decode( $item->collectionName, ENT_QUOTES );

				}
			}

			// adaption
			if ( isset( $item->kind ) && $item->kind == 'song' ) {
				wpcp_logger()->info( __( 'Extracting contents from song and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content'] = $item->trackName;
				$article['title']   = $title;

				$article['item_collectionId']      = $item->collectionId;
				$article['item_collectionName']    = $item->collectionName;
				$article['item_collectionViewUrl'] = $item->collectionViewUrl;

				$article['item_previewUrl'] = $item->previewUrl;

				$article['image_url'] = str_replace( '100x100', '600x600', $item->artworkUrl100 );

				$article['item_artistId']      = $item->artistId;
				$article['item_artistName']    = $item->artistName;
				$article['item_trackName']     = $item->trackName;
				$article['item_artistViewUrl'] = $item->artistViewUrl;

				$article['item_price']           = wpcp_price( $item->trackPrice, $item->currency );
				$article['item_collectionPrice'] = wpcp_price( $item->collectionPrice, $item->currency );

				$article['item_trackCount']  = $item->trackCount;
				$article['item_trackNumber'] = $item->trackNumber;

				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';

			} elseif ( isset( $item->kind ) && $item->kind == 'feature-movie' ) {
				wpcp_logger()->info( __( 'Extracting contents from feature movie and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->longDescription;
				$article['title']                 = $title;
				$article['item_previewUrl']       = $item->previewUrl;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->trackPrice;
				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';

			} elseif ( isset( $item->kind ) && $item->kind == 'podcast' ) {
				wpcp_logger()->info( __( 'Extracting contents from podcast and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content'] = $item->trackName;
				$article['title']   = $title;
				//$article['item_previewUrl']       = $item->trackViewUrl;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->trackPrice;
				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';


			} elseif ( isset( $item->kind ) && $item->kind == 'music-video' ) {
				wpcp_logger()->info( __( 'Extracting contents from music video and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->trackName;
				$article['title']                 = $title;
				$article['item_previewUrl']       = $item->previewUrl;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->trackPrice;
				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';

			} elseif ( isset( $item->wrapperType ) && $item->wrapperType == 'audiobook' ) {
				wpcp_logger()->info( __( 'Extracting contents from feature audio book and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->description;
				$article['title']                 = $title;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_trackName']        = $item->collectionName;
				$article['item_price']            = $item->collectionPrice;
				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_previewUrl']       = $item->previewUrl;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';


			} elseif ( isset( $item->kind ) && $item->kind == 'tv-episode' ) {
				wpcp_logger()->info( __( 'Extracting contents from feature tv episode and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->longDescription;
				$article['title']                 = $title;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_previewUrl']       = $item->previewUrl;
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->trackPrice;
				$article['item_country']          = $item->country;
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';


			} elseif ( isset( $item->kind ) && $item->kind == 'ebook' ) {
				wpcp_logger()->info( __( 'Extracting contents from feature e-book and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->description;
				$article['title']                 = $title;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_previewUrl']       = $item->previewUrl;
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->price;
				$article['item_country']          = isset( $item->country ) ? $item->country : '';
				$article['item_currency']         = $item->currency;
				$article['item_rating']           = isset( $item->averageUserRating ) ? $item->averageUserRating : '';
				$article['item_rating_counts']    = isset( $item->userRatingCount ) ? $item->userRatingCount : '';
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_supportedDevices'] = isset( $item->supportedDevices ) ? $item->supportedDevices : '';
				$article['item_fileSize']         = isset( $item->fileSize ) ? number_format( ( $item->fileSizeBytes ) / 1024, 2 ) : '';
				$article['item_version']          = isset( $item->version ) ? $item->version : '';
				$article['item_primaryGenreName'] = isset( $item->primaryGenreName ) ? $item->primaryGenreName : '';
				$article['item_screenshotUrls']   = isset( $item->screenshotUrls ) ? implode( ',', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $item->screenshotUrls ) ? implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls ) : '';
				$article['item_screenshot']       = isset( $article['item_screenshot'] ) ? '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">' : '';

			} elseif ( isset( $item->kind ) && $item->kind == 'software' ) {
				wpcp_logger()->info( __( 'Extracting contents from feature software and combining them', 'wp-content-pilot-pro' ), $campaign_id );

				$article['content']               = $item->description;
				$article['title']                 = $title;
				$article['image_url']             = str_replace( '100x100', '600x600', $item->artworkUrl100 );
				$article['item_artistName']       = $item->artistName;
				$article['item_artistViewUrl']    = $item->artistViewUrl;
				$article['item_previewUrl']       = isset( $item->previewUrl ) ? $item->previewUrl : '';
				$article['item_supportedDevices'] = implode( ',', $item->supportedDevices );
				$article['item_fileSize']         = number_format( ( $item->fileSizeBytes ) / 1024, 2 );
				$article['item_sellerUrl']        = isset( $item->sellerUrl ) ? $item->sellerUrl : '';
				$article['item_trackName']        = $item->trackName;
				$article['item_price']            = $item->price;
				$article['item_currency']         = $item->currency;
				$article['item_version']          = $item->version;
				$article['item_primaryGenreName'] = $item->primaryGenreName;
				$article['item_rating']           = $item->averageUserRating;
				$article['item_rating_counts']    = $item->userRatingCount;
				$article['item_screenshotUrls']   = implode( ',', $item->screenshotUrls );
				$article['item_screenshot']       = implode( '"><br><img style="width:300px;padding:5px" src="', $item->screenshotUrls );
				$article['item_screenshot']       = '<img  style="width:300px;" src="' . $article['item_screenshot'] . '">';

			}

			//Release date
			wpcp_logger()->info( __( 'Extracting release date and combining it with other parts', 'wp-content-pilot-pro' ), $campaign_id );
			if ( isset( $item->releaseDate ) ) {
				$article['item_releaseDate'] = $item->releaseDate;
				$article['item_releaseDate'] = str_replace( 'T', ' ', $article['item_releaseDate'] );
				$article['item_releaseDate'] = str_replace( 'Z', '', $article['item_releaseDate'] );
			}

			//Time
			wpcp_logger()->info( __( 'Extracting track times and combining it with other parts', 'wp-content-pilot-pro' ), $campaign_id );
			if ( isset( $item->trackTimeMillis ) ) {
				//track time
				$trackTimeMillis      = $item->trackTimeMillis;
				$trackTimeMillis      = number_format( $trackTimeMillis / ( 1000 * 60 ), 2 );
				$article['item_time'] = $trackTimeMillis;
			}

			if ( wpcp_is_duplicate_url( $article['source_url'] ) ) {
				wpcp_logger()->info( __( 'Checking for duplicate title and skipping them', 'wp-content-pilot-pro' ), $campaign_id );
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				continue;
			}

			$skip = apply_filters( 'wpcp_skip_duplicate_title', false, $article['title'], $campaign_id );
			if ( $skip ) {
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				continue;
			}

			wpcp_logger()->info( __( 'Inserting links into store...', 'wp-content-pilot-pro' ), $campaign_id );
			$this->insert_link( array(
				'url'     => $article['source_url'],
				'title'   => $article['source_url'],
				'for'     => $keyword,
				'camp_id' => $campaign_id,
				'status'  => 'success',
			) );

			wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );

			return $article;
		}

		$log_url = admin_url( '/edit.php?post_type=wp_content_pilot&page=wpcp-logs' );

		return new WP_Error( 'campaign-error', __( sprintf( 'No article generated check <a href="%s">log</a> for details.', $log_url ), 'wp-content-pilot-pro' ) );

	}


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

		return self::$_instance;
	}

}

WPCP_Itunes::instance();
