<?php
global $ytevo_curator;
$ytevo_curator = Ytevo_Curator::init();
global $ytevo_db_version;
$ytevo_db_version = '1.0';


class Ytevo_Curator {

    public static $ytevo_dashboard; 
    public static $curltimeout = 30;
     
    public static $ytevo_settings;  
    public static $ytevo_spinwriter;  
  
    public static $instance;
  
    public static function init() {
    
        if ( is_null( self::$instance ) )
            self::$instance = new Ytevo_Curator();
        
        return self::$instance;
    }
  
  
    // Constructor  
    function __construct() {
        //echo "Ron abc";exit;
    
        // create all the classes used by the plugin
        self::create_classes();
        
       
        add_filter( 'wp_insert_post_data', array( $this, 'check_values'), 10, 3 );
        // add action links to the Plugins List page
       
        add_filter( 'tube_vc_filter_post_pre_insert', array( $this, 'add_ez_content' ),10,5 );
        
        add_filter( 'artf_tube_vc_filter_post_pre_insert', array( $this, 'add_artforge_content' ),10,5 );

          
        //  WP Ajax stuff
        //  add_action( 'admin_enqueue_scripts', array( self::$ytevo_settings, 'ytevo_scripts') );
        // Create video post
        
        add_action('wp_ajax_get_subcat_by_ajax',array( self::$ytevo_settings,  'get_subcat_by_ajax_callback'));
        add_action('wp_ajax_nopriv_get_subcat_by_ajax',array( self::$ytevo_settings,  'get_subcat_by_ajax_callback'));
    } 
  
    function check_values($data, $post, $po){
      
       if( $po['ID'] ){
            $opost = get_post($po['ID']);
           // if($opost->post_excerpt == $data['post_excerpt']  ){
                $pattern = '/<p>.*?<\/p>(.*)/'; 
                $contenido = preg_replace($pattern, '$1', $data['post_content']);
                
                $tempcontent = wp_trim_words( $contenido, 40 );
              
                //$data['post_excerpt'] = self::cleaner($tempcontent);
           // }
       }
   
        return $data;

    }


    function cleaner($url) {
      $U = explode(' ',$url);

      $W =array();
      foreach ($U as $k => $u) {
        if (stristr($u,'https://www.youtube.com') || (count(explode('.',$u)) > 1)) {
          unset($U[$k]);
          return self::cleaner( implode(' ',$U));
        }
      }
      return implode(' ',$U);
    }


    /* Checking success code for Article Forge */
    function recursive_check_article_process($ref_key){
        $api_key = get_option('ytevo_articleforge_api_key');

        $url = 'https://af.articleforge.com/api/get_api_progress';
        $result2 = wp_remote_post( $url, array(
            'method'      => 'POST',
            'timeout'     => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking'    => true,
            'headers'     => array(),
            'body'        => array(
                'key' => $api_key,
                'ref_key' => $ref_key,
            ),
            'cookies'     => array()
            )
        );

        if ( is_wp_error( $result2 ) ) {
            $error_message = $result2->get_error_message();
            echo "Something went wrong: $error_message";
        } else {

            $data2 = json_decode($result2['body']);
            if($data2->api_status == '201'){
                return self::fetch_content_article($ref_key);
            }else{
                return self::recursive_check_article_process($ref_key);
            }
        }

        
    }


    /* Fetch content from Article Forge */
    function fetch_content_article($ref_key){
        $api_key = get_option('ytevo_articleforge_api_key');

        $url = 'https://af.articleforge.com/api/get_api_article_result';

        $result3 = wp_remote_post( $url, array(
            'method'      => 'POST',
            'timeout'     => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking'    => true,
            'headers'     => array(),
            'body'        => array(
                'key' => $api_key,
                'ref_key' => $ref_key,
            ),
            'cookies'     => array()
            )
        );

        
        if ( is_wp_error( $result3 ) ) {
            $error_message = $result3->get_error_message();
            echo "Something went wrong: $error_message";
        } else {

            $data3 = json_decode($result3['body']);
            if($data3->status == 'Success'){
                $data = $data3->article;
            }else{
                $data = '';
            }
            return $data;
        }

        // var_dump($data3);
        // exit;
        
    }

