<?php
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       http://themeisle.com/plugins/feedzy-rss-feed-pro/
 * @since      1.0.0
 *
 * @package    feedzy-rss-feeds-pro
 * @subpackage feedzy-rss-feeds-pro/includes/admin
 */
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    feedzy-rss-feeds-pro
 * @subpackage feedzy-rss-feeds-pro/includes/admin
 * @author     Bogdan Preda <bogdan.preda@themeisle.com>
 */

/**
 * Class Feedzy_Rss_Feed_Pro_Admin
 */
class Feedzy_Rss_Feeds_Pro_Admin {
	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $plugin_name The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string $version The current version of this plugin.
	 */
	private $version;

	/**
	 * The settings for Feedzy PRO services.
	 *
	 * @since   1.3.2
	 * @access  public
	 * @var     array $settings The settings for Feedzy PRO.
	 */
	private $settings;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since       1.0.0
	 * @access      public
	 *
	 * @param       string $plugin_name The name of this plugin.
	 * @param       string $version The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
		$this->version     = $version;

		$this->settings = get_option( 'feedzy-rss-feeds-settings', array() );
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since       1.0.0
	 * @access      public
	 */
	public function enqueue_styles() {
		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Feedzy_Rss_Feeds_Pro_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Feedzy_Rss_Feeds_Pro_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_enqueue_style( $this->plugin_name, FEEDZY_PRO_ABSURL . 'css/feedzy-rss-feed-pro.css', array(), $this->version, 'all' );
		if ( get_current_screen()->post_type == 'feedzy_imports' ) {
			wp_enqueue_style( $this->plugin_name . '_chosen', FEEDZY_PRO_ABSURL . 'includes/views/css/chosen.css', array(), $this->version, 'all' );
			wp_enqueue_style( $this->plugin_name . '_metabox_edit', FEEDZY_PRO_ABSURL . 'includes/views/css/import-metabox-edit.css', array(), $this->version, 'all' );
			wp_enqueue_script( $this->plugin_name . '_chosen_scipt', FEEDZY_PRO_ABSURL . 'includes/views/js/chosen.js', array( 'jquery' ), $this->version, true );
			wp_enqueue_script( $this->plugin_name . '_dropdown_scipt', FEEDZY_PRO_ABSURL . 'includes/views/js/dropdown.js', array( 'jquery' ), $this->version, true );
			wp_enqueue_script(
				$this->plugin_name . '_metabox_edit_script', FEEDZY_PRO_ABSURL . 'includes/views/js/import-metabox-edit.js', array(
					'jquery',
					$this->plugin_name . '_dropdown_scipt',
				), $this->version, true
			);
		}
	}

	/**
	 * The custom plugin_row_meta function
	 * Adds additional links on the plugins page for this plugin
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   array  $links The array having default links for the plugin.
	 * @param   string $file The name of the plugin file.
	 *
	 * @return  array
	 */
	public function feedzy_filter_plugin_row_meta( $links, $file ) {
		if ( strpos( $file, 'feedzy-rss-feed-pro.php' ) !== false ) {
			$new_links = array(
				'doc'          => '<a href="http://docs.themeisle.com/article/277-feedzy-rss-feeds-hooks" target="_blank" title="' . __( 'Documentation and examples', 'feedzy-rss-feeds' ) . '">' . __( 'Documentation and examples', 'feedzy-rss-feeds' ) . '</a>',
				'more_plugins' => '<a href="http://themeisle.com/wordpress-plugins/" target="_blank" title="' . __( 'More Plugins', 'feedzy-rss-feeds' ) . '">' . __( 'More Plugins', 'feedzy-rss-feeds' ) . '</a>',
			);
			$links     = array_merge( $links, $new_links );
		}

		return $links;
	}

	/**
	 * Register required plugins default image for Feedzy with PRO version
	 *
	 * @since   1.0.0
	 * @access  public
	 */
	public function register_required_plugins() {
		$plugins = array(
			array(
				'name'     => 'Feedzy RSS Feeds Lite',
				'slug'     => 'feedzy-rss-feeds',
				'required' => true,
			),
		);
		$config  = array(
			'id'           => 'feedzy-rss-feeds-pro',
			// Unique ID for hashing notices for multiple instances of TGMPA.
			'default_path' => '',
			// Default absolute path to bundled plugins.
			'menu'         => 'tgmpa-install-plugins',
			// Menu slug.
			'parent_slug'  => 'plugins.php',
			// Parent menu slug.
			'capability'   => 'manage_options',
			// Capability needed to view plugin install page, should be a capability associated with the parent menu used.
			'has_notices'  => true,
			// If false, a user cannot dismiss the nag message.
			'dismiss_msg'  => 'Required',
			// If 'dismissable' is false, this message will be output at top of nag.
			'is_automatic' => false,
			// Automatically activate plugins after installation or not.
			'message'      => '',
		);
		tgmpa( $plugins, $config );
	}

