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

    /**
     * WPCP_Reddit constructor.
     */
    public function __construct() {
        parent::__construct( 'reddit' );
    }

    /**
     * @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' ),
            'author_name' => __( 'Author Name', 'wp-content-pilot-pro' ),
            'author_link' => __( 'Author Link', 'wp-content-pilot-pro' ),
            'embed_html'  => __( 'Embed Media', 'wp-content-pilot-pro' ),
            'item_gif'    => __( 'Reddit gif image', 'wp-content-pilot-pro' ),
            'item_mp4'    => __( 'Reddit mp4 video', 'wp-content-pilot-pro' ),
            'item_link'   => __( 'Item Link', 'wp-content-pilot-pro' ),
            'item_date'   => __( 'Item Date', 'wp-content-pilot-pro' )
        );
    }

    /**
     * @return string
     * @since 1.1.0
     */
    public function get_default_template() {
        $template
            = <<<EOT
<img src="{image_url}"><br>
{content}<br>
{embed_html}<br>
{item_gif}<br>
{item_mp4}<br>
<a href="{item_link}">View Reddit</a> by <a href="{author_link}">{author_name}</a> - <a href="{source_url}" target="_blank">Source</a>
EOT;

        return $template;
    }

    /**
     * @param $post
     */
    public function add_campaign_option_fields( $post ) {
        echo WPCP_HTML::text_input( array(
            'label'    => __( 'Reddit page url', 'wp-content-pilot-pro' ),
            'name'     => '_page_url',
            'required' => true,
            'desc'     => __( 'Copy the reddit page url from where you want to post', 'wp-content-pilot-pro' ),
            'attrs'    => array(
                'required' => 'required'
            )
        ) );
    }

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

    /**
     * @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.2.0
     */
    public function get_post( $campaign_id ) {
        wpcp_logger()->info( __( 'Loaded Reddit Campaign', 'wp-content-pilot-pro' ), $campaign_id );

        $page_urls = $this->get_campaign_meta( $campaign_id, '_page_url' );
        if ( empty( $page_urls ) ) {
            return new WP_Error( 'missing-data', __( 'Campaign do not have page url to proceed, please set page url', 'wp-content-pilot-pro' ) );
        }

        if ( empty( $page_urls ) ) {
            wpcp_disable_campaign( $campaign_id );
            $message = __( 'Campaign do not have any source page url, disabling campaign', 'wp-content-pilot-pro' );
            wpcp_logger()->error( $message, $campaign_id );

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

        foreach ( $page_urls as $page_url ) {
            wpcp_logger()->info( sprintf( 'Looping through page url [ %s ]', $page_url ), $campaign_id );
            if ( $this->is_deactivated_key( $campaign_id, $page_url ) ) {
                wpcp_logger()->error( sprintf( __( 'The page_url is deactivated for 1 hr because last time could not find any article with url [%s]', 'wp-content-pilot-pro' ), $page_url ), $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( $page_url, $campaign_id );
            if ( empty( $links ) ) {
                wpcp_logger()->info( __( 'No cached links in store. Generating new links..', 'wp-content-pilot-pro' ), $campaign_id );
                $this->discover_links( $campaign_id, $page_url );
                $links = $this->get_links( $page_url, $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' => '' ] );

                //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( __( 'Combining all parts for article', 'wp-content-pilot-pro' ), $campaign_id );
                $article = array(
                    'title'       => $title,
                    'content'     => @$link->meta['content'],
                    'image_url'   => @$link->meta['image_url'],
                    'source_url'  => $link->url,
                    'author_name' => @$link->meta['author_name'],
                    'author_link' => @$link->meta['author_link'],
                    'embed_html'  => @$link->meta['embed_html'],
                    'item_gif'    => @$link->meta['item_gif'],
                    'item_mp4'    => @$link->meta['item_mp4'],
                    'item_link'   => @$link->meta['item_link'],
                    'item_date'   => get_date_from_gmt( gmdate( 'Y-m-d H:i:s', $link->meta['item_date'] ) )
                );

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

    /**
     * Discover new links
     *
     * @param $campaign_id
     * @param $page_url
     *
     * @return bool
     * @since 1.2.0
     */
    protected function discover_links( $campaign_id, $page_url ) {
        $page_key    = $this->get_unique_key( $page_url );
        $query_after = wpcp_get_post_meta( $campaign_id, $page_key, '' );
        $api_url     = untrailingslashit( $page_url ) . '.json';
        $query_args  = array(
            'after' => $query_after
        );
        $end_point   = add_query_arg( $query_args, $api_url );

        wpcp_logger()->info( sprintf( __( 'Requesting urls from reddit [%s]', 'wp-content-pilot-pro' ), $end_point ), $campaign_id );

        $curl = $this->setup_curl();
        $curl->get( $end_point );
        $response = $curl->getResponse();

        if ( $curl->isError() ) {
            $notice = sprintf( __( 'Error in retrieving items [%s]', 'wp-content-pilot-pro' ), $curl->getErrorMessage() );
            wpcp_logger()->error( $notice, $campaign_id );
            $this->deactivate_key( $campaign_id, $page_url );

            return false;
        }

        wpcp_logger()->info( __( 'Getting valid response from reddit', 'wp-content-pilot-pro' ), $campaign_id );
        $items    = $response->data->children;
        $inserted = 0;

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

            $image = ! empty( $item->preview->images[0]->source->url ) ? $item->preview->images[0]->source->url : '';

            $gif = ! empty( $item->preview->images[0]->variants->gif->source->url ) ? $item->preview->images[0]->variants->gif->source->url : '';
            $mp4 = ! empty( $item->preview->images[0]->variants->mp4->source->url ) ? $item->preview->images[0]->variants->mp4->source->url : '';

            /* reddit gifs */
            $gif = '<img src="' . $gif . '">';

            /* fallback media */
            if ( empty( $gif ) and empty( $mp4 ) and ! empty( $item->media->reddit_video->fallback_url ) ) {
                $mp4 = $item->media->reddit_video->fallback_url;
            }

            $mp4 = ! empty( $mp4 ) ? '<video controls="controls"><source src="' . $mp4 . '" type="video/mp4"></video>' : '';

            /* external media embed */
            $embed = '';
            if ( ! empty( $item->media->oembed->html ) && ! stristr( $item->media->oembed->html, 'embedly-embed' ) ) {
                $embed = html_entity_decode( $item->media->oembed->html );
            }

            /* item link */
            $link      = 'https://reddit.com' . $item->permalink;
            $item_link = $link;

            /*Item Date */
            $item_date = $item->created_utc;

            /* author link */
            $author_link = 'https://reddit.com/user/' . $item->author;

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


            $meta = [
                'author_name' => $item->author,
                'author_link' => $author_link,
                'embed_html'  => $embed,
                'item_gif'    => $gif,
                'item_mp4'    => $mp4,
                'content'     => $content,
                'image_url'   => $image,
                'item_link'   => $item_link,
                'item_date'   => $item_date
            ];

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

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

        }

        wpcp_update_post_meta( $campaign_id, $page_key, $response->data->after );
        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;
    }


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

        return self::$_instance;
    }

}

WPCP_Reddit::instance();