    /* Add content to post content */
    function add_artforge_content($my_post,$source_site,$creator_name, $ytpid,$vid){
        $api_key = get_option('ytevo_articleforge_api_key');
        $keyword = get_option('ytevo_articleforge_keyword');
        $subkeyword = get_option('ytevo_articleforge_subkeyword');
        $articleforge_length = get_option( 'ytevo_articleforge_content_length' );
        $articleforge_title = get_option( 'ytevo_articleforge_title' );
        $articleforge_image = get_option( 'ytevo_articleforge_image' );
        if($articleforge_title == 'on'){
            $title = 1;
        } else {
            $title = 0;
        }
        if($articleforge_image == 'on'){
            $image = 1.00;
        } else {
            $image = 0.00;
        }
        //echo "I am here".$keyword;exit;
        $data = '';
        $url = 'https://af.articleforge.com/api/initiate_article';
        $response = wp_remote_post( $url, array(
            'method'      => 'POST',
            'timeout'     => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking'    => true,
            'headers'     => array(),
            'body'        => array(
                'key' => $api_key,
                'keyword' => $keyword,
                'title' => $title,
                'image' => $image,
                'sub_keywords' => $subkeyword,
                'length' => $articleforge_length,
            ),
            'cookies'     => array()
            )
        );
        
        $data = '';         
        if ( is_wp_error( $response ) ) {
            $error_message = $response->get_error_message();
            echo "Something went wrong: $error_message";
        } else {

            $data = json_decode($response['body']);
        }


        $ref_key = '';
        if($data->status != 'Fail'){
            $ref_key = $data->ref_key;
        }


        $article_res = self::recursive_check_article_process($ref_key);
        //echo $article_res;exit;
        $article_content = $article_res;
        
        if($article_content){
            $my_post['post_content'] = $my_post['post_content'].'<br/><br/>'.$article_content; 
        }

        return $my_post;
    }
  