	/**
	 * Replace default image for Feedzy with PRO version
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   string $imageSrc The array having default links for the plugin.
	 *
	 * @return  string
	 */
	public function feedzy_pro_define_default_image( $imageSrc ) {
		$defaultImg = FEEDZY_PRO_ABSURL . '/img/feedzy_pro.jpg';

		return $defaultImg;
	}

	/**
	 * Returns the attributes of the shortcode for the PRO version
	 * Overrides the Lite method
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   array $atts The attributes passed by WordPress.
	 *
	 * @return array
	 */
	public function feedzy_pro_get_short_code_attributes( $atts ) {
		// Retrieve & extract shorcode parameters
		$sc = shortcode_atts(
			array(
				'price'        => '',          // yes, no, auto (if price is shown)
			'referral_url' => '',   // the referral variables
			'keywords_ban' => '',   // the keywords exclude var
			'columns'      => '1',       // the columns number
			'template'     => '',       // the template name
			), $atts, 'feedzy_default'
		);

		return $sc;
	}

	/**
	 * Add grid class to item
	 *
	 * @since   1.0.0
	 * @access  private
	 *
	 * @param   array $classes The feed item classes.
	 * @param   array $sc The shortcode attributes.
	 *
	 * @return string
	 */
	public function feedzy_filter_add_grid_class( $classes = array(), $sc = array() ) {
		$classes[] = 'feedzy-rss-col-' . $sc['columns'];

		return $classes;
	}

	/**
	 * Check title for banned keywords
	 *
	 * @since   1.0.2
	 * @access  public
	 *
	 * @param   boolean $continue A boolean to stop the script.
	 * @param   array   $sc The shortcode attrs.
	 * @param   object  $item The feed item.
	 * @param   string  $feedURL The feed URL.
	 *
	 * @return  boolean
	 */
	public function item_keywords_ban( $continue, $sc, $item, $feedURL ) {
		$keywords_ban = $sc['keywords_ban'];
		if ( ! empty( $keywords_ban ) ) {
			foreach ( $keywords_ban as $keyword ) {
				if ( strpos( $item->get_title(), $keyword ) !== false || strpos( $item->get_content(), $keyword ) !== false ) {
					$continue = false;
				}
			}
		}

		return $continue;
	}

	/**
	 * Add attributes to $itemArray.
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   array  $itemArray The item attributes array.
	 * @param   object $item The feed item.
	 *
	 * @return mixed
	 */
	public function feedzy_pro_add_data_to_item( $itemArray, $item ) {
		$price                   = $this->retrive_price( $item );
		$price                   = apply_filters( 'feedzy_price_output', $price );
		$itemArray['item_price'] = $price;

		$media                   = $this->retrive_media( $item );
		$media                   = apply_filters( 'feedzy_media_output', $media );
		$itemArray['item_media'] = $media;

		return $itemArray;
	}

	/**
	 * Retrive the price from feed
	 *
	 * @since   1.0.0
	 * @access  private
	 *
	 * @param   object $item The feed item.
	 *
	 * @return string
	 */
	private function retrive_price( $item ) {
		$thePrice = '';
		if ( empty( $thePrice ) ) {
			$data = $item->get_item_tags( '', 'price' );
			if ( isset( $data[0]['data'] ) && ! empty( $data[0]['data'] ) ) {
				$thePrice = $data[0]['data'];
			}
		}
		if ( empty( $thePrice ) ) {
			$data = $item->get_item_tags( 'http://base.google.com/ns/1.0', 'price' );
			if ( isset( $data[0]['data'] ) && ! empty( $data[0]['data'] ) ) {
				$thePrice = $data[0]['data'];
			}
		}

		return $thePrice;
	}

	/**
	 * Retrive media form feed enclosure.
	 *
	 * @since   1.4.0
	 * @access  private
	 *
	 * @param   object $item The feed item.
	 *
	 * @return array
	 */
	private function retrive_media( $item ) {
		$enclosure = $item->get_enclosure();
		if ( isset( $enclosure ) ) {
			$type = $enclosure->type;
			if ( in_array( $type, array( 'audio/mpeg' ) ) ) {
				return array(
					'src'      => $enclosure->link,
					'duration' => $enclosure->duration,
					'length'   => $enclosure->length,
					'type'     => $type,
				);
			}
		}

		return array();
	}

