<?php
/**
 * Ebay Class
 *
 * @since       1.1.0
 * @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
 * @package     WP Content Pilot Pro
 */

defined( 'ABSPATH' ) || exit();

class WPCP_Ebay extends WPCP_Module {

    /**
     * @var string
     */
    protected $module = 'ebay';

    /**
     * The single instance of the class
     *
     * @var $this ;
     */
    protected static $_instance = null;

    /**
     * WPCP_Ebay constructor.
     */
    public function __construct() {
        //fields
        add_action( 'wpcp_ebay_campaign_options_meta_fields', 'wpcp_keyword_suggestion_field' );
        add_action( 'wpcp_ebay_campaign_options_meta_fields', 'wpcp_keyword_field' );
        parent::__construct( $this->module );
    }

    /**
     * @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' ),
            'affiliate_url'  => __( 'Affiliate Url', 'wp-content-pilot-pro' ),
            'date'           => __( 'Published date', 'wp-content-pilot-pro' ),
            //'payment_methods' => __( 'Show payment methods', 'wp-content-pilot-pro' ),
            'location'       => __( 'Location', 'wp-content-pilot-pro' ),
            'return_policy'  => __( 'Return Policy', 'wp-content-pilot-pro' ),
            'ships_to'       => __( 'Ships to', 'wp-content-pilot-pro' ),
            'current_price'  => __( 'Last bid price, if available formatted', 'wp-content-pilot-pro' ),
            'price_numeric'  => __( 'Last bid price, if available numeric', 'wp-content-pilot-pro' ),
            'bids'           => __( 'Bids, if available', 'wp-content-pilot-pro' ),
            'start_time'     => __( 'Start time', 'wp-content-pilot-pro' ),
            'end_time'       => __( 'End time', 'wp-content-pilot-pro' ),
            'deal_end_time'  => __( 'Deal End time', 'wp-content-pilot-pro' ),
            'listing_type'   => __( 'Listing type', 'wp-content-pilot-pro' ),
            'item_condition' => __( 'Item Condition ', 'wp-content-pilot-pro' ),
        );
    }

    /**
     * @return string
     * @since 1.1.0
     */
    public function get_default_template() {
        $template
            = <<<EOT
<img src="{image_url}" alt=""><br>
<strong>Price: </strong> {current_price} <br>
{content}<br>
<br> <a href="{source_url}">View on eBay </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'   => __( 'Ebay Site', 'wp-content-pilot-pro' ),
            'name'    => '_ebay_site',
            'options' => $this->get_ebay_sites(),
            'desc'    => __( 'Select ebay site', 'wp-content-pilot-pro' ),
            'attrs'   => array(
                'required' => 'required'
            )
        ) );

        echo WPCP_HTML::select_input( array(
            'label'   => __( 'Ebay Category', 'wp-content-pilot-pro' ),
            'name'    => '_category',
            'options' => $this->get_ebay_cats(),
            'desc'    => __( 'Select category', 'wp-content-pilot-pro' ),
        ) );

        echo WPCP_HTML::select_input( array(
            'label'   => __( 'Ebay Listing Type', 'wp-content-pilot-pro' ),
            'name'    => '_listing_type',
            'options' => array(
                'all'                                    => 'ALL',
                'Auction'                                => 'Auction',
                'AuctionWithBIN&listingType2=FixedPrice' => 'BIN Only',
            )
        ) );

        echo WPCP_HTML::select_input( array(
            'label'   => __( 'Ebay Order By', 'wp-content-pilot-pro' ),
            'name'    => '_order_by',
            'options' => array(
                'BestMatch'                => 'Best Match',
                'EndTimeSoonest'           => 'Items Ending First',
                'BidCountMost'             => 'Bid Count Most',
                'StartTimeNewest'          => 'Newest',
                'PricePlusShippingLowest'  => 'Price Lowest first',
                'PricePlusShippingHighest' => 'Price Height first',
            ),
        ) );

        /**
         * Ebay price filter
         * @since 1.1.7
         */
        echo WPCP_HTML::text_input(
            array(
                'label' => __( 'Ebay Minimum Price', 'wp-content-pilot-pro' ),
                'name'  => '_min_price',
                'desc'  => __( 'Minimum price for ebay', 'wp-content-pilot-pro' ),
            )
        );
        echo WPCP_HTML::text_input(
            array(
                'label' => __( 'Ebay Maximum Price', 'wp-content-pilot-pro' ),
                'name'  => '_max_price',
                'desc'  => __( 'Maximum price for ebay', 'wp-content-pilot-pro' ),
            )
        );

        echo WPCP_HTML::end_double_columns();

        echo WPCP_HTML::checkbox_input( array(
            'label' => __( 'Get products only from top rated sellers', 'wp-content-pilot-pro' ),
            'name'  => '_top_rated',
        ) );
        echo WPCP_HTML::checkbox_input( array(
            'label' => __( 'Get products with free shipping only', 'wp-content-pilot-pro' ),
            'name'  => '_free_shipping',
        ) );
    }

    /**
     * @param $campaign_id
     * @param $posted
     */
    public function save_campaign_meta( $campaign_id, $posted ) {
        update_post_meta( $campaign_id, '_ebay_site', empty( $posted['_ebay_site'] ) ? '' : sanitize_text_field( $posted['_ebay_site'] ) );
        update_post_meta( $campaign_id, '_category', empty( $posted['_category'] ) ? '' : sanitize_text_field( $posted['_category'] ) );
        update_post_meta( $campaign_id, '_listing_type', empty( $posted['_listing_type'] ) ? '' : sanitize_text_field( $posted['_listing_type'] ) );
        update_post_meta( $campaign_id, '_order_by', empty( $posted['_order_by'] ) ? '' : sanitize_text_field( $posted['_order_by'] ) );
        update_post_meta( $campaign_id, '_top_rated', empty( $posted['_top_rated'] ) ? '' : sanitize_text_field( $posted['_top_rated'] ) );
        update_post_meta( $campaign_id, '_free_shipping', empty( $posted['_free_shipping'] ) ? '' : sanitize_text_field( $posted['_free_shipping'] ) );
        update_post_meta( $campaign_id, '_min_price', empty( $posted['_min_price'] ) ? '' : sanitize_text_field( $posted['_min_price'] ) );
        update_post_meta( $campaign_id, '_max_price', empty( $posted['_max_price'] ) ? '' : sanitize_text_field( $posted['_max_price'] ) );
    }

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

        return $sections;
    }

    /**
     * @param $fields
     *
     * @return array
     * @since 1.1.0
     *
     */
    public function get_setting_fields( $fields ) {
        $fields['wpcp_settings_ebay'] = [
            array(
                'name'              => 'app_id',
                'label'             => __( 'App ID', 'wp-content-pilot-pro' ),
                'desc'              => sprintf( __( 'Learn to create your Ebay App ID <a href="%s" target="_blank">here</a>.', 'wp-content-pilot-pro' ), 'https://www.pluginever.com/docs/wp-content-pilot/ebay-campaign-settings/' ),
                'type'              => 'password',
                'sanitize_callback' => 'sanitize_text_field',
            ),
            array(
                'name'              => 'campaign_id',
                'label'             => __( 'Campaign ID', 'wp-content-pilot-pro' ),
                'desc'              => sprintf( __( 'Learn to create your Ebay Campaign ID <a href="%s" target="_blank">here</a>.', 'wp-content-pilot-pro' ), 'https://www.pluginever.com/docs/wp-content-pilot/ebay-campaign-settings/' ),
                'type'              => 'password',
                'sanitize_callback' => 'sanitize_text_field'
            ),
        ];

        return $fields;
    }

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

        $ebay_campaign_id = wpcp_get_settings( 'campaign_id', 'wpcp_settings_ebay', '0987654321' );
        $ebay_app_id      = wpcp_get_settings( 'app_id', 'wpcp_settings_ebay', '' );
        $site             = wpcp_get_post_meta( $campaign_id, '_ebay_site', '1' );

        wpcp_logger()->info( __( 'Checking ebay campaign id and app id for authentication', 'wp-content-pilot-pro' ), $campaign_id );
        if ( empty( $ebay_campaign_id ) || empty( $ebay_app_id ) ) {
            wpcp_disable_campaign( $campaign_id );
            $ebay_settings_url = admin_url( '/edit.php?post_type=wp_content_pilot&page=wpcp-settings#wpcp_settings_ebay' );

            $notice = __( sprintf( 'Ebay appid or campaignid is not set.So, the campaign wont run, disabling campaign. set it from <a href="%s">here</a>', $ebay_settings_url ), 'wp-content-pilot-pro' );
            wpcp_logger()->error( $notice );

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

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

            wpcp_logger()->info( __( "Checking if the keyword already deactivated", "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 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 );
            }

            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' ), preg_replace( '/campid=([^&]+)/m', 'campid=X', $link->url ) ), $campaign_id );
                $this->update_link( $link->id, [ 'status' => 'failed', 'meta' => '' ] );

                if ( empty( $link->meta ) || empty( $link->meta['id'] ) ) {
                    continue;
                }

                $item_id = $link->meta['id'];
                if ( $site == 1 ) {
                    $domain = 'ebay.com';
                } elseif ( $site == 2 ) {
                    $domain = 'ebay.ie';
                } elseif ( $site == 3 ) {
                    $domain = 'ebay.at';
                } elseif ( $site == 4 ) {
                    $domain = 'ebay.com.au';
                } elseif ( $site == 5 ) {
                    $domain = 'befr.ebay.be';
                } elseif ( $site == 7 ) {
                    $domain = 'ebay.ca';
                } elseif ( $site == 10 ) {
                    $domain = 'ebay.fr';
                } elseif ( $site == 11 ) {
                    $domain = 'ebay.de';
                } elseif ( $site == 12 ) {
                    $domain = 'ebay.it';
                } elseif ( $site == 13 ) {
                    $domain = 'ebay.es';
                } elseif ( $site == 14 ) {
                    $domain = 'ebay.ch';
                } elseif ( $site == 15 ) {
                    $domain = 'ebay.co.uk';
                } elseif ( $site == 16 ) {
                    $domain = 'ebay.nl';
                }

                //$url = "http://www.$domain/itm/www/$item_id";
                $url = $link->url;
                wpcp_logger()->info( sprintf( __( 'Preparing url for requesting [%s]', 'wp-content-pilot-pro' ), $url ), $campaign_id );

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

                wpcp_logger()->info( __( 'Getting raw response from url for content', 'wp-content-pilot-pro' ), $campaign_id );
                $response = $curl->getRawResponse();
                $dom      = wpcp_str_get_html( $response );

                // extract image
                wpcp_logger()->info( __( 'Extracting image for article', 'wp-content-pilot-pro' ), $campaign_id );
                if ( stristr( $response, 'maxImageUrl":"' ) ) {
                    preg_match_all( '{maxImageUrl":"(.*?)"}', $response, $matches );
                } else {
                    preg_match_all( '{displayImgUrl":"(.*?)"}', $response, $matches );
                }
                $images = array_unique( $matches[1] );

                $json       = implode( '","', $images );
                $json       = '["' . $json . '"]';
                $images_arr = json_decode( $json );
                $image_url  = $images_arr[0];

                wpcp_logger()->info( __( 'Extracting description for article', 'wp-content-pilot-pro' ), $campaign_id );
                $description = '';
                $itemAttrs   = $dom->find( '.itemAttr' );
                foreach ( $itemAttrs as $itemAttr ) {
                    $description .= $itemAttr->outertext;
                }
                $description = preg_replace( '{<span id="hiddenContent.*?span>}', '</td>', $description );
                $description = preg_replace( '{<span id="readFull.*?span>}', '</td>', $description );
                $description = str_replace( '50.0%', '30.0%', $description );
                $description = str_replace( '92%', '70%', $description );
                $description = wp_kses_post( $description );

                $detail_description_nodes = $dom->find( '.prodDetailDesc' );
                foreach ( $detail_description_nodes as $detail_description_node ) {
                    $html        = $detail_description_node->outertext;
                    $html        = preg_replace( '{<span id="hiddenContent.*?span>}', '</td>', $html );
                    $html        = preg_replace( '{<span id="readFull.*?span>}', '</td>', $html );
                    $description .= $html;
                }

                //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( $link->title );
                } else {
                    $title = html_entity_decode( $link->title, ENT_QUOTES );
                }

                wpcp_logger()->info( __( 'Extracting seller for article', 'wp-content-pilot-pro' ), $campaign_id );
                $seller_node = $dom->find( '.mbg-nw', 0 );
                $seller_name = $seller_node->innertext;

                wpcp_logger()->info( __( 'Extracting location for article', 'wp-content-pilot-pro' ), $campaign_id );
                $location_node = $dom->find( "[itemprop='availableAtOrFrom']", 0 );
                $location      = $location_node->innertext;

                wpcp_logger()->info( __( 'Extracting condition for article', 'wp-content-pilot-pro' ), $campaign_id );
                $condition_node = $dom->find( "[itemprop='itemCondition']", 0 );
                $condition      = $condition_node->innertext;

                wpcp_logger()->info( __( 'Extracting return policy for article', 'wp-content-pilot-pro' ), $campaign_id );
                $return_policy_node = $dom->find( "#vi-ret-accrd-txt", 0 );
                $return_policy      = $return_policy_node->innertext;

                wpcp_logger()->info( __( 'Extracting area served for article', 'wp-content-pilot-pro' ), $campaign_id );
                $ships_to_node = $dom->find( "[itemprop='areaServed']", 0 );
                $ships_to      = trim( preg_replace( '{<span.*}s', '', $ships_to_node->innertext ) );

                wpcp_logger()->info( __( 'Extracting price for article', 'wp-content-pilot-pro' ), $campaign_id );
                $price_node = $dom->find( "[itemprop='price']", 0 );
                $html_price = $price_node->innertext;

                wpcp_logger()->info( __( 'Extracting listing type for article', 'wp-content-pilot-pro' ), $campaign_id );
                $listing_type_node = $dom->getElementById( 'bidBtn_btn' );
                if ( empty( $listing_type_node ) ) {
                    $listing_type = 'auction';
                } else {
                    $listing_type = 'buy it now';
                }

                $ebay_campaign_id = wpcp_get_settings( 'campaign_id', 'wpcp_settings_ebay', '0987654321' );

                //creating affiliate url from link
                $affiliate_url = preg_replace( "/%u([0-9a-f]{3,4})/i", "&#x\\1;", urldecode( $link->url ) );
                $url_parts     = parse_url( $affiliate_url );
                parse_str( $url_parts['fragment'], $query_parts );
                $affiliate_url = preg_replace( '/\?.*/', '', $affiliate_url );
                $affiliate_url = add_query_arg( array(
                    'mpre'   => urlencode( $url ),
                    'campid' => $ebay_campaign_id,
                    'toolid' => array_key_exists('038;toolid', $query_parts)? $query_parts['038;toolid']:''
                ), remove_query_arg( array( 'mpre', 'campid', 'toolid' ), esc_url( $affiliate_url ) ) );

                $url        = add_query_arg( array( 'campid' => $ebay_campaign_id ), remove_query_arg( array( 'campid' ), esc_url( $url ) ) );
                $meta_price = number_format( $link->meta['price'], 2 );

                wpcp_logger()->info( __( 'Combining all parts for article', 'wp-content-pilot-pro' ), $campaign_id );
                $article = array(
                    'title'           => $title,
                    'content'         => $description,
                    'image_url'       => $image_url,
                    'source_url'      => $url,
                    'affiliate_url'   => ( $affiliate_url != '' ) ? $affiliate_url : $url,
                    'seller_username' => $seller_name,
                    'seller_url'      => empty( $seller_name ) ? '' : esc_url( sprintf( "http://www.%s/usr/%s", $site, $seller_name ) ),
                    'date'            => get_date_from_gmt( $link->meta['publish_date'] ),
                    'location'        => $location,
                    'return_policy'   => $return_policy,
                    'ships_to'        => $ships_to,
                    'current_price'   => empty( $html_price ) ? $meta_price : $html_price,
                    'price_numeric'   => str_replace( ',', '', $meta_price ),
                    'bids'            => $link->meta['bids'],
                    'start_time'      => get_date_from_gmt( $link->meta['publish_date'] ),
                    'end_time'        => get_date_from_gmt( $link->meta['end_date'] ),
                    'deal_end_time'   => get_date_from_gmt( $link->meta['end_date'] ),
                    'listing_type'    => $listing_type,
                    'item_condition'  => $condition,
                );

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

                return apply_filters( 'wpcp_ebay_article', $article, $response, $campaign_id, $keyword );
            }
        }

        $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 $keyword
     *
     * @param $campaign_id
     *
     * @return array|bool|int|WP_Error
     * @throws ErrorException
     * @since 1.2.0
     *
     */
    protected function discover_links( $campaign_id, $keyword ) {
        $site             = wpcp_get_post_meta( $campaign_id, '_ebay_site', 'EBAY-US' );
        $order_by         = wpcp_get_post_meta( $campaign_id, '_order_by', '' );
        $listing_type     = wpcp_get_post_meta( $campaign_id, '_listing_type', 'all' );
        $category         = wpcp_get_post_meta( $campaign_id, '_category', '' );
        $page_key         = sanitize_key( '_page_' . $campaign_id . '_' . md5( $keyword ) );
        $page_number      = wpcp_get_post_meta( $campaign_id, $page_key, '1' );
        $top_rated        = wpcp_get_post_meta( $campaign_id, '_top_rated', '1' );
        $free_shipping    = wpcp_get_post_meta( $campaign_id, '_free_shipping', '1' );
        $ebay_campaign_id = wpcp_get_settings( 'campaign_id', 'wpcp_settings_ebay', '0987654321' );
        $ebay_app_id      = wpcp_get_settings( 'app_id', 'wpcp_settings_ebay', 'DeanDev07-ba44-495b-9106-d8d1c333fbb' );
        $min_price        = wpcp_get_post_meta( $campaign_id, '_min_price', '' );
        $max_price        = wpcp_get_post_meta( $campaign_id, '_max_price', '' );

        //$api_url = 'http://rest.ebay.com/epn/v1/find/item.rss';
        $api_url = 'https://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsAdvanced&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&REST-PAYLOAD=TRUE';

        $filter_number = 0;

        $query_args = array(
            'SECURITY-APPNAME'           => $ebay_app_id,
            'GLOBAL-ID'                  => $site,
            'campaignid'                 => $ebay_campaign_id,
            'paginationInput.pageNumber' => $page_number,
            'keywords'                   => urlencode( $keyword ),
            'sortOrder'                  => $order_by,
        );

        if ( ! empty( $category ) ) {
            $query_args['categoryId1'] = $category;
        }
        /**
         * Changed the parameters for the api
         * @since 1.1.7
         */
        if ( $top_rated == 'on' ) {
            $query_args["itemFilter($filter_number).name=TopRatedSellerOnly&itemFilter($filter_number).value(0)"] = 'true';
            $filter_number ++;
        }
        if ( $listing_type !== 'all' ) {
            $query_args["itemFilter($filter_number).name=ListingType&itemFilter($filter_number).value(0)"] = $listing_type;
            $filter_number ++;
        }
        if ( $free_shipping == 'on' ) {
            $query_args["itemFilter($filter_number).name=FreeShippingOnly&itemFilter($filter_number).value(0)"] = 'true';
            $filter_number ++;
        }
//        if ( $top_rated == 'on' ) {
//            $query_args['topRatedSeller'] = 'true';
//        }
//        if ( $listing_type !== 'all' ) {
//            $query_args['listingType1'] = $listing_type;
//        }
//        if ( $free_shipping == 'on' ) {
//            $query_args['freeShipping'] = 'true';
//        }
        /**
         * price filter
         * @since 1.1.7
         */
        if ( $min_price != '' && is_numeric( $min_price ) ) {
            $query_args["itemFilter($filter_number).name=MinPrice&itemFilter($filter_number).value(0)"] = $min_price;
        }
        if ( $max_price != '' && is_numeric( $max_price ) ) {
            $query_args["itemFilter($filter_number).name=MaxPrice&itemFilter($filter_number).value(0)"] = $max_price;
        }

        $query_args = apply_filters( 'wpcp_ebay_search_query_args', $query_args, $campaign_id, $keyword );
        $endpoint   = add_query_arg( $query_args, $api_url );
        wpcp_logger()->info( sprintf( __( "Searching for links [%s]", 'wp-content-pilot-pro' ), preg_replace( array( '/campaignid=([^&]+)/m', '/SECURITY-APPNAME=([^&]+)/m' ), array( 'campaignid=X', 'SECURITY-APPNAME=X' ), $endpoint ) ), $campaign_id );

        $curl = $this->setup_curl();
        $curl->get( $endpoint );
        wpcp_logger()->info( __( 'Getting response from request', 'wp-content-pilot-pro' ), $campaign_id );
        $response = $curl->getRawResponse();
        $response = json_decode( $response );
        error_log(print_r($response, true));
        //check error
        if ( $response->findItemsAdvancedResponse[0]->errorMessage ) {
            wpcp_logger()->error( sprintf( __( 'eBay returned an error %s', 'wp-content-pilot-pro' ), $response->findItemsAdvancedResponse[0]->errorMessage[0]->error[0]->message[0] ), $campaign_id );

            return false;
        }

        $items_count = count( $response->findItemsAdvancedResponse[0]->searchResult[0]->item );
        if ( $items_count == 0 ) {
            $this->deactivate_key( $campaign_id, $keyword );
            wpcp_logger()->error( __( 'No Item returned from Ebay, disabling for 1 hour', 'wp-content-pilot-pro' ), $campaign_id );

            return false;
        }
        $items   = apply_filters( 'wpcp_ebay_discovered_items', $response->findItemsAdvancedResponse[0]->searchResult[0]->item, $campaign_id, $keyword );
        $links   = [];
        $counter = 0;

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

            $title = $item->title[0];
            $url   = $item->viewItemURL[0];

            $meta              = [];
            $meta['id']        = $item->itemId[0];
            $meta ['subtitle'] = $item->subtitle[0];
            $meta ['category'] = $item->primaryCategory[0]->categoryName[0];
            $meta ['payment']  = isset( $item->paymentMethod[0] ) ? $item->paymentMethod[0] : '';
            $meta ['postal']   = $item->postalCode[0];
            $meta ['location'] = $item->location[0];

            $meta ['img']          = $item->galleryURL[0];
            $meta ['publish_date'] = str_replace( 'T', ' ', str_replace( 'Z', ' ', $item->listingInfo[0]->startTime[0] ) );
            $meta ['publish_date'] = str_replace( '.000', '', $meta ['publish_date'] );
            $meta ['bids']         = isset( $item->sellingStatus[0]->bidCount[0] ) ? $item->sellingStatus[0]->bidCount[0] : 0;
            $meta ['price']        = isset( $item->sellingStatus[0]->currentPrice[0]->__value__ ) ? $item->sellingStatus[0]->currentPrice[0]->__value__ : '';
            $meta ['bin']          = isset( $item->listingInfo[0]->buyItNowPrice[0]->__value__ ) ? $item->listingInfo[0]->buyItNowPrice[0]->__value__ : '';
            $meta ['end_date']     = str_replace( 'T', ' ', str_replace( 'Z', ' ', $item->listingInfo[0]->endTime[0] ) );
            $meta ['end_date']     = str_replace( '.000', '', $meta ['end_date'] );

            //skipping duplicate url
            if ( wpcp_is_duplicate_url( $url ) ) {
                continue;
            }

            //skipping duplicate title
            $skip = apply_filters( 'wpcp_skip_duplicate_title', true, $title, $campaign_id );
            if ( $skip ) {
                continue;
            }
            $data = array(
                'url'     => esc_url( $url ),
                'title'   => $title,
                'for'     => $keyword,
                'camp_id' => $campaign_id,
                'meta'    => $meta
            );

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

        }

        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 ), $counter, ( count( $items ) - $counter ) ), $campaign_id );

        return true;
    }

    /**
     * ebay sites
     * since 1.0.0
     */
    public function get_ebay_sites() {
        return array(
            'EBAY-US'   => 'eBay United States',
            'EBAY-IE'   => 'eBay Ireland',
            'EBAY-AT'   => 'eBay Austria',
            'EBAY-AU'   => 'eBay Australia',
            'EBAY-FRBE' => 'eBay BE',
            'EBAY-FRCA' => 'eBay CA',
            'EBAY-FR'   => 'ebay France',
            'EBAY-DE'   => 'eBay Germany',
            'EBAY-IT'   => 'eBay Italy',
            'EBAY-ES'   => 'eBay Spain',
            'EBAY-CH'   => 'eBay Switzerland',
            'EBAY-GB'   => 'eBay UK',
            'EBAY-N'    => 'eBay Netherlands',
        );
    }


    public function get_ebay_cats() {
        $cats = [
            ''       => "ALL",
            '20081'  => "Antiques",
            '550'    => "Art",
            '2984'   => "Baby",
            '267'    => "Books",
            '12576'  => "Business & Industrial",
            '625'    => "Cameras & Photo",
            '15032'  => "Cell Phones & Accessories",
            '11450'  => "Clothing, Shoes & Accessories",
            '11116'  => "Coins & Paper Money",
            '1'      => "Collectibles",
            '58058'  => "Computers/Tablets & Networking",
            '293'    => "Consumer Electronics",
            '14339'  => "Crafts",
            '237'    => "Dolls & Bears",
            '11232'  => "DVDs & Movies",
            '6000'   => "eBay Motors",
            '45100'  => "Entertainment Memorabilia",
            '172008' => "Gift Cards & Coupons",
            '26395'  => "Health & Beauty",
            '11700'  => "Home & Garden",
            '281'    => "Jewelry & Watches",
            '11233'  => "Music",
            '619'    => "Musical Instruments & Gear",
            '1281'   => "Pet Supplies",
            '870'    => "Pottery & Glass",
            '10542'  => "Real Estate",
            '316'    => "Specialty Services",
            '888'    => "Sporting Goods",
            '64482'  => "Sports Mem, Cards & Fan Shop",
            '260'    => "Stamps",
            '1305'   => "Tickets & Experiences",
            '220'    => "Toys & Hobbies",
            '3252'   => "Travel",
            '1249'   => "Video Games & Consoles",
            '99'     => "Everything Else",
        ];
        asort( $cats );

        return $cats;
    }

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

        return self::$_instance;
    }

}

WPCP_Ebay::instance();