    function add_ez_content($my_post,$source_site,$creator_name, $ytpid,$vid){
        $en_ez =  get_option('ytevo_ezinearticles_enable');
        $spin_enable =  get_option('ytevo_spine_enable');


        if($en_ez) {
           global $wpdb;
           $limit = get_option('ytevo_default_ezinearticles_limit', 5);
           $table_name_articles = $wpdb->prefix . 'ytevo_ez_articles';

            if($ytpid){
             $articles = $wpdb->get_results( "SELECT * FROM $table_name_articles WHERE used = 0 AND cat=$ytpid LIMIT 0,$limit", OBJECT ); 
            }else{
             $articles = $wpdb->get_results( "SELECT * FROM $table_name_articles WHERE used = 0 LIMIT 0,$limit", OBJECT );  
            }
         
            if(empty($articles) || count($articles) < $limit ){
               $this::$ytevo_settings->generate_ez_contents(FALSE,$ytpid);
              if($ytpid){
                 $articles = $wpdb->get_results( "SELECT * FROM $table_name_articles WHERE used = 0 AND cat=$ytpid LIMIT 0,$limit", OBJECT ); 
              }else{
                 $articles = $wpdb->get_results( "SELECT * FROM $table_name_articles WHERE used = 0 LIMIT 0,$limit", OBJECT );  
              }
            }

         
            $ezcontent = '';
            $content = '';
            $pc = '';
            $ezprepare = array();
            foreach($articles as $article) {
                
                 $pc = $article->summery;
                 $ezprepare[] = $article->summery;
                 $content = "<b>{$article->title}</b><br/><p>$pc</p>";
                     $ezcontent .= "     <!-- wp:paragraph -->
            $content
            <!-- /wp:paragraph -->"; 
                   
                $data = [ 'used' => 1 ];
               $where = [ 'id' => $article->id ];
               $wpdb->update( $wpdb->prefix . 'ytevo_ez_articles', $data, $where );
             
            }


            if($spin_enable){
                $spinprecontent = implode(' sharifcrish. ', $ezprepare);
                $spresponse = $this::$ytevo_spinwriter->getUniqueVariation($spinprecontent);
                
                $spinrescontent = $spresponse['response'];
                $spinrescontentarray = explode(' sharifcrish. ', $spinrescontent);
                $ezcontent = '';
                $count = 0;
                foreach($articles as $article) {
                    $content = "<b>{$article->title}</b><br/><p>{$spinrescontentarray[$count]}</p>";
                    $ezcontent .= "     <!-- wp:paragraph -->
           $content
           <!-- /wp:paragraph -->"; 
                 $count++;
                }
                
            }



            $en_artf =  get_option('ytevo_articleforge_enable');

            if($en_artf){
                $api_key = get_option('ytevo_articleforge_api_key');
                $keyword = get_option('ytevo_articleforge_keyword');
                $subkeyword = get_option('ytevo_articleforge_subkeyword');
                $articleforge_length = get_option( 'ytevo_articleforge_content_length' );
                $articleforge_title = get_option( 'ytevo_articleforge_title' );
                $articleforge_image = get_option( 'ytevo_articleforge_image' );
                if($articleforge_title == 'on'){
                    $title = 1;
                } else {
                    $title = 0;
                }
                if($articleforge_image == 'on'){
                    $image = 1.00;
                } else {
                    $image = 0.00;
                }

                $url = 'https://af.articleforge.com/api/initiate_article';
                $response = wp_remote_post( $url, array(
                    'method'      => 'POST',
                    'timeout'     => 45,
                    'redirection' => 5,
                    'httpversion' => '1.0',
                    'blocking'    => true,
                    'headers'     => array(),
                    'body'        => array(
                        'key' => $api_key,
                        'keyword' => $keyword,
                        'title' => $title,
                        'image' => $image,
                        'sub_keywords' => $subkeyword,
                        'length' => $articleforge_length,
                    ),
                    'cookies'     => array()
                    )
                );
                
                $data = '';         
                if ( is_wp_error( $response ) ) {
                    $error_message = $response->get_error_message();
                    echo "Something went wrong: $error_message";
                } else {

                    $data = json_decode($response['body']);
                }

                $ref_key = '';
                if($data->status != 'Fail'){
                    $ref_key = $data->ref_key;
                }


                $article_res = self::recursive_check_article_process($ref_key);

                $article_content = $article_res;
                $ezcontent .= '<br/>'.$article_content;

                //print_r($ezcontent); exit;
            }


            $my_post['post_content'] = $my_post['post_content'].'<br/><br/>'.$ezcontent; 
       
       }

       //echo $ezcontent;exit;
      // echo "Ron Test 2";exit;

       return $my_post;
    }
  
 
  
    // Set up a bunch of constants used by the plugin
    private static function set_constants() {
  
        $constants = array(
          'YTEVO_CRUATOR_DIR' => plugin_dir_path( __FILE__ ),
          'YTEVO_CRUATOR_URL' => plugin_dir_url( __FILE__ ),
          'YTEVO_CRUATOR_SLUG' => 'ytevo-cruator',
          'YTEVO_CRUATOR_DASH_URL' => admin_url('admin.php?page=ytevo-cruator'),
          'YTEVO_CRUATOR_SETTINGS_URL' => admin_url('admin.php?page=ytevo-cruator'),
          'YTEVO_CRUATOR_IMPORT_SETTINGS_URL' => admin_url('admin.php?page=ytevo-cruator-settings&tab=import'),
          'YTEVO_CRUATOR_API_KEYS_URL' => admin_url('admin.php?page=ytevo-cruator-api-keys'),
          
          'YTEVO_CRUATOR_VIEW_SOURCES_URL' => admin_url( 'edit.php?post_type=ytevo_source' ),
          'YTEVO_CRUATOR_FIND_SOURCES_URL' => admin_url( 'admin.php?page=yt-evolution-find-sources' ),
          'YTEVO_CRUATOR_ADD_VIA_URL_URL' => admin_url( 'admin.php?page=yt-evolution-add-via-url' ),
          'YTEVO_CRUATOR_FIND_VIDEOS_URL' => admin_url( 'admin.php?page=yt-evolution-find-videos' ),
          'YTEVO_CRUATOR_SKIPPED_VIDEOS_URL' => admin_url( 'edit.php?post_type=ytevo_skipped_video' ),
          'YTEVO_CRUATOR_LOADER' => plugin_dir_url( __FILE__ ) . '/images/tube-loader.gif',
        );
    
        foreach ( $constants as $key => $value):
          
          if ( !defined( $key ) ) {
            define( $key, $value );
          }
          
        endforeach;
    }