	/**
	 * Append referral params if the option is set.
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   string $itemLink The item url.
	 * @param   array  $sc The shortcode attributes array.
	 *
	 * @return string
	 */
	public function feedzy_pro_referral_url( $itemLink, $sc ) {
		$newLink = $itemLink;
		if ( isset( $sc['referral_url'] ) && $sc['referral_url'] != '' ) {
			$parseUrl = parse_url( $itemLink );
			if ( isset( $parseUrl['query'] ) ) {
				$newLink = $itemLink . '&' . $sc['referral_url'];
			} else {
				$newLink = $itemLink . '?' . $sc['referral_url'];
			}
		}

		return $newLink;
	}

	/**
	 * Render the content to be displayed for the PRO version
	 * Takes into account the PRO shortcode attributes
	 * Overrides the Lite method
	 *
	 * @since   1.0.0
	 * @access  public
	 *
	 * @param   string $content The original content.
	 * @param   array  $sc The shorcode attributes array.
	 * @param   array  $feed_title The feed title array.
	 * @param   array  $feed_items The feed items array.
	 *
	 * @return string
	 */
	public function feedzy_pro_render_content( $content, $sc, $feed_title, $feed_items ) {
		$template_name = 'default';
		if ( isset( $sc['template'] ) && $sc['template'] != '' ) {
			$template_name = $sc['template'];
		}
		if ( $this->check_template_file_exists( $template_name ) ) {
			ob_start();
			include $this->get_template( $template_name );
			$content = ob_get_clean();

			return $content;
		} else {
			return $content;
		}
	}

	/**
	 * Checks if file exists in templates.
	 *
	 * @since   1.0.0
	 * @access  private
	 *
	 * @param   string $fileName The name of the file to check in templates (defaults to default).
	 *
	 * @return mixed
	 */
	private function check_template_file_exists( $fileName = 'default' ) {
		$userTemplate = get_template_directory() . '/feedzy_templates/' . $fileName . '.php';
		$filePath     = FEEDZY_PRO_ABSPATH . '/templates/' . $fileName . '.php';
		$defaultPath  = FEEDZY_PRO_ABSPATH . '/templates/default.php';
		if ( file_exists( $userTemplate ) ) {
			return $userTemplate;
		}
		if ( file_exists( $filePath ) ) {
			return $filePath;
		}
		if ( file_exists( $defaultPath ) ) {
			return $defaultPath;
		}

		return false;
	}

	/**
	 * Get the template content
	 *
	 * @since   1.0.0
	 * @access  private
	 *
	 * @param   string $fileName The name of the file to check in templates (defaults to default).
	 *
	 * @return string
	 */
	private function get_template( $fileName = 'default' ) {
		if ( $this->check_template_file_exists( $fileName ) != false ) {
			return $this->check_template_file_exists( $fileName );
		}

		return FEEDZY_PRO_ABSPATH . '/templates/default.php';
	}

