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

	/**
	 * WPCP_Quora constructor.
	 */
	public function __construct() {
		add_action( 'wpcp_quora_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
		add_action( 'wpcp_quora_campaign_options_meta_fields', 'wpcp_keyword_field' );
		parent::__construct( 'quora' );
	}

	/**
	 * @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' ),
		);
	}

	/**
	 * @return string
	 * @since 1.1.0
	 */
	public function get_default_template() {
		$template
			= <<<EOT
<img src="{image_url}" alt=""><br>
{content}<br>
<a href="{source_url}" target="_blank">Source</a>
EOT;

		return $template;
	}

	/**
	 * @param $post
	 */
	public function add_campaign_option_fields( $post ) {

	}

	/**
	 * @param $campaign_id
	 * @param $posted
	 */
	public function save_campaign_meta( $campaign_id, $posted ) {

	}

	/**
	 * @param $sections
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_section( $sections ) {
		return $sections;
	}

	/**
	 * @param $fields
	 *
	 * @return array
	 * @since 1.1.0
	 */
	public function get_setting_fields( $fields ) {
		return $fields;
	}


	/**
	 * @param $campaign_id
	 *
	 * @return mixed|void
	 * @throws ErrorException
	 * @since 1.1.0
	 */
	public function get_post( $campaign_id ) {
		wpcp_logger()->info( __( 'Loaded Quora Campaign', 'wp-content-pilot-pro' ), $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 [ %s ]', 'wp-content-pilot-pro' ), $keyword ), $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;
			}

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

			if ( empty( $links ) ) {
				wpcp_logger()->info( __( 'No generated links in store. Generating new links...', 'wp-content-pilot-pro' ), $campaign_id );
				$this->discover_links( $campaign_id, $keyword );
				$links = $this->get_links( $keyword, $campaign_id );
			}

			if ( empty( $links ) ) {
				$message = __( 'No links to process the campaign, waiting to run later...', 'wp-content-pilot-pro' );
				wpcp_logger()->error( $message, $campaign_id );
				$this->deactivate_key( $campaign_id, $keyword );

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

			wpcp_logger()->info( __( 'Starting to process campaign 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' => '' ] );
				$curl = $this->setup_curl();
				$curl->get( $link->url );

				if ( $curl->isError() && $this->initiator != 'cron' ) {
					wpcp_logger()->info( sprintf( __( "Failed processing link reason [%s]", 'wp-content-pilot-pro' ), $curl->getErrorMessage() ), $campaign_id );
					continue;
				}

				$html        = $curl->response;
				$readability = new WPCP_Readability();
				$readable    = $readability->parse( $html, $link->url );
				if ( is_wp_error( $readable ) ) {
					wpcp_logger()->info( sprintf( __( "Failed readability reason [%s]", 'wp-content-pilot-pro' ), $readable->get_error_message() ), $campaign_id );
					continue;
				}

				wpcp_logger()->info( __( 'Combining all parts for article', 'wp-content-pilot-pro' ), $campaign_id );
				$article = array(
					'title'      => $readability->get_title(),
					'author'     => $readability->get_author(),
					'image_url'  => $readability->get_image(),
					'excerpt'    => $readability->get_excerpt(),
					'language'   => $readability->get_language(),
					'content'    => $readability->get_content(),
					'source_url' => $link->url,
				);

				wpcp_logger()->info( 'Successfully generated article', $campaign_id );
				$this->update_link( $link->id, [ 'status' => 'success' ] );

				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    = sanitize_key( '_page_' . $campaign_id . '_' . md5( $keyword ) );
		$page_number = wpcp_get_post_meta( $campaign_id, $page_key, 0 );


		$endpoint = add_query_arg( array(
			'q'      => urlencode( sprintf( '%s site: quora.com', $keyword ) ),
			'count'  => 10,
			'loc'    => 'en',
			'format' => 'rss',
			'first'  => ( $page_number * 10 ),
		), 'https://www.bing.com/search' );

		wpcp_logger()->info( sprintf( __( 'Searching page url [%s]', 'wp-content-pilot-pro' ), $endpoint ), $campaign_id );

		$curl = $this->setup_curl();

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

			return $response;
		}

		if ( ! $response instanceof \SimpleXMLElement ) {
			$response = simplexml_load_string( $response );
		}

		wpcp_logger()->info( __( 'Extracting response from request', 'wp-content-pilot-pro' ), $campaign_id );
		$response = json_encode( $response );
		$response = json_decode( $response, true );

		//check if links exist
		if ( empty( $response ) || ! isset( $response['channel'] ) || ! isset( $response['channel']['item'] ) || empty( $response['channel']['item'] ) ) {
			$message = __( 'Could not find any links from search engine, deactivating keyword for an hour.', 'wp-content-pilot-pro' );
			wpcp_logger()->info( $message, $campaign_id );
			$this->deactivate_key( $campaign_id, $keyword );

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

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

			if ( wpcp_is_duplicate_url( $item['link'] ) ) {
				continue;
			}
			$skip = apply_filters( 'wpcp_skip_duplicate_title', false, $item['title'], $campaign_id );
			if ( $skip ) {
				continue;
			}


			$links[] = array(
				'url'     => esc_url( $item['link'] ),
				'title'   => $item['title'],
				'for'     => $keyword,
				'camp_id' => $campaign_id,
			);
		}

		$total_inserted = $this->inset_links( $links );
		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( $links ), $total_inserted, ( count( $links ) - $total_inserted ) ), $campaign_id );

		return true;
	}


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

		return self::$_instance;
	}

}

WPCP_Quora::instance();
