<?php
/**
 * Soundcloud 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_SoundCloud extends WPCP_Module {
	/**
	 * The single instance of the class
	 *
	 * @var $this ;
	 */
	protected static $_instance = null;

	/**
	 * WPCP_SoundCloud constructor.
	 */
	public function __construct() {
		//fields
		add_action( 'wpcp_soundcloud_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
		add_action( 'wpcp_soundcloud_campaign_options_meta_fields', 'wpcp_keyword_field' );
		parent::__construct( 'soundcloud' );
	}

	/**
	 * @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' ),
			'image_url'         => __( 'Main image url', 'wp-content-pilot-pro' ),
			'source_url'        => __( 'Source link', 'wp-content-pilot-pro' ),
			'date'              => __( 'Published date', 'wp-content-pilot-pro' ),
			'id'                => __( 'Item ID', 'wp-content-pilot-pro' ),
			'url'               => __( 'Item URL', 'wp-content-pilot-pro' ),
			'embed_html'        => __( 'Embed Code', 'wp-content-pilot-pro' ),
			'likes_count'       => __( 'Likes Count', 'wp-content-pilot-pro' ),
			'purchase_url'      => __( 'Purchase URL', 'wp-content-pilot-pro' ),
			'thumbnail'         => __( 'Thumbnail', 'wp-content-pilot-pro' ),
			'comment_count'     => __( 'Comments Count', 'wp-content-pilot-pro' ),
			'item_title'        => __( 'Item Title', 'wp-content-pilot-pro' ),
			'description'       => __( 'Item Description', 'wp-content-pilot-pro' ),
			'favoritings_count' => __( 'Favorites Count', 'wp-content-pilot-pro' ),
			'genre'             => __( 'Genre', 'wp-content-pilot-pro' ),
			'playback_count'    => __( 'Playback Counts', 'wp-content-pilot-pro' ),
			'reposts_count'     => __( 'Reposts Counts', 'wp-content-pilot-pro' ),
			'item_tags'         => __( 'Item Tags', 'wp-content-pilot-pro' ),
			'created_at'        => __( 'Created Date', 'wp-content-pilot-pro' ),
			'item_duration'     => __( 'Duration', 'wp-content-pilot-pro' ),
			'user_id'           => __( 'User ID', 'wp-content-pilot-pro' ),
			'user_link'         => __( 'User Link', 'wp-content-pilot-pro' ),
			'user_thumbnail'    => __( 'User Thumbnail', 'wp-content-pilot-pro' ),
			'user_username'     => __( 'User username', 'wp-content-pilot-pro' ),
			'download_url'      => __( 'Download URL', 'wp-content-pilot-pro' ),
		);
	}

	/**
	 * @return string
	 * @since 1.1.0
	 */
	public function get_default_template() {
		$template
			= <<<EOT
{embed_html}<br>
{content}<br>
<a href="{source_url}" target="_blank">Source</a> by <a href="{user_link}">{user_username}</a>
EOT;


		return $template;
	}

	/**
	 * @param $post
	 */
	public function add_campaign_option_fields( $post ) {
		echo WPCP_HTML::start_double_columns();
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Get Posts From', 'wp-content-pilot-pro' ),
			'name'    => '_post_from',
			'id'      => 'soundcloud_post_from',
			'desc'    => __( 'Get posts from globally, user or playlist', 'wp-content-pilot-pro' ),
			'options' => array(
				'global'   => __( 'Global', 'wp-content-pilot-pro' ),
				'user'     => __( 'User', 'wp-content-pilot-pro' ),
				'playlist' => __( 'Playlist', 'wp-content-pilot-pro' ),
			)
		) );

		echo WPCP_HTML::text_input( array(
			'label'       => __( 'User/ Playlist ID', 'wp-content-pilot-pro' ),
			'name'        => 'sc_user_playlist_id',
			'placeholder' => __( 'User/ Playlist ID', 'wp-content-pilot-pro' ),
			'desc'        => __( 'The specific User/ Playlist ID.', 'wp-content-pilot-pro' ),
		) );

		echo WPCP_HTML::text_input( array(
			'label'       => __( 'Minimum Length', 'wp-content-pilot-pro' ),
			'type'        => 'number',
			'name'        => 'sc_min_length',
			'placeholder' => __( 'Minimum Length', 'wp-content-pilot-pro' ),
			'desc'        => __( 'Minimum Length in milliseconds', 'wp-content-pilot-pro' ),
		) );

		echo WPCP_HTML::text_input( array(
			'label'       => __( 'Maximum Length', 'wp-content-pilot-pro' ),
			'type'        => 'number',
			'name'        => 'sc_max_length',
			'placeholder' => __( 'Maximum Length', 'wp-content-pilot-pro' ),
			'desc'        => __( 'Maximum Length in milliseconds', 'wp-content-pilot-pro' ),
		) );
		echo WPCP_HTML::end_double_columns();
	}

	/**
	 * @param $campaign_id
	 * @param $posted
	 */
	public function save_campaign_meta( $campaign_id, $posted ) {
		update_post_meta( $campaign_id, '_post_from', empty( $posted['_post_from'] ) ? '' : sanitize_text_field( $posted['_post_from'] ) );
		update_post_meta( $campaign_id, 'sc_user_playlist_id', empty( $posted['sc_user_playlist_id'] ) ? '' : sanitize_text_field( $posted['sc_user_playlist_id'] ) );
		update_post_meta( $campaign_id, 'sc_min_length', empty( $posted['sc_min_length'] ) ? '' : sanitize_text_field( $posted['sc_min_length'] ) );
		update_post_meta( $campaign_id, 'sc_max_length', empty( $posted['sc_max_length'] ) ? '' : sanitize_text_field( $posted['sc_max_length'] ) );
		update_post_meta( $campaign_id, 'sc_keyword_as_tag', empty( $posted['sc_keyword_as_tag'] ) ? '' : sanitize_text_field( $posted['sc_keyword_as_tag'] ) );
		update_post_meta( $campaign_id, 'sc_post_comments', empty( $posted['sc_post_comments'] ) ? '' : sanitize_text_field( $posted['sc_post_comments'] ) );
		update_post_meta( $campaign_id, 'sc_post_tags', empty( $posted['sc_post_tags'] ) ? '' : sanitize_text_field( $posted['sc_post_tags'] ) );
	}

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

		return $sections;
	}

	/**
	 * @param $fields
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_fields( $fields ) {
		$fields['wpcp_settings_soundcloud'] = array(
			array(
				'name'              => 'client_id',
				'label'             => __( 'Client ID', 'wp-content-pilot-pro' ),
				'type'              => 'password',
				'sanitize_callback' => 'sanitize_text_field',
				'placeholder'       => __( 'Client ID', 'wp-content-pilot-pro' ),
				'desc'              => sprintf( __( 'SoundCloud client ID creation guide <a href="%s" target="_blank">here</a>.', 'wp-content-pilot-pro' ), 'https://www.pluginever.com/docs/wp-content-pilot/soundcloud-campaign-settings/' ),
				'default'           => ''
			)
		);

		return $fields;
	}

	/**
	 * @return mixed|void
	 */
	public function get_post( $campaign_id, $keywords ) {
		wpcp_logger()->info( 'Instagram Campaign Started', $campaign_id );

		$client_id = wpcp_get_settings( 'client_id', 'wpcp_settings_soundcloud' );

		if ( empty( $client_id ) ) {
			$notice = __( 'SoundCloud Client ID is not set, so no campaign won\'t work.', 'wp-content-pilot-pro' );
			wpcp_logger()->warning( $notice, $campaign_id );
			wpcp_disable_campaign( $campaign_id );

			return new WP_Error( 'missing-data', $notice );
		}

		//loop through keywords
		foreach ( $keywords as $keyword ) {
			wpcp_logger()->debug( sprintf( 'Looping through keywords [ %s ]', $keyword ), $campaign_id );
//            if ( $this->is_deactivated_key( $campaign_id, $keyword ) ) {
//                wpcp_logger()->debug( sprintf( 'The keyword is deactivated for 1 hr because last time could not find any article with keyword [%s]', $keyword ), $campaign_id );
//                continue;
//            }

			//get links from database
			$links = $this->get_links( $keyword, $campaign_id );
			if ( empty( $links ) ) {
				wpcp_logger()->info( 'No generated links in store. Generating new links...', $campaign_id );
				$this->discover_links( $campaign_id, $keyword );
				$links = $this->get_links( $keyword, $campaign_id );
			}

			foreach ( $links as $link ) {
				wpcp_logger()->info( sprintf( 'Grabbing article from [%s]', $link->url ), $campaign_id );

				$this->update_link( $link->id, [ 'status' => 'failed' ] );

			}


		}
		$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' ) );
	}

	/**
	 * @param $campaign_id
	 * @param $keyword
	 *
	 * @return array|bool|int|WP_Error
	 * @since 1.2.0
	 */
	protected function discover_links( $campaign_id, $keyword ) {
		$page_key         = sanitize_key( '_page_' . $campaign_id . '_' . md5( $keyword ) );
		$page_number      = wpcp_get_post_meta( $campaign_id, $page_key, '1' );
		$post_from        = wpcp_get_post_meta( $campaign_id, '_post_from' );
		$user_playlist_id = wpcp_get_post_meta( $campaign_id, 'sc_user_playlist_id' );
		$min_length       = wpcp_get_post_meta( $campaign_id, 'sc_min_length' );
		$max_length       = wpcp_get_post_meta( $campaign_id, 'sc_max_length' );
		$client_id        = wpcp_get_settings( 'client_id', 'wpcp_settings_soundcloud' );


		$api_url = 'http://api.soundcloud.com/tracks/';

		if ( 'user' == $post_from ) {
			$api_url = "http://api.soundcloud.com/users/{$user_playlist_id}/tracks";
		} elseif ( 'playlist' == $post_from ) {
			$api_url = "http://api.soundcloud.com/playlists/{$user_playlist_id}";
		}

		$query_args = array(
			'q'         => $keyword,
			'client_id' => $client_id
		);

		//=== min length ===
		if ( ! empty( $min_length ) ) {
			$query_args['duration[from]'] = $min_length;
		}
		//=== max length ===
		if ( ! empty( $max_length ) ) {
			$query_args['duration[to]'] = $max_length;
		}

		// === pagination -if playlist there is no pagination it retuns them all ===
		if ( ! stristr( $api_url, '/playlists/' ) ) {
			$query_args['limit']               = 50;
			$query_args['linked_partitioning'] = true;
			$query_args['offset']              = $page_number;
		}

		$endpoint = add_query_arg( $query_args, $api_url );
		$curl = $this->setup_curl();
		$curl->get( $endpoint );
		$response = $curl->getResponse();
		exit();
	}

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

		return self::$_instance;
	}

}

WPCP_SoundCloud::instance();