	/**
	 * Register a new post type for feed imports.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function register_import_post_type() {
		$labels   = array(
			'name'               => __( 'Import Posts', 'feedzy-rss-feeds' ),
			'singular_name'      => __( 'Import Post', 'feedzy-rss-feeds' ),
			'add_new'            => __( 'New Import', 'feedzy-rss-feeds' ),
			'add_new_item'       => __( 'New Import', 'feedzy-rss-feeds' ),
			'edit_item'          => __( 'Edit Import', 'feedzy-rss-feeds' ),
			'new_item'           => __( 'New Import Post', 'feedzy-rss-feeds' ),
			'view_item'          => __( 'View Import', 'feedzy-rss-feeds' ),
			'search_items'       => __( 'Search Imports', 'feedzy-rss-feeds' ),
			'not_found'          => __( 'No imports found', 'feedzy-rss-feeds' ),
			'not_found_in_trash' => __( 'No imports in the trash', 'feedzy-rss-feeds' ),
		);
		$supports = array(
			'title',
		);
		$args     = array(
			'labels'               => $labels,
			'supports'             => $supports,
			'public'               => true,
			'exclude_from_search'  => true,
			'publicly_queryable'   => false,
			'capability_type'      => 'post',
			'show_in_nav_menus'    => false,
			'rewrite'              => array(
				'slug' => 'feedzy-import',
			),
			'show_in_menu'         => 'edit.php?post_type=feedzy_imports',
			'register_meta_box_cb' => array( $this, 'add_feedzy_import_metaboxes' ),
		);
		$args     = apply_filters( 'feedzy_imports_args', $args );
		register_post_type( 'feedzy_imports', $args );
	}

	/**
	 * Method to add a meta box to `feedzy_imports`
	 * custom post type.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function add_feedzy_import_metaboxes() {
		add_meta_box(
			'feedzy_import_feeds', __( 'Feed Import Options', 'feedzy-rss-feeds' ), array(
				$this,
				'feedzy_import_feed_options',
			), 'feedzy_imports', 'normal', 'high'
		);
	}

	/**
	 * Method to display metabox for import post type.
	 *
	 * @since   1.2.0
	 * @access  public
	 * @return mixed
	 */
	public function feedzy_import_feed_options() {
		global $post;
		$args                 = array(
			'post_type'      => 'feedzy_categories',
			'posts_per_page' => 100,
		);
		$feed_categories      = get_posts( $args );
		$post_types           = get_post_types( '', 'names' );
		$post_types           = array_diff( $post_types, array( 'feedzy_imports', 'feedzy_categories' ) );
		$import_post_type     = get_post_meta( $post->ID, 'import_post_type', true );
		$import_post_term     = get_post_meta( $post->ID, 'import_post_term', true );
		$source               = get_post_meta( $post->ID, 'source', true );
		$inc_key              = get_post_meta( $post->ID, 'inc_key', true );
		$exc_key              = get_post_meta( $post->ID, 'exc_key', true );
		$import_title         = get_post_meta( $post->ID, 'import_post_title', true );
		$import_date          = get_post_meta( $post->ID, 'import_post_date', true );
		$import_content       = get_post_meta( $post->ID, 'import_post_content', true );
		$import_featured_img  = get_post_meta( $post->ID, 'import_post_featured_img', true );
		$import_custom_fields = get_post_meta( $post->ID, 'imports_custom_fields', true );
		$post_status          = $post->post_status;
		$nonce                = wp_create_nonce( FEEDZY_PRO_BASEFILE );
		$output               = '
            <input type="hidden" name="feedzy_import_noncename" id="feedzy_category_meta_noncename" value="' . $nonce . '" />
        ';
		include FEEDZY_PRO_ABSPATH . '/includes/views/import-metabox-edit.php';
		echo $output;
	}

	/**
	 * Save method for custom post type
	 * import feeds.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   integer $post_id The post ID.
	 * @param   object  $post The post object.
	 *
	 * @return bool
	 */
	public function save_feedzy_import_feed_meta( $post_id, $post ) {
		if (
			empty( $_POST ) ||
			get_post_type( $post_id ) != 'feedzy_imports' ||
			( isset( $_POST['feedzy_import_noncename'] ) && ! wp_verify_nonce( $_POST['feedzy_import_noncename'], FEEDZY_PRO_BASEFILE ) ) ||
			! current_user_can( 'edit_post', $post_id )
		) {
			return $post_id;
		}
		$data_meta            = isset( $_POST['feedzy_meta_data'] ) ? ( is_array( $_POST['feedzy_meta_data'] ) ? $_POST['feedzy_meta_data'] : array() ) : array();
		$custom_fields_keys   = isset( $_POST['custom_vars_key'] ) ? ( is_array( $_POST['custom_vars_key'] ) ? $_POST['custom_vars_key'] : array() ) : array();
		$custom_fields_values = isset( $_POST['custom_vars_value'] ) ? ( is_array( $_POST['custom_vars_value'] ) ? $_POST['custom_vars_value'] : array() ) : array();
		$custom_fields        = array();
		foreach ( $custom_fields_keys as $index => $key_value ) {
			$value = '';
			if ( isset( $custom_fields_values[ $index ] ) ) {
				$value = implode( ',', (array) $custom_fields_values[ $index ] );
			}
			$custom_fields[ $key_value ] = $value;
		}
		if ( $post->post_type == 'revision' ) {
			return true;
		} else {
			foreach ( $data_meta as $key => $value ) {
				$value = implode( ',', (array) $value );
				if ( get_post_meta( $post_id, $key, false ) ) {
					update_post_meta( $post_id, $key, $value );
				} else {
					add_post_meta( $post_id, $key, $value );
				}
				if ( ! $value ) {
					delete_post_meta( $post_id, $key );
				}
			}
			if ( get_post_meta( $post_id, 'imports_custom_fields', false ) ) {
				update_post_meta( $post_id, 'imports_custom_fields', $custom_fields );
			} else {
				add_post_meta( $post_id, 'imports_custom_fields', $custom_fields );
			}
			if ( empty( $custom_fields ) ) {
				delete_post_meta( $post_id, 'imports_custom_fields' );
			}
			// Added this to activate post if publish is clicked and sometimes it does not change status.
			if ( isset( $_POST['custom_post_status'] ) && $_POST['custom_post_status'] == 'Publish' ) {
				$activate = array(
					'ID'          => $post_id,
					'post_status' => 'publish',
				);
				remove_action( 'save_post_feedzy_imports', array( $this, 'save_feedzy_import_feed_meta' ), 1, 2 );
				wp_update_post( $activate );
				add_action( 'save_post_feedzy_imports', array( $this, 'save_feedzy_import_feed_meta' ), 1, 2 );
			}

			return true;
		}// End if().
	}

