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

	/**
	 * WPCP_ClickBank constructor.
	 */
	public function __construct() {
		add_action( 'wpcp_clickbank_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
		add_action( 'wpcp_clickbank_campaign_options_meta_fields', 'wpcp_keyword_field' );
		parent::__construct( 'clickbank' );
	}

	/**
	 * @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' ),
			'content'                  => __( 'Content', 'wp-content-pilot-pro' ),
			'image_url'                => __( 'Main image url', 'wp-content-pilot-pro' ),
			'source_url'               => __( 'Source link', 'wp-content-pilot-pro' ),
			'site'                     => __( 'Site', 'wp-content-pilot-pro' ),
			'description'              => __( 'Description', 'wp-content-pilot-pro' ),
			'activate_date'            => __( 'Activate Date', 'wp-content-pilot-pro' ),
			'category'                 => __( 'Category', 'wp-content-pilot-pro' ),
			'sub_category'             => __( 'Sub Category', 'wp-content-pilot-pro' ),
			'commission'               => __( 'Commission', 'wp-content-pilot-pro' ),
			'referral_url'             => __( 'Referral URL', 'wp-content-pilot-pro' ),
			'average_dollars_per_sale' => __( 'Average dollars per sale', 'wp-content-pilot-pro' ),
			'initial_dollars_per_sale' => __( 'Initial dollars per sale', 'wp-content-pilot-pro' ),
			'pct_per_sale'             => __( 'PCT per sale', 'wp-content-pilot-pro' ),
			'total_rebill'             => __( 'Total rebill', 'wp-content-pilot-pro' ),
			'pct_per_rebill'           => __( 'PCT per rebill', 'wp-content-pilot-pro' ),
			'gravity'                  => __( 'Gravity', 'wp-content-pilot-pro' ),
		);
	}

	/**
	 * @return string
	 * @since 1.1.0
	 */
	public function get_default_template() {
		$template
			= <<<EOT
<img src="{image_url}" alt=""><br>
<strong>Product Name:</strong> {title} <br>
<a href="{source_url}"><img style="display:inline" src="https://i.imgur.com/RBVKrWl.jpg"></a><br>
<strong>Description:</strong> {description} <br>
<a href="{source_url}" target="_blank">Source</a>
EOT;

		return $template;
	}

	/**
	 * @param $post
	 */
	public function add_campaign_option_fields( $post ) {
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Category', 'wp-content-pilot-pro' ),
			'name'    => '_category',
			'options' => $this->categories(),
		) );
	}

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

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

		return $sections;
	}

	/**
	 * @param $fields
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_fields( $fields ) {
		$fields['wpcp_settings_clickbank'] = [
			[
				'name'    => 'username',
				'label'   => __( 'ClickBank Username', 'wp-content-pilot-pro' ),
				'desc'    => sprintf( __( 'Follow <a href="%s" target="_blank">this guide</a> to create your ClickBank username.', 'wp-content-pilot-pro' ), 'https://www.pluginever.com/docs/wp-content-pilot/clickbank-settings/' ),
				'type'    => 'text',
				'default' => ''
			]
		];

		return $fields;
	}

	/**
	 * @return mixed|void
	 */
	public function get_post( $campaign_id ) {
		wpcp_logger()->info( __( 'Loaded Clickbank Campaign', 'wp-content-pilot-pro' ), $campaign_id );

		$user_name = wpcp_get_settings( 'username', 'wpcp_settings_clickbank', 'wpcp' );

		wpcp_logger()->info( __( 'Checking click bank username key for referral', 'wp-content-pilot-pro' ), $campaign_id );
		if ( empty( $user_name ) ) {
			$notice = __( 'ClickBank user name is not set, so no referral link will be set', 'wp-content-pilot-pro' );
			wpcp_logger()->warning( $notice, $campaign_id );
		}

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

		//loop through keywords
		foreach ( $keywords as $keyword ) {
			wpcp_logger()->info( sprintf( __( 'Looping through keywords now trying with keyword [ %s ]', 'wp-content-pilot-pro' ), $keyword ), $campaign_id );

			wpcp_logger()->info( __( 'Checking if the keyword is deactivated already', 'wp-content-pilot-pro' ), $campaign_id );

			if ( $this->is_deactivated_key( $campaign_id, $keyword ) ) {
				wpcp_logger()->error( 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;
			}

			//get links from database
			wpcp_logger()->info( __( 'Checking if any cached links in store..', 'wp-content-pilot-pro' ), $campaign_id );
			$links = $this->get_links( $keyword, $campaign_id );

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

			wpcp_logger()->info( __( 'Looping through links for publishing article', 'wp-content-pilot-pro' ), $campaign_id );
			foreach ( $links as $link ) {
				wpcp_logger()->info( sprintf( __( 'Grabbing article from [%s]', 'wp-content-pilot-pro' ), $link->url ), $campaign_id );
				$this->update_link( $link->id, [ 'status' => 'failed', 'meta' => '' ] );

				//$site  = $link->meta['site'];
				$site  = explode( '.', $link->url );
				$site  = strtolower( $site[1] );
				$image = "https://www.cbtrends.com/images/vendor-pages/$site-x400-thumb.jpg";

				wpcp_logger()->info( __( 'Combining all parts for article', 'wp-content-pilot-pro' ), $campaign_id );
				$article = array(
					'title'                    => $link->title,
					'content'                  => $link->meta['description'],
					'image_url'                => $image,
					'source_url'               => str_replace( 'zzzzz', $user_name, $link->url ),
					'site'                     => $link->meta['site'],
					'description'              => $link->meta['description'],
					'activate_date'            => $link->meta['activate_date'],
					'category'                 => $link->meta['category'],
					'sub_category'             => $link->meta['sub_category'],
					'commission'               => $link->meta['commission'],
					'referral_url'             => isset( $link->meta['referral_url'] ) ? $link->meta['referral_url'] : '',
					'average_dollars_per_sale' => $link->meta['average_dollars_per_sale'],
					'initial_dollars_per_sale' => $link->meta['initial_dollars_per_sale'],
					'pct_per_sale'             => $link->meta['pct_per_sale'],
					'total_rebill'             => $link->meta['total_rebill'],
					'pct_per_rebill'           => $link->meta['pct_per_rebill'],
					'gravity'                  => $link->meta['gravity'],
				);
				$this->update_link( $link->id, [ 'status' => 'success', 'meta' => '' ] );

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


	/**
	 * @param $campaign_id
	 * @param $keyword
	 *
	 * @return bool|mixed|WP_Error
	 * @throws ErrorException
	 * @since 1.2.0
	 */
	protected function discover_links( $campaign_id, $keyword ) {
		$page_key    = $this->get_unique_key( $keyword );
		$page_number = wpcp_get_post_meta( $campaign_id, $page_key, 0 );

		$api_url    = 'https://accounts.clickbank.com/api2/marketplace';
		$query_args = [
			'includeKeywords' => trim( $keyword ),
			'excludeKeywords' => wpcp_get_post_meta( $campaign_id, '_banned_words', '' ),
			'mainCategoryId'  => wpcp_get_post_meta( $campaign_id, '_category', '' ),
			'resultsPerPage'  => 10,
		];

		$endpoint = add_query_arg( $query_args, $api_url );
		wpcp_logger()->info( sprintf( __( 'Search for items at clickbank url [%s]', 'wp-content-pilot-pro' ), $endpoint ) );
		$curl = $this->setup_curl();
		$curl->setHeader( 'Page', $page_number );
		$curl->setHeader( 'Accept', 'application/json' );
		$curl->get( $endpoint );

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

		if ( $curl->isError() ) {
			wpcp_logger()->error( $curl->errorMessage, $campaign_id );
			$this->deactivate_key( $campaign_id, $keyword );

			return $response;
		}

		if ( empty( $response->result->details ) || ! is_array( $response->result->details ) ) {
			$message = __( 'Could not find any links from clickbank, deactivating keyword for an hour.', 'wp-content-pilot-pro' );
			wpcp_logger()->error( $message, $campaign_id );
			$this->deactivate_key( $campaign_id, $keyword );

			return new WP_Error( 'no-links-found', $message );
		}

		$items    = $response->result->details;
		$inserted = 0;

		wpcp_logger()->info( __( 'Looping through links for storing...', 'wp-content-pilot-pro' ), $campaign_id );
		foreach ( $items as $item ) {

			$url = esc_url_raw( 'http://zzzzz.' . strtolower( $item->site ) . '.hop.clickbank.net/' );

			if ( wpcp_is_duplicate_url( $url ) ) {
				continue;
			}
			//check duplicate title and don't publish the post with duplicate title
			$skip = apply_filters( 'wpcp_skip_duplicate_title', false, $item->title, $campaign_id );
			if ( $skip ) {
				continue;
			}

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

			if ( 'on' == $check_clean_title ) {
				$title = wpcp_clean_title( $item->title );
			} else {
				$title = html_entity_decode( $item->title, ENT_QUOTES );
			}


			$meta = array(
				'site'                     => $title,
				'description'              => wp_kses_post( $item->description ),
				'activate_date'            => date( 'Y-m-d', strtotime( $item->marketplaceStats->activateDate ) ),
				'category'                 => sanitize_text_field( @$item->marketplaceStats->category ),
				'sub_category'             => sanitize_text_field( @$item->marketplaceStats->subCategory ),
				'commission'               => number_format( @$item->marketplaceStats->commission ),
				'average_dollars_per_sale' => number_format( @$item->marketplaceStats->averageDollarsPerSale, 2 ),
				'initial_dollars_per_sale' => number_format( @$item->marketplaceStats->initialDollarsPerSale, 2 ),
				'pct_per_sale'             => number_format( @$item->marketplaceStats->pctPerSale, 2 ),
				'total_rebill'             => number_format( @$item->marketplaceStats->totalRebill, 2 ),
				'pct_per_rebill'           => number_format( @$item->marketplaceStats->pctPerRebill, 2 ),
				'gravity'                  => number_format( @$item->marketplaceStats->gravity, 2 ),
			);

			$data = array(
				'url'     => $url,
				'title'   => $item->title,
				'for'     => $keyword,
				'camp_id' => $campaign_id,
				'meta'    => $meta,
			);

			if ( false !== $this->insert_link( $data ) ) {
				$inserted += 1;
			}
		}

		wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
		wpcp_logger()->info( sprintf( __( 'Total found links [%d] and accepted [%d] and rejected [%d]', 'wp-content-pilot-pro' ), count( $items ), $inserted, ( count( $items ) - $inserted ) ), $campaign_id );

		return true;
	}

	/**
	 * clickbank categories
	 *
	 * @return array
	 * @since 1.0.0
	 */
	public function categories() {
		return [
			''     => '- All Categories -',
			'1253' => 'Arts &amp; Entertainment',
			'1539' => 'As Seen on TV',
			'1510' => 'Betting Systems',
			'1266' => 'Business / Investing',
			'1283' => 'Computers / Internet',
			'1297' => 'Cooking, Food &amp; Wine',
			'1308' => 'E-business &amp; E-marketing',
			'1362' => 'Education',
			'1332' => 'Employment &amp; Jobs',
			'1338' => 'Fiction',
			'1340' => 'Games',
			'1344' => 'Green Products',
			'1347' => 'Health &amp; Fitness',
			'1366' => 'Home &amp; Garden',
			'1377' => 'Languages',
			'1392' => 'Mobile',
			'1400' => 'Parenting &amp; Families',
			'1408' => 'Politics / Current Events',
			'1410' => 'Reference',
			'1419' => 'Self-Help',
			'1432' => 'Software &amp; Services',
			'1461' => 'Spirituality, New Age &amp; Alternative Beliefs',
			'1472' => 'Sports',
			'1494' => 'Travel',
		];
	}

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

		return self::$_instance;
	}

}

WPCP_ClickBank::instance();