    function load_textdomain() {
        load_plugin_textdomain( YTEVO_CRUATOR_SLUG, false, dirname( plugin_basename(__FILE__) ) . '/languages' );
    }
    
    // Load the text domain
    function load_ytevo_vc_textdomain() {
        load_plugin_textdomain('ytevo-curator', false, basename( dirname( __FILE__ ) ) . '/i18n' );
    }
  
  
    private static function create_classes() {

        // Get the Tube_Settings instance
        require_once YTEVO_CRUATOR_DIR . '/classes/class-ytevo-settings.php';
        self::$ytevo_settings = new Ytevo_Settings();
        $spin_enable =     get_option('ytevo_spine_enable');
        $spin_api =  get_option('ytevo_spine_api_key');
        $spin_email =  get_option('ytevo_spine_email');
        

        if($spin_enable){
        require_once YTEVO_CRUATOR_DIR . 'classes/SpinRewriterAPI.php';
       
         
        // Spin Rewriter API settings - authentication:
    	if(!$spin_email) $spin_email = "cderenberger@outlook.com";			// your Spin Rewriter email address goes here
    	if(!$spin_api) $spin_api = "6e316f1#783758c_632d03b?570ad75";	// your unique Spin Rewriter API key goes here
        
            
        $spinrewriter_api = new SpinRewriterAPI($spin_email, $spin_api);

        $protected_terms = " sharifcrish. ";
    	$spinrewriter_api->setProtectedTerms($protected_terms);
            $spinrewriter_api->setAutoProtectedTerms(false);
    	
    	// (optional) Set the confidence level of the One-Click Rewrite process.
    	$spinrewriter_api->setConfidenceLevel("medium");
    	
    	// (optional) Set whether the One-Click Rewrite process uses nested spinning syntax (multi-level spinning) or not.
    	$spinrewriter_api->setNestedSpintax(true);
    	
    	// (optional) Set whether Spin Rewriter rewrites complete sentences on its own.
    	$spinrewriter_api->setAutoSentences(false);
    	
    	// (optional) Set whether Spin Rewriter rewrites entire paragraphs on its own.
    	$spinrewriter_api->setAutoParagraphs(false);
    	
    	// (optional) Set whether Spin Rewriter writes additional paragraphs on its own.
    	$spinrewriter_api->setAutoNewParagraphs(false);
    	
    	// (optional) Set whether Spin Rewriter changes the entire structure of phrases and sentences.
    	$spinrewriter_api->setAutoSentenceTrees(false);

    	// (optional) Sets whether Spin Rewriter should only use synonyms (where available) when generating spun text.
    	$spinrewriter_api->setUseOnlySynonyms(false);

    	// (optional) Sets whether Spin Rewriter should intelligently randomize the order of paragraphs and lists when generating spun text.
    	$spinrewriter_api->setReorderParagraphs(false);
             self::$ytevo_spinwriter = $spinrewriter_api;

        }
  }