	/**
	 * Method to add header columns to import feeds table.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   array $columns The columns array.
	 *
	 * @return array|bool
	 */
	public function feedzy_import_columns( $columns ) {
		$columns['title'] = __( 'Import Job Title', 'feedzy-rss-feeds' );
		if ( $new_columns = $this->array_insert_before( 'date', $columns, 'status', __( 'Status', 'feedzy-rss-feeds' ) ) ) {
			$columns = $new_columns;
		} else {
			$columns['status'] = __( 'Status', 'feedzy-rss-feeds' );
		}

		if ( $new_columns = $this->array_insert_before( 'date', $columns, 'next_run', __( 'Next Run', 'feedzy-rss-feeds' ) ) ) {
			$columns = $new_columns;
		} else {
			$columns['next_run'] = __( 'Next Run', 'feedzy-rss-feeds' );
		}

		return $columns;
	}

	/**
	 * Utility method to insert before specific key
	 * in an associative array.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   string $key The key before to insert.
	 * @param   array  $array The array in which to insert the new key.
	 * @param   string $new_key The new key name.
	 * @param   mixed  $new_value The new key value.
	 *
	 * @return array|bool
	 */
	protected function array_insert_before( $key, &$array, $new_key, $new_value ) {
		if ( array_key_exists( $key, $array ) ) {
			$new = array();
			foreach ( $array as $k => $value ) {
				if ( $k === $key ) {
					$new[ $new_key ] = $new_value;
				}
				$new[ $k ] = $value;
			}

			return $new;
		}

		return false;
	}

	/**
	 * Method to add a toggle checkbox on the status column
	 * in the import feeds table.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   string  $column The current column to check.
	 * @param   integer $post_id The post ID.
	 */
	public function manage_feedzy_import_columns( $column, $post_id ) {
		global $post;
		switch ( $column ) {
			case 'status':
				$status = $post->post_status;
				if ( empty( $status ) ) {
					echo __( 'Undefined', 'feedzy-rss-feeds' );
				} else {
					if ( $status == 'publish' ) {
						$checked = 'checked';
					} else {
						$checked = '';
					}
					echo '
                    <div class="switch">
                        <input id="feedzy-toggle_' . $post->ID . '" class="feedzy-toggle feedzy-toggle-round" type="checkbox" value="' . $post->ID . '" ' . $checked . '>
                        <label for="feedzy-toggle_' . $post->ID . '"></label>
                    </div>
                    ';
				}
				break;
			case 'next_run':
				$next = wp_next_scheduled( 'feedzy_cron' );
				if ( $next ) {
					$now  = new DateTime();
					$then = new DateTime();
					$then = $then->setTimestamp( $next );
					$in   = $now->diff( $then );
					echo sprintf( __( 'In %1$d hours %2$d minutes', 'feedzy-rss-feeds' ), $in->format( '%h' ), $in->format( '%i' ) );
				}
				break;
			default:
				break;
		}
	}

