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

	/**
	 * WPCP_CareerJet constructor.
	 */
	public function __construct() {
		add_action( 'wpcp_careerjet_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
		add_action( 'wpcp_careerjet_campaign_options_meta_fields', 'wpcp_keyword_field' );
		parent::__construct( 'careerjet' );
	}

	/**
	 * @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' ),
			'date'                 => __( 'Published date', 'wp-content-pilot-pro' ),
			'salary_min'           => __( 'Salary min', 'wp-content-pilot-pro' ),
			'locations'            => __( 'Locations', 'wp-content-pilot-pro' ),
			'salary_type'          => __( 'Salary type', 'wp-content-pilot-pro' ),
			'salary_currency_code' => __( 'Salary currency code', 'wp-content-pilot-pro' ),
			'salary'               => __( 'Salary', 'wp-content-pilot-pro' ),
			'site'                 => __( 'Site', 'wp-content-pilot-pro' ),
			'salary_max'           => __( 'Salary max', 'wp-content-pilot-pro' ),
			'company'              => __( 'Company', 'wp-content-pilot-pro' ),
		);
	}

	/**
	 * @return string
	 * @since 1.1.0
	 */
	public function get_default_template() {
		$template
			= <<<EOT
<strong>Job title:</strong> {title}<br>
<strong>Company:</strong> {company}<br>
<strong>Salary</strong>: {salary} ({salary_currency_code})<br>
<strong>Location</strong>: {locations}<br>
{content}
<br><a href="{source_url}"><strong>Apply for the job now!</strong></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'   => __( 'Location', 'wp-content-pilot-pro' ),
			'name'    => '_location',
			'options' => array_merge( array( '' => 'All' ), $this->get_locations() ),
		) );
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Contract Type', 'wp-content-pilot-pro' ),
			'name'    => '_contracttype',
			'options' => array(
				'none' => 'All',
				'p'    => 'permanent job',
				'c'    => 'contract',
				't'    => 'temporary',
				'i'    => 'training',
				'v'    => 'voluntary',
			),
		) );
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Contract Period', 'wp-content-pilot-pro' ),
			'name'    => '_contractperiod',
			'options' => array(
				'none' => 'All',
				'f'    => 'Full time',
				'p'    => 'Part time',
			),
		) );
		echo WPCP_HTML::select_input( array(
			'label'   => __( 'Sort By', 'wp-content-pilot-pro' ),
			'name'    => '_sort_by',
			'options' => array(
				'relevance' => __( 'Most relevant first', 'wp-content-pilot-pro' ),
				'date'      => __( 'Freshest offer first', 'wp-content-pilot-pro' ),
				'salary'    => __( 'Biggest salary first', '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, '_location', empty( $posted['_location'] ) ? '' : sanitize_text_field( $posted['_location'] ) );
		update_post_meta( $campaign_id, '_contracttype', empty( $posted['_contracttype'] ) ? '' : sanitize_key( $posted['_contracttype'] ) );
		update_post_meta( $campaign_id, '_contractperiod', empty( $posted['_contractperiod'] ) ? '' : sanitize_key( $posted['_contractperiod'] ) );
		update_post_meta( $campaign_id, '_sort_by', empty( $posted['_sort_by'] ) ? '' : sanitize_key( $posted['_sort_by'] ) );
	}

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

		return $sections;
	}

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

		return $fields;
	}

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

		$affiliate_id = wpcp_get_settings( 'affiliate_id', 'wpcp_settings_careerjet', '' );

		wpcp_logger()->info( __( 'Checking careerjet affiliate id for authentication', 'wp-content-pilot-pro' ), $campaign_id );
		if ( empty( $affiliate_id ) ) {
			$notice = __( 'CareerJet affiliate ID 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 [ %s ]', 'wp-content-pilot-pro' ), $keyword ), $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;
			}

			wpcp_logger()->info( __( 'Starting to process campaign article', 'wp-content-pilot-pro' ), $campaign_id );

			$page_key    = sanitize_key( '_page_' . $campaign_id . '_' . md5( $keyword ) );
			$page_number = wpcp_get_post_meta( $campaign_id, $page_key, 0 );

			$api_url    = 'http://public.api.careerjet.net/search';
			$query_args = array(
				'keywords'       => $keyword,
				'location'       => wpcp_get_post_meta( $campaign_id, '_location', '' ),
				'sort'           => wpcp_get_post_meta( $campaign_id, '_sort_by', '' ),
				'pagesize'       => 1,
				'user_ip'        => '::1',
				'affid'          => $affiliate_id,
				'page'           => $page_number,
				'user_agent'     => 'Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_13_2%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F64.0.3282.119+Safari%2F537.36',
				'contracttype'   => wpcp_get_post_meta( $campaign_id, '_contracttype', '' ),
				'contractperiod' => wpcp_get_post_meta( $campaign_id, '_contractperiod', '' ),
			);

			$endpoint = add_query_arg( $query_args, $api_url );

			wpcp_logger()->info( sprintf( __( 'Searching page url [%s]', 'wp-content-pilot-pro' ), preg_replace( '/affid=([^&]+)/m', 'affid=X', $endpoint ) ), $campaign_id );

			$curl = $this->setup_curl();
			$curl->get( $endpoint );

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

			wpcp_logger()->info( __( 'Extracting response from request', 'wp-content-pilot-pro' ), $campaign_id );
			$response = (object) json_decode( $curl->getResponse(), true );
			if ( empty( $response->jobs ) || ! is_array( $response->jobs ) ) {
				$notice = __( 'Could find any jobs', '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;
			}

			$job = (object) array_pop( $response->jobs );

			if ( wpcp_is_duplicate_url( $job->url ) ) {
				wpcp_logger()->info( __( 'Skipping duplicate url', 'wp-content-pilot-pro' ), $campaign_id );
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				continue;
			}
			//check duplicate title and don't publish the post with duplicate title
			$skip = apply_filters( 'wpcp_skip_duplicate_title', false, $job->title, $campaign_id );
			if ( $skip ) {
				wpcp_logger()->info( __( 'Skipping links with duplicate title', 'wp-content-pilot-pro' ), $campaign_id );
				wpcp_update_post_meta( $campaign_id, $page_key, $page_number + 1 );
				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 ) {
				wpcp_logger()->info( __( 'Cleaning title', 'wp-content-pilot-pro' ), $campaign_id );
				$title = wpcp_clean_title( $job->title );
			} else {
				$title = html_entity_decode( $job->title, ENT_QUOTES );
			}

			wpcp_logger()->info( __( 'Combining all parts for article', 'wp-content-pilot-pro' ), $campaign_id );
			$article = array(
				'salary_min'           => @$job->salary_min,
				'locations'            => @$job->locations,
				'salary_type'          => @$job->salary_type,
				'salary_currency_code' => @$job->salary_currency_code,
				'salary'               => @$job->salary,
				'site'                 => @$job->site,
				'salary_max'           => @$job->salary_max,
				'company'              => @$job->company,
				'content'              => @$job->description,
				'title'                => $title,
				'source_url'           => $job->url,
				'image_url'            => '',
			);
			wpcp_logger()->info( __( 'Inserting links into store..', 'wp-content-pilot-pro' ), $campaign_id );
			$this->insert_link( array(
				'url'     => $job->url,
				'title'   => $job->title,
				'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' ) );
	}


	/**
	 * @return array
	 * @since 1.2.0
	 */
	public function get_locations() {
		$locations = array(
			'Czech Republic   ',
			'Denmark          ',
			'Austria          ',
			'Switzerland      ',
			'Germany          ',
			'United Arab Emirate',
			'Australia        ',
			'Canada           ',
			'China            ',
			'Hong Kong        ',
			'Ireland          ',
			'India            ',
			'Malaysia         ',
			'New Zealand      ',
			'Oman             ',
			'Philippines      ',
			'Pakistan         ',
			'Qatar            ',
			'Singapore        ',
			'United Kingdom   ',
			'United States    ',
			'South Africa     ',
			'Taiwan           ',
			'Vietnam          ',
			'Argentina        ',
			'Bolivia          ',
			'Chile            ',
			'Costa Rica       ',
			'Dominican Republic',
			'Ecuador          ',
			'Spain            ',
			'Guatemala        ',
			'Mexico           ',
			'Panama           ',
			'Peru             ',
			'Puerto Rico      ',
			'Paraguay         ',
			'Uruguay          ',
			'Venezuela        ',
			'Finland          ',
			'Canada           ',
			'Belgium          ',
			'Switzerland      ',
			'France           ',
			'Luxembourg       ',
			'Morocco          ',
			'Hungary          ',
			'Italy            ',
			'Japan            ',
			'Korea            ',
			'Belgium          ',
			'Netherlands      ',
			'Norway           ',
			'Poland           ',
			'Portugal         ',
			'Brazil           ',
			'Russia           ',
			'Ukraine          ',
			'Sweden           ',
			'Slovakia         ',
			'Turkey           ',
			'Ukraine          ',
			'Vietnam          ',
			'China   '
		);

		$list = array();
		foreach ( $locations as $location ) {
			$location          = trim( $location );
			$list[ $location ] = $location;
		}

		return $list;
	}

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

		return self::$_instance;
	}

}

WPCP_CareerJet::instance();