  // function to test the autosycn
  function test_autosync() {
  
    self::$ytevo_import_cron -> do_autosync();
  
  }
  
  
  // Create the Admin Menu for the plugin
  function create_ytevo_vc_admin_menu() {

    // Main Menu Page
    $menu_page = add_menu_page(
      __('YTEvo-Curator', 'ytevo-curator'), // The Page title
      __('YTEvo-Curator', 'ytevo-curator'), // The Menu Title
      'publish_posts', // The capability required for access to this item
      YTEVO_CRUATOR_SLUG, // the slug to use for the page in the URL
      array( $this::$ytevo_settings, 'render_options_page_settings' ),  // The function to call to render the page
      "dashicons-format-video",
      58 // Position
    );      
  
    // Load the Styes / JS conditionally
    add_action( 'load-' . $menu_page, array( $this, 'load_ytevo_vc_admin_styles') );
    add_action( 'load-' . $menu_page, array( $this::$ytevo_settings, 'ytevo_scripts') );
              
  }
  
  
  // Customize the Admin menu
  function customize_ytevo_vc_admin_menu(){    
      
      // customize the menu
      global $submenu;   
     
      if ( 
        isset( $submenu[YTEVO_CRUATOR_SLUG] )
         && ( current_user_can( 'manage_options' ) ||  current_user_can( 'publish_posts' ) )
       
       ):
        
        $curator_submenu = $submenu[YTEVO_CRUATOR_SLUG];
        
        // create a separator device
        $separator = array(
          '<span class="tube-vc-menu-separator"></span>',
          'publish_posts',
          '#',
          NULL        
        );
        
          
        // change the name of first menu item
        $curator_submenu[0][0] = __( 'Dashboard', 'yt-revolution' );
          
        if( current_user_can( 'manage_options' ) ):
        
          // Do something, for admins only
          
          $revised_menu[] = $curator_submenu[0]; // Dashboard
          
          $revised_menu[] = $separator;     
          
          $revised_menu[] = $curator_submenu[6]; // Your Channels
          
          $revised_menu[] = $curator_submenu[5]; // Add Channels
          
          $revised_menu[] = $separator;     
          
          $revised_menu[] = $curator_submenu[3]; // Add via URL
          
          $revised_menu[] = $curator_submenu[4]; // Search Videos
          
          $revised_menu[] = $curator_submenu[7]; // Skipped Videos
          
          $revised_menu[] = $separator;     
          
          $revised_menu[] = $curator_submenu[1];  // Settings
          
          $revised_menu[] = $curator_submenu[2];  // API Keys 
        
        elseif ( current_user_can( 'publish_posts' ) ):
          
          $revised_menu[] = $curator_submenu[0]; // Dashboard
          
          $revised_menu[] = $separator;     
          
          $revised_menu[] = $curator_submenu[3]; // Your Channels
          
          $revised_menu[] = $separator;     
          
          $revised_menu[] = $curator_submenu[1]; // Add via URL
          
          $revised_menu[] = $curator_submenu[2]; // Search Videos
          
          $revised_menu[] = $curator_submenu[4]; // Skipped Videos
          
        
        endif;
          
        $submenu[YTEVO_CRUATOR_SLUG] = $revised_menu;

      endif;
      
  }

  
  
  // Main Tube Admin CSS
  function load_ytevo_vc_admin_styles(){
      add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_ytevo_vc_admin_styles') );
  }
      
  function enqueue_ytevo_vc_admin_styles() {
      wp_register_style(
        YTEVO_CRUATOR_SLUG, 
        plugins_url('/css/style.css', __FILE__), 
        array(), 
        '1.0.0'
     );
     wp_enqueue_style(YTEVO_CRUATOR_SLUG);
     
  }
  
  
  // add action links to the Plugins List page
  function add_ytevo_vc_action_links ( $links ) {
      
     $mylinks = array(
       '<a href="' . YTEVO_CRUATOR_DASH_URL . '">Dashboard</a>',
       '<a href="' . YTEVO_CRUATOR_SETTINGS_URL . '">Settings</a>'
       );
       
      return array_merge( $links, $mylinks );
      
  }
 
}