	/**
	 * AJAX called method to update post status.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function import_status() {
		global $wpdb;
		$id      = $_POST['id'];
		$status  = $_POST['status'];
		$publish = 'draft';
		if ( $status == 'true' ) {
			$publish = 'publish';
		}
		$new_post_status = array(
			'ID'          => $id,
			'post_status' => $publish,
		);
		$post_id         = wp_update_post( $new_post_status );
		if ( is_wp_error( $post_id ) ) {
			$errors = $post_id->get_error_messages();
			foreach ( $errors as $error ) {
				echo $error;
			}
		}
		wp_die(); // this is required to terminate immediately and return a proper response
	}

	/**
	 * AJAX method to get taxonomies for a given post_type.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function get_taxonomies() {
		$post_type  = $_POST['post_type'];
		$taxonomies = get_object_taxonomies(
			array(
				'post_type' => $post_type,
			)
		);
		$results    = array();
		if ( ! empty( $taxonomies ) ) {
			foreach ( $taxonomies as $taxonomy ) {
				$terms                = get_terms(
					array(
						'taxonomy'   => $taxonomy,
						'hide_empty' => false,
					)
				);
				$results[ $taxonomy ] = $terms;
			}
		}
		echo json_encode( $results );
		wp_die();
	}

	/**
	 * The Cron Job.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function run_cron( $max = 100 ) {
		global $post;
		$args           = array(
			'post_type'   => 'feedzy_imports',
			'post_status' => 'publish',
		);
		$feedzy_imports = get_posts( $args );
		foreach ( $feedzy_imports as $job ) {
			$source               = get_post_meta( $job->ID, 'source', true );
			$inc_key              = get_post_meta( $job->ID, 'inc_key', true );
			$exc_key              = get_post_meta( $job->ID, 'exc_key', true );
			$import_title         = get_post_meta( $job->ID, 'import_post_title', true );
			$import_date          = get_post_meta( $job->ID, 'import_post_date', true );
			$import_content       = get_post_meta( $job->ID, 'import_post_content', true );
			$import_featured_img  = get_post_meta( $job->ID, 'import_post_featured_img', true );
			$import_post_type     = get_post_meta( $job->ID, 'import_post_type', true );
			$import_post_term     = get_post_meta( $job->ID, 'import_post_term', true );
			$import_custom_fields = get_post_meta( $job->ID, 'imports_custom_fields', true );
			$imported_items       = get_post_meta( $job->ID, 'imported_items', true );
			if ( ! is_array( $imported_items ) ) {
				$imported_items = array();
			}
			$options = array(
				'feeds'          => $source,
				// comma separated feeds url
				'max'            => $max,
				// number of feeds items (0 for unlimited)
				'feed_title'     => 'no',
				// display feed title yes/no
				'target'         => '_blank',
				// _blank, _self
				'title'          => '',
				// strip title after X char
				'meta'           => 'yes',
				// yes, no
				'summary'        => 'yes',
				// strip title
				'summarylength'  => '',
				// strip summary after X char
				'thumb'          => 'auto',
				// yes, no, auto
				'default'        => '',
				// default thumb URL if no image found (only if thumb is set to yes or auto)
				'size'           => '250',
				// thumbs pixel size
				'keywords_title' => $inc_key,
				'keywords_ban'   => $exc_key,
				'columns'        => 1,
			);
			if ( ! empty( $options['keywords_title'] ) ) {
				$options['keywords_title'] = rtrim( $options['keywords_title'], ',' );
				$options['keywords_title'] = array_map( 'trim', explode( ',', $options['keywords_title'] ) );
			}
			if ( ! empty( $options['keywords_ban'] ) ) {
				$options['keywords_ban'] = rtrim( $options['keywords_ban'], ',' );
				$options['keywords_ban'] = array_map( 'trim', explode( ',', $options['keywords_ban'] ) );
			}
			$result = $this->get_job_feed( $options );
			$count  = 0;
			foreach ( $result as $item ) {
				$item_hash = hash( 'sha256', $item['item_url'] . '_' . $item['item_date'] );
				if ( ! in_array( $item_hash, $imported_items ) ) {
					$imported_items[] = $item_hash;
					update_post_meta( $job->ID, 'imported_items', $imported_items );
					// create post
					$post_title = str_replace( '[#item_title]', $item['item_title'], $import_title );
					$author     = '';
					if ( $item['item_author'] ) {
						$author = $item['item_author'];
					}

					$item_link = '<a href="' . $item['item_url'] . '" target="_blank">' . __( 'Read More', 'feedzy-rss-feeds' ) . '</a>';

					$post_title = str_replace( '[#item_author]', $author, $post_title );
					$post_title = str_replace( '[#item_date]', date( get_option( 'date_format' ) . ' at ' . get_option( 'time_format' ), $item['item_date'] ), $post_title );

					if ( strpos( $post_title, '[#title_wordai]' ) !== false ) {
						$spin_title = $item['item_title'];
						$wordai     = new Feedzy_Rss_Feeds_Pro_Wordai();
						$wordai->init( $this->settings['wordai_username'], $this->settings['wordai_hash'] );
						$response = $wordai->call_api(
							array(
								'text' => $spin_title,
							)
						);
						if ( $response ) {
							$spin_title = $response['text'];
						}
						$post_title = str_replace( '[#title_wordai]', $spin_title, $post_title );
					}

					$image_html   = '<img src="' . $item['item_img_path'] . '" title="' . $item['item_title'] . '" />';
					$post_content = str_replace( '[#item_content]', $item['item_description'], $import_content );
					$post_content = str_replace( '[#item_image]', $image_html, $post_content );
					$post_content = str_replace( '[#item_url]', $item_link, $post_content );

					if ( strpos( $post_content, '[#content_wordai]' ) !== false ) {
						$spin_content = $item['item_description'];
						$wordai       = new Feedzy_Rss_Feeds_Pro_Wordai();
						$wordai->init( $this->settings['wordai_username'], $this->settings['wordai_hash'] );
						$response = $wordai->call_api(
							array(
								'text' => $spin_content,
							)
						);
						if ( $response ) {
							$spin_content = $response['text'];
						}
						$post_content = str_replace( '[#content_wordai]', $spin_title, $post_content );
					}

					$item_date = date( 'Y-m-d H:i:s', $item['item_date'] );
					$now       = date( 'Y-m-d H:i:s' );
					if ( trim( $import_date ) == '' ) {
						$post_date = $now;
					}
					$post_date   = str_replace( '[#item_date]', $item_date, $import_date );
					$post_date   = str_replace( '[#post_date]', $now, $post_date );
					$new_post    = array(
						'post_type'    => $import_post_type,
						'post_title'   => $post_title,
						'post_content' => $post_content,
						'post_date'    => $post_date,
						'post_status'  => 'publish',
					);
					$new_post_id = 0;
					$new_post_id = wp_insert_post( $new_post );
					if ( $import_post_term != 'none' && strpos( $import_post_term, '_' ) ) {
						list( $taxonomy, $terms ) = explode( '_', $import_post_term );
						wp_set_object_terms( $new_post_id, intval( $terms ), $taxonomy );
					}
					if ( ! empty( $import_custom_fields ) ) {
						foreach ( $import_custom_fields as $key => $value ) {
							if ( get_post_meta( $new_post_id, $key, false ) ) {
								update_post_meta( $new_post_id, $key, $value );
							} else {
								add_post_meta( $new_post_id, $key, $value );
							}
							if ( ! $value ) {
								delete_post_meta( $new_post_id, $key );
							}
						}
					}
					if ( trim( $import_featured_img ) != '' && $new_post_id != 0 ) {
						$image_url = str_replace( '[#item_image]', $item['item_img_path'], $import_featured_img );
						if ( $image_url != '' && isset( $item['item_img_path'] ) && $item['item_img_path'] != '' ) {
							$this->generate_featured_image( $image_url, $new_post_id, $item['item_title'] );
						} else {
							$this->generate_featured_image( $import_featured_img, $new_post_id, $item['item_title'] );
						}
					}
				}// End if().
			}// End foreach().
		}// End foreach().
	}

	/**
	 * Method to return feed items to use on cron job.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   array $options The options for the job.
	 *
	 * @return mixed
	 */
	public function get_job_feed( $options ) {
		$admin = Feedzy_Rss_Feeds::instance()->get_admin();
		if ( ! method_exists( $admin, 'normalize_urls' ) ) {
			return array();
		}
		$feedURL = $admin->normalize_urls( $options['feeds'] );
		$feed    = $admin->fetch_feed( $feedURL );
		if ( is_string( $feed ) ) {
			return array();
		}
		$sizes      = array(
			'width'  => $options['size'],
			'height' => $options['size'],
		);
		$sizes      = apply_filters( 'feedzy_thumb_sizes', $sizes, $feedURL );
		$feed_items = apply_filters( 'feedzy_get_feed_array', array(), $options, $feed, $feedURL, $sizes );

		return $feed_items;
	}

	/**
	 * Downloads and sets a post featured image if possible.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   string  $file The file URL.
	 * @param   integer $post_id The post ID.
	 * @param   string  $desc Description.
	 *
	 * @return WP_Error | boolean
	 */
	public function generate_featured_image( $file, $post_id, $desc ) {
		require_once( ABSPATH . 'wp-admin' . '/includes/image.php' );
		require_once( ABSPATH . 'wp-admin' . '/includes/file.php' );
		require_once( ABSPATH . 'wp-admin' . '/includes/media.php' );
		// Set variables for storage, fix file filename for query strings.
		preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
		if ( ! $matches ) {
			return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL', 'feedzy-rss-feeds' ) );
		}
		$file_array         = array();
		$file_array['name'] = basename( $matches[0] );
		// Download file to temp location.
		$file_array['tmp_name'] = download_url( $file );
		// If error storing temporarily, return the error.
		if ( is_wp_error( $file_array['tmp_name'] ) ) {
			return $file_array['tmp_name'];
		}
		// Do the validation and storage stuff.
		$id = media_handle_sideload( $file_array, $post_id, $desc );
		// If error storing permanently, unlink.
		if ( is_wp_error( $id ) ) {
			unlink( $file_array['tmp_name'] );

			return $id;
		}

		return set_post_thumbnail( $post_id, $id );

	}

	/**
	 * Sets a custom cron schedule.
	 *
	 * @since   1.2.0
	 * @access  public
	 *
	 * @param   array $schedules The WordPress schedules array.
	 *
	 * @return mixed
	 */
	public function do_cron_recurrence( $schedules ) {
		$schedules['on_every_hour'] = array(
			'display'  => __( 'Every Hour', 'feedzy-rss-feeds' ),
			'interval' => 3600,
		);

		return $schedules;
	}

	/**
	 * Registers a cron schedule.
	 *
	 * @since   1.2.0
	 * @access  public
	 */
	public function do_cron() {
		if ( ! wp_next_scheduled( 'feedzy_cron' ) ) {
			wp_schedule_event( time(), 'on_every_hour', 'feedzy_cron' );
		}
	}

	/**
	 * Method to return license status.
	 * Used to filter PRO version types.
	 *
	 * @since   1.2.0
	 * @access  public
	 * @return bool
	 */
	public function feedzy_is_business() {
		$plan = get_option( 'feedzy_rss_feeds_pro_license_plan', 1 );
		$plan = intval( $plan );
		return ( $plan > 1 );
	}

	/**
	 * Method for updating settings page via AJAX.
	 *
	 * @since   1.3.2
	 * @access  public
	 */
	public function update_settings_page() {
		$post_data = $_POST['feedzy_settings'];

		if ( isset( $post_data['wordai_pass'] ) && $post_data['wordai_pass'] != '' ) {
			if ( isset( $this->settings['wordai_hash'] ) && $this->settings['wordai_hash'] == md5( substr( md5( $post_data['wordai_pass'] ), 0, 15 ) ) ) {
				$post_data['wordai_hash'] = $this->settings['wordai_hash'];
				unset( $post_data['wordai_pass'] );
			} else {
				$post_data['wordai_hash'] = md5( substr( md5( $post_data['wordai_pass'] ), 0, 15 ) );
				unset( $post_data['wordai_pass'] );
			}
		}
		$wordai = new Feedzy_Rss_Feeds_Pro_Wordai();
		$wordai->init( $post_data['wordai_username'], $post_data['wordai_hash'] );
		$response = $wordai->check_api();
		if ( $response['status'] == 'Success' ) {
			$post_data['wordai_licence']    = 'yes';
			$post_data['wordai_last_check'] = date( 'd/m/Y H:i:s' );
		} else {
			$post_data['wordai_licence']    = 'no';
			$post_data['wordai_last_check'] = date( 'd/m/Y H:i:s' );
		}
		$this->settings = array_merge( $this->settings, $post_data );
		$this->save_settings();

		echo json_encode( $response );
		wp_die();
	}

	/**
	 * Method to save settings.
	 *
	 * @since   1.3.2
	 * @access  private
	 */
	private function save_settings() {
		update_option( 'feedzy-rss-feeds-settings', $this->settings );
	}

	/**
	 * Add settings menu item.
	 *
	 * @since   1.3.2
	 * @access  public
	 */
	public function feedzy_pro_menu_pages() {
		if ( $this->feedzy_is_agency() != false ) {
			add_submenu_page(
				'feedzy-admin-menu', __( 'Settings', 'feedzy-rss-feeds' ), __( 'Settings', 'feedzy-rss-feeds' ), 'manage_options', 'feedzy-pro-settings', array(
					$this,
					'settings_page',
				)
			);
		}
	}

	/**
	 * Method to return if licence is agency.
	 *
	 * @since   1.3.2
	 * @access  public
	 * @return bool
	 */
	public function feedzy_is_agency() {
		$plan = get_option( 'feedzy_rss_feeds_pro_license_plan', 1 );
		$plan = intval( $plan );
		return ( $plan > 2 );
	}

	/**
	 * The method for the settings page display.
	 *
	 * @since   1.3.2
	 * @access  public
	 */
	public function settings_page() {
		echo $this->render_view( 'wordai' );
	}

	/**
	 * Render a view page.
	 *
	 * @since   1.3.2
	 * @access  public
	 *
	 * @param   string $name The name of the view.
	 *
	 * @return string
	 */
	private function render_view( $name ) {
		wp_enqueue_style( 'feedzy-upsell', FEEDZY_ABSURL . 'includes/layouts/css/upsell.css', array(), $this->version,'all' );
		wp_enqueue_style( $this->plugin_name . '_metabox_edit', FEEDZY_PRO_ABSURL . 'includes/views/css/import-metabox-edit.css', array(), $this->version, 'all' );
		ob_start();
		include FEEDZY_PRO_ABSPATH . '/includes/views/' . $name . '-view.php';

		return ob_get_clean();
	}

}
