<?php

/**
 * Sets the post status to published
 */
function hide_publishing_actions(){
        $my_post_type = 'post';
        global $post;
        if($post->post_type == $my_post_type && $post->post_status == 'publish' || $post->post_status == 'draft' || $post->post_status == 'trash'){
            echo '
                <style type="text/css">
                    #mycp-1
					{
                        display:none;
                    }
                </style>
            ';
        }
}
add_action('admin_head-post.php', 'hide_publishing_actions');
add_action('admin_head-post-new.php', 'hide_publishing_actions');


add_action( 'wp_ajax_nopriv_wpch_spinrewriter_setting', 'myajax_wpch_spinrewriter_setting' );
add_action('wp_ajax_wpch_spinrewriter_setting', 'myajax_wpch_spinrewriter_setting');

function myajax_wpch_spinrewriter_setting ()
{
	$wpch_spinrewriter_email = $_POST['ajax_spinrewriter_email'];
	$wpch_spinrewriter_api_key = $_POST['ajax_spinrewriter_api_key'];
	
    $wpch_spinrewriter_email = update_option('wpch_spinrewriter_email',$wpch_spinrewriter_email);
    $wpch_spinrewriter_api_key = update_option('wpch_spinrewriter_api',$wpch_spinrewriter_api_key);
	
	if($wpch_spinrewriter_email || $wpch_spinrewriter_api_key)
	{?>
	<div class="wrap">
		<div class="updated"><p>Setting is saved</p></div>
	</div>
	<?php 
	}
	else
	{?>
	<div class="wrap">
		<div class="error"><p>Setting is already saved</p></div>
	</div>
	<?php } ?>		
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_wpch_perfect_tense_setting', 'myajax_wpch_perfect_tense_setting' );
add_action('wp_ajax_wpch_perfect_tense_setting', 'myajax_wpch_perfect_tense_setting');

function myajax_wpch_perfect_tense_setting()
{
	$wpch_perfect_api_key = $_POST['ajax_perfect_api_key'];
	$wpch_perfect_app_key = $_POST['ajax_perfect_app_key'];
	
    $wpch_perfectapi_key = update_option('wpch_perfect_api_key',$wpch_perfect_api_key);
    $wpch_perfectapp_key = update_option('wpch_perfect_app_key',$wpch_perfect_app_key);
	
	if($wpch_perfectapi_key || $wpch_perfectapp_key)
	{?>
	<div class="wrap">
		<div class="updated"><p>Setting is saved</p></div>
	</div>
	<?php 
	}
	else
	{?>
	<div class="wrap">
		<div class="error"><p>Setting is already saved</p></div>
	</div>
	<?php } ?>		
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_mych_get_ezine_subcat', 'myajax_mych_get_ezine_subcat' );
add_action('wp_ajax_mych_get_ezine_subcat', 'myajax_mych_get_ezine_subcat');

function myajax_mych_get_ezine_subcat()
{
	global $wpdb;
	
	$api_key = get_option('wpch_ezinearticle_app_key');
	$mych_subcatid = $_REQUEST['ajax_mych_category_id'];
	
	if(!empty($api_key)){
		$url = 'https://api.ezinearticles.com/api.php?search=categories&response_format=json&key='.$api_key.'&category='.$mych_subcatid;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		$data = curl_exec($ch);
		curl_close($ch);
		$sub_category=json_decode($data);		
	}

	$subcateg = $sub_category->categories[0]->category->subcategory;
	
	if(!empty($subcateg)) {
	?>
	<select id="select_ezine_subcategory_id_setting" name="select_ezine_subcategory_name_setting">								
	  <?php
		foreach($subcateg as $subcateg1)
		{
		?>															
		<option value="<?php echo str_replace(" ", "-", $subcateg1); ?>" ><?php echo $subcateg1; ?></option>	
		<?php
		}		
	  ?>
	</select>
	<?php
	}
	exit;
}

add_action( 'wp_ajax_nopriv_wpch_ezine_articles_setting', 'myajax_wpch_ezine_articles_setting' );
add_action('wp_ajax_wpch_ezine_articles_setting', 'myajax_wpch_ezine_articles_setting');

function myajax_wpch_ezine_articles_setting()
{
	global $wpdb;
	
	$ezine_articles_api_key = $_POST['ajax_ezine_articles_api_key'];
	$ezine_articles_enable = $_POST['ajax_ezine_enable_articles'];
	$ezine_articles_limit = $_POST['ajax_ezine_article_limit'];
	$ezine_category_id_setting = $_POST['ajax_ezine_category_id_setting'];
	$ezine_subcategory_id_setting = $_POST['ajax_ezine_subcategory_id_setting'];

	$postmeta_channel_categ_id = get_posts(array(
        'meta_key' => 'mych_channels_catid',
        'suppress_filters' => true,
		'post_type' => 'mych-ytube-channels'
    ));
	
	foreach ($postmeta_channel_categ_id as $postmeta_channel_categ_id1)
	{
		$post_ids = $postmeta_channel_categ_id1->ID;
		update_post_meta( $post_ids, 'mych_channels_catid', $ezine_category_id_setting);		
		update_post_meta( $post_ids, 'mych_ezine_subcategory_name', $ezine_subcategory_id_setting);				
	}	
	
    $wpch_ezine_articles_key = update_option('wpch_ezinearticle_app_key',$ezine_articles_api_key);
    $wpch_ezine_articles_enable = update_option('wpch_articleezine_enable',$ezine_articles_enable);
    $wpch_ezine_articles_limit = update_option('wpch_articleezine_limit',$ezine_articles_limit);
    $wpch_ezine_category_id_setting = update_option('wpch_articleezine_category_setting',$ezine_category_id_setting);
    $wpch_ezine_subcategory_id_setting = update_option('wpch_articleezine_subcategory_setting',$ezine_subcategory_id_setting);

	
	$category='';

	if(!empty($ezine_articles_api_key)){
		$url='http://api.ezinearticles.com/api.php?search=categories&category=&response_format=json&key='.$ezine_articles_api_key;            
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		$data = curl_exec($ch);
		curl_close($ch);
		$categories1 = json_decode($data);
		if(!empty($categories1->categories))
		{		
			$category = $categories1->categories;
		}
	}
	
	if(!empty($category))
	{
		$result_table_ez = array();
		
		for ($x = 1; $x <= 15; $x++)
		{			
			$url_table_ez = 'http://api.ezinearticles.com/api.php?search=articles&category='.$ezine_category_id_setting.'&subcategory='.$ezine_subcategory_id_setting.'&page='.$x.'&response_format=json&key='.$ezine_articles_api_key;
			$ch_table_ez = curl_init($url_table_ez);
			curl_setopt($ch_table_ez, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch_table_ez, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch_table_ez, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch_table_ez, CURLOPT_SSL_VERIFYHOST, 0);
			$data_table_ez = curl_exec($ch_table_ez);
			curl_close($ch_table_ez);
			$mych_ezine_article_result_table_ez = json_decode($data_table_ez);
			foreach($mych_ezine_article_result_table_ez->articles as $mych_ezine_article_result_table_ezs)
			{
				if(!empty($mych_ezine_article_result_table_ezs->article))
				{
					$result_table_ez[] = $mych_ezine_article_result_table_ezs->article;
				}
			}
		}
		
		$ez_table_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_ezarticles WHERE cat = '".$ezine_category_id_setting."' AND scat = '".$ezine_subcategory_id_setting."' AND used = 0");				
		$count_ez_table_result_detail = count($ez_table_result_detail);
		//echo "Count-".$count_ez_table_result_detail;
		
		if($count_ez_table_result_detail < 50)
		{
			if(!empty($result_table_ez))
			{
				foreach($result_table_ez as $result_table_ezs)
				{
					$aid = $result_table_ezs->id;
					$title = $result_table_ezs->title;
					$summary = $result_table_ezs->summary;
					$url = $result_table_ezs->url;
					$used = 0;
					$date_ez = date('Y-m-d H:i:s');
					
					$mych_ezine_table = $wpdb->base_prefix . "mych_ezarticles";
		
					$mych_ezine_data=array(
										'aid' => $aid, 
										'title' => $title, 
										'summary' => $summary, 
										'cat' => $ezine_category_id_setting, 
										'scat' => $ezine_subcategory_id_setting, 
										'url' => $url, 
										'schedule_date' => $date_ez, 
										'used' => $used,
									   );

					$wpdb->insert( $mych_ezine_table, $mych_ezine_data); 
					
					$wpdb->query($wpdb->prepare("DELETE FROM $mych_ezine_table WHERE used = %d",'1'));				
				}			
			}		
		}
		if($wpch_ezine_articles_key || $wpch_ezine_articles_enable || $wpch_ezine_articles_limit || $wpch_ezine_category_id_setting || $wpch_ezine_subcategory_id_setting)
		{?>
		<div class="wrap">
			<div class="updated"><p>Setting is saved</p></div>
		</div>
		<?php 
		}
		else
		{?>
		<div class="wrap">
			<div class="error"><p>Setting is already saved</p></div>
		</div>
		<?php } 
	}
	else {
	?>		
		<div class="wrap">
			<div class="error"><p>Key is not valid . Please check .</p></div>
		</div>
	<?php } ?>
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_wpch_article_forge_setting', 'myajax_wpch_article_forge_setting' );
add_action('wp_ajax_wpch_article_forge_setting', 'myajax_wpch_article_forge_setting');

function myajax_wpch_article_forge_setting()
{
	$article_forge_enable = $_POST['ajax_article_forge_enable'];
	$article_forge_api_key = $_POST['ajax_article_forge_api_key'];
	$article_forge_add_title = $_POST['ajax_article_forge_add_title'];
	$article_forge_add_image = $_POST['ajax_article_forge_add_image'];
	$article_forge_content_length = $_POST['ajax_article_forge_content_length'];
	$article_forge_setting_keyword = $_POST['ajax_article_forge_setting_keyword'];
	$article_forge_setting_subkey = $_POST['ajax_article_forge_setting_subkey'];

	$article_forge_setting_subkey1 = preg_replace('/\s*,\s*/', ',', $article_forge_setting_subkey);

    $wpch_article_forge_enable = update_option('wpch_articleforge_enable',$article_forge_enable);
    $wpch_article_forge_key = update_option('wpch_articleforge_app_key',$article_forge_api_key);
    $wpch_article_forge_title = update_option('wpch_articleforge_title',$article_forge_add_title);
    $wpch_article_forge_image = update_option('wpch_articleforge_image',$article_forge_add_image);
    $wpch_article_forge_content_length = update_option('wpch_articleforge_length',$article_forge_content_length);
    $wpch_articleforge_setting_keyword = update_option('wpch_articleforge_setting_keyword',$article_forge_setting_keyword);
    $wpch_articleforge_setting_sub_key = update_option('wpch_articleforge_setting_sub_key',$article_forge_setting_subkey1);
	
	if($wpch_article_forge_enable || $wpch_article_forge_key || $wpch_article_forge_title || $wpch_article_forge_image || $wpch_article_forge_content_length || $wpch_articleforge_setting_keyword || $wpch_articleforge_setting_sub_key)
	{?>
	<div class="wrap">
		<div class="updated"><p>Setting is saved</p></div>
	</div>
	<?php 
	}
	else
	{?>
	<div class="wrap">
		<div class="error"><p>Setting is already saved</p></div>
	</div>
	<?php } ?>		
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_wpch_article_builder_setting', 'myajax_wpch_article_builder_setting' );
add_action('wp_ajax_wpch_article_builder_setting', 'myajax_wpch_article_builder_setting');

function myajax_wpch_article_builder_setting()
{
	$article_builder_enable = $_POST['ajax_article_builder_enable'];
	$articlebuilder_username = $_POST['ajax_articlebuilder_username'];
	$articlebuilder_password = $_POST['ajax_articlebuilder_password'];
	$articlebuilder_limit = $_POST['ajax_articlebuilder_limit'];
	$articlebuilder_category = $_POST['ajax_articlebuilder_category'];

    $wpch_article_builder_enable = update_option('wpch_articlebuilder_enable',$article_builder_enable);
    $wpch_articlebuilder_username = update_option('wpch_articlebuilder_username',$articlebuilder_username);
    $wpch_articlebuilder_password = update_option('wpch_articlebuilder_passowrd',$articlebuilder_password);
    $wpch_articlebuilder_limit = update_option('wpch_articlebuilder_limit',$articlebuilder_limit);
    $wpch_articlebuilder_category = update_option('wpch_articlebuilder_category',$articlebuilder_category);
	
	if($wpch_article_builder_enable || $wpch_articlebuilder_username || $wpch_articlebuilder_password || $wpch_articlebuilder_limit || $wpch_articlebuilder_category)
	{?>
	<div class="wrap">
		<div class="updated"><p>Setting is saved</p></div>
	</div>
	<?php 
	}
	else
	{?>
	<div class="wrap">
		<div class="error"><p>Setting is already saved</p></div>
	</div>
	<?php } ?>		
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_wpch_ytube_setting', 'myajax_wpch_ytube_setting' );
add_action('wp_ajax_wpch_ytube_setting', 'myajax_wpch_ytube_setting');

function myajax_wpch_ytube_setting()
{
	$wpch_ytube_api_key = $_POST['ajax_ytube_api_key'];		
	$wpch_ytube_enable = $_POST['ajax_ytube_enable'];
	
    $wpch_ytubeapi_key = update_option('wpch_ytube_api_key',$wpch_ytube_api_key);
    $wpch_ytube_enable_update = update_option('wpch_ytube_enable',$wpch_ytube_enable);
	
	if($wpch_ytube_enable_update || $wpch_ytubeapi_key)
	{?>
	<div class="wrap">
		<div class="updated"><p>Setting is saved</p></div>
	</div>
	<?php 
	}
	else
	{?>
	<div class="wrap">
		<div class="error"><p>Setting is already saved</p></div>
	</div>
	<?php } ?>		
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 8000); // <-- time in milliseconds
	});
	</script>
	<?php 
	exit;
}

add_action( 'wp_ajax_nopriv_ch_get_subcat', 'myajax_wpch_get_subcat' );
add_action('wp_ajax_ch_get_subcat', 'myajax_wpch_get_subcat');

function myajax_wpch_get_subcat ()
{
	include_once("template/class/afe_blog.php"); 

    $afe_blog_main=new afeblogs();

	$afe_catid = $_REQUEST['afe_subcat_id'];
	if($afe_catid){
		$afe_sub_catgories=$afe_blog_main->afe_article_category($afe_catid);
	}
	if(is_array($afe_sub_catgories)){
		echo '<ul style="padding: 10px;margin-top:10px;column-count:2;">';
		
		foreach ( $afe_sub_catgories as $afe_subcatgorie ) {
			$checked= ' ';
			if (@in_array($afe_subcatgorie->id)) {
				$checked="checked";
			}
			echo '<li><input type="checkbox" name="afe_subcat[]" class="afe_subcat_check" value="'.$afe_subcatgorie->id.'" id="'.$afe_subcatgorie->cat_name.'" '.$checked.' required> <label style="margin:0 auto !important;" for="'.$afe_subcatgorie->cat_name.'">'.$afe_subcatgorie->cat_name.'</label></li>';
		}
		echo '</ul>';
	}
	exit;
}

add_action( 'wp_ajax_nopriv_ch_get_search_result', 'myajax_wpch_get_search_result' );
add_action('wp_ajax_ch_get_search_result', 'myajax_wpch_get_search_result');

function myajax_wpch_get_search_result ()
{
	include_once("template/class/afe_blog.php"); 
    $afe_blog_main1=new afeblogs();

    $ajax_check_val =  $_POST['afe_ajax_array_val'];
    $ajax_key =  $_POST['afe_ajax_keyword'];
    
    $afe_blog_main1->afe_search_result($ajax_check_val,$ajax_key);
    ?>    
    <table id="exampless" class="display" style="width:100%">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
              <?php
                    global $wpdb;
                     $afe_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE type = 'article' ORDER BY id ASC");
                    if(!empty($afe_result_detail))
                    {
                        foreach($afe_result_detail as $afe_result_detail1)
                        {  
							if(!empty($afe_result_detail1->title)) {
                    ?>
                        <tr>
                            <td><span style="color:firebrick;"><?php echo $afe_result_detail1->title; ?></span></td>
                            <td><?php echo wp_trim_words( $afe_result_detail1->short_des, 30 ,'...' ); ?></td>
                            <td><input type=checkbox name=afe_check_vals[] class=afe_check_val value=<?php echo $afe_result_detail1->id;?> /></td>                              
                        </tr>
							<?php } } } ?>
            </tbody>
    </table>        
    <script>
        jQuery(document).ready(function($) {
            $('#exampless').DataTable();
        } );
    </script>
<?php    
exit;
}

add_action( 'wp_ajax_nopriv_ch_get_check_result', 'myajax_wpch_get_check_result' );
add_action('wp_ajax_ch_get_check_result', 'myajax_wpch_get_check_result');

function myajax_wpch_get_check_result ()
{
    global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);

    include_once("template/class/afe_blog.php"); 
    $spin_blog_aticle=new afeblogs();

    $ajax_check_result =  $_POST['afe_ajax_check_array_val'];

	$afe_check_val = str_replace( ',', ' ', $ajax_check_result );
    $afe_check_split_string=explode(" ",$afe_check_val);
    
    foreach($afe_check_split_string as $afe_check_split_string1)
    {
        $afe_saved_table = $wpdb->base_prefix . "ch_saved_result";
        $afe_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE id = '".$afe_check_split_string1."' AND type = 'article'");
        $afe_count_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_saved_result WHERE catg_id = '".$afe_check_result_detail[0]->id."' AND type = 'article'");
        
        if (count($afe_count_check_result_detail) == 0)
        {            
            if(@$_POST['afe_ajax_spin_content_article'] == 'on')
            {
                $spinned_short_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->short_des);
                $spinned_long_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->long_desc);
    
                $orig_string_article = ["&lt;", "&gt;"];
                $repl_string_article   = ["<", ">"];
    
                $spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$spinned_short_desc1);
                $spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$spinned_long_desc1);
            }
            elseif(@$_POST['afe_ajax_spin_content_rewriter'] == 'on')
            {
                $spinned_short_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->short_des);
                $spinned_long_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->long_desc);
    
                $orig_string_article = ["&lt;", "&gt;"];
                $repl_string_article   = ["<", ">"];
    
				// Spin Rewriter API settings - authentication:
				$result_spinrewriter_email1 = get_option( 'wpch_spinrewriter_email' );
				$result_spinrewriter_api1 = get_option( 'wpch_spinrewriter_api' );

				if(!empty($result_spinrewriter_email1) && !empty($result_spinrewriter_api1)) 
				{ 
					$afe_spinrewriter_api=$spin_blog_aticle->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$spinned_short_desc1);

					if(!empty($afe_spinrewriter_api))
					{
						$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$afe_spinrewriter_api['response']);
					}
					else
					{
						$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$spinned_short_desc1);
					}
					
					$afe_spinrewriter_api_long=$spin_blog_aticle->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$spinned_long_desc1);

					if(!empty($afe_spinrewriter_api_long))
					{
						$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$afe_spinrewriter_api_long['response']);				
					}						
					else
					{
						$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$spinned_long_desc1);				
					}
				}				
				else
				{
					$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$spinned_short_desc1);
					$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$spinned_long_desc1);				
				}					
            }
            elseif(@$_POST['afe_ajax_spin_content_perfecttense'] == 'on')
            {
                $spinned_short_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->short_des);
                $spinned_long_desc1 = $spin_blog_aticle->spin_article($afe_check_result_detail[0]->long_desc);
    
                $orig_string_article = ["&lt;", "&gt;"];
                $repl_string_article   = ["<", ">"];
    
				// Spin Rewriter API settings - authentication:
				$result_perfecttense_api = get_option( 'wpch_perfect_api_key' );
				$result_perfecttense_app = get_option( 'wpch_perfect_app_key' );

				if(!empty($result_perfecttense_api) && !empty($result_perfecttense_app)) 
				{ 
					$afe_perfecttense_short = $spin_blog_aticle->perfecttense_afe($result_perfecttense_api,$result_perfecttense_app,$spinned_short_desc1);

					if(!empty($afe_perfecttense_short))
					{
						$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$afe_perfecttense_short);
					}
					else
					{
						$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$spinned_short_desc1);
					}
					
					$afe_perfecttense_long = $spin_blog_aticle->perfecttense_afe($result_perfecttense_api,$result_perfecttense_app,$spinned_long_desc1);

					if(!empty($afe_perfecttense_long))
					{
						$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$afe_perfecttense_long);				
					}
					else
					{
						$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$spinned_long_desc1);				
					}
				}				
				else
				{
					$spinned_short_desc = str_replace($orig_string_article,$repl_string_article,$spinned_short_desc1);
					$spinned_long_desc = str_replace($orig_string_article,$repl_string_article,$spinned_long_desc1);				
				}					
            }
            else
            {
                $spinned_short_desc = $afe_check_result_detail[0]->short_des;
                $spinned_long_desc = $afe_check_result_detail[0]->long_desc;
            }
            $afe_saved_data=array(
                                'catg_id' => $afe_check_result_detail[0]->catg_id, 
                                'title' => $afe_check_result_detail[0]->title, 
                                'link' => $afe_check_result_detail[0]->link, 
                                'short_des' => $spinned_short_desc, 
                                'long_desc' => $spinned_long_desc, 
                                'type' => 'article' 
                               );
    
            $insert = $wpdb->insert( $afe_saved_table, $afe_saved_data); 
        }
    }
    if($insert)
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is Saved. Please go to the <a href="<?php echo admin_url('admin.php?page=my-import-result')?>" target="_blank">Import Result</a> Tab</p></div>
    </div>
    <?php }
    else
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is alreday saved. Please go to the <a href="<?php echo admin_url('admin.php?page=my-import-result')?>" target="_blank">Import Result</a> Tab</p></div>
    </div>
    <?php }?>
    <script>
    jQuery(function() {
        setTimeout(function() {
              jQuery('.updated').fadeOut('slow');
            }, 20000); // <-- time in milliseconds
    });
    </script>
    <?php
    exit;
}

add_action( 'wp_ajax_nopriv_ch_search_video_result', 'myajax_wpch_search_video_result' );
add_action('wp_ajax_ch_search_video_result', 'myajax_wpch_search_video_result');

function myajax_wpch_search_video_result ()
{
    include_once("template/class/afe_blog.php"); 

    $afe_blog_main_video = new afeblogs();

    $ajax_video_key_val = $_REQUEST['afe_ajax_vid_keyword'];
	$new_ajax_video_key_val = str_replace(' ', '+', $ajax_video_key_val);
	
    $afe_blog_main_video->afe_youtube_search_keyword($new_ajax_video_key_val);
    ?>    
    <table id="exampless" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Image</th>
                <th>Title</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
          <?php
                global $wpdb;
                 $afe_result_detail_video = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE type = 'video' ORDER BY id ASC");
                if(!empty($afe_result_detail_video))
                {
                    foreach($afe_result_detail_video as $afe_result_detail_video1)
                    {  
                        $afe_fetch_link_data = unserialize($afe_result_detail_video1->link);
                        $afe_video_url = $afe_fetch_link_data['link'];
                        $afe_video_image = $afe_fetch_link_data['thum_img_url'];
                ?>
                    <tr>
                        <td><a href="https://www.youtube.com/watch?v=<?php echo $afe_video_url;?>" target=_blank><img src="<?php echo $afe_video_image;?>"/></a></td>
                        <td><span style="color:firebrick;"><?php echo $afe_result_detail_video1->title; ?></span></td>
                        <td><?php echo wp_trim_words( $afe_result_detail_video1->short_des, 30 ,'...' ); ?></td>
                        <td><input type=checkbox name=afe_video_check_vals[] class=afe_video_check_val value=<?php echo $afe_result_detail_video1->id;?> /></td>                              
                    </tr>
            <?php } } ?>
        </tbody>
    </table>        
    <script>
        jQuery(document).ready(function($) {
            $('#exampless').DataTable();
        } );
    </script>
    <?php    
    exit;
}
add_action( 'wp_ajax_nopriv_ch_video_check_results', 'myajax_wpch_video_check_results' );
add_action('wp_ajax_ch_video_check_results', 'myajax_wpch_video_check_results');

function myajax_wpch_video_check_results ()
{
    global $wpdb;
    $ajax_video_check_result =  $_POST['afe_ajax_video_check_array_val'];

	$afe_video_check_val = str_replace( ',', ' ', $ajax_video_check_result );
    $afe_video_check_split_string = explode(" ",$afe_video_check_val);
    
    foreach($afe_video_check_split_string as $afe_video_check_split_string1)
    {
        $afe_video_saved_table = $wpdb->base_prefix . "ch_saved_result";
        $afe_video_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE id = '".$afe_video_check_split_string1."' AND type = 'video'");
        $afe_count_video_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_saved_result WHERE title = '".$afe_video_check_result_detail[0]->title."' AND type = 'video'");
        
        if (count($afe_count_video_check_result_detail) == 0)
        {
            $afe_video_saved_data=array(
                                        'catg_id' => '', 
                                        'title' => $afe_video_check_result_detail[0]->title, 
                                        'link' => $afe_video_check_result_detail[0]->link, 
                                        'short_des' => $afe_video_check_result_detail[0]->short_des, 
                                        'long_desc' => '', 
                                        'type' => 'video' 
                                       );
    
            $video_insert = $wpdb->insert( $afe_video_saved_table, $afe_video_saved_data); 
        }
    }
    if($video_insert)
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is Saved</p></div>
    </div>
    <?php }
    else
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is alreday saved</p></div>
    </div>
    <?php }?>
    <script>
    jQuery(function() {
        setTimeout(function() {
              jQuery('.updated').fadeOut('slow');
            }, 5000); // <-- time in milliseconds
    });
    </script>
    <?php
    exit;
    
}


add_action( 'wp_ajax_nopriv_ch_campaign_search_result', 'myajax_wpch_campaign_search_result' );
add_action('wp_ajax_ch_campaign_search_result', 'myajax_wpch_campaign_search_result');

function myajax_wpch_campaign_search_result ()
{
	include_once("template/class/afe_blog.php"); 
    $afe_cmp_blog_main1=new afeblogs();

    $ajax_cmp_check_val =  $_POST['afe_ajax_cmp_array_val'];
    $ajax_cmp_key =  $_POST['afe_ajax_cmp_keyword'];
    
    $afe_cmp_blog_main1->afe_search_result($ajax_cmp_check_val,$ajax_cmp_key);
    global $wpdb;
    $afe_cmp_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE type = 'article' ORDER BY id ASC");
    if(count($afe_cmp_result_detail) != 0) {
    ?>
    <div style="min-height:850px;">
    <table id="example_cmp_article" class="table table-striped widefat" style="width:100%;">
      <thead>
        <tr>
          <th style="text-align: inherit;font-weight: 700;">Title</th>
          <th style="text-align: inherit;font-weight: 700;">Description</th>
          <th style="text-align: inherit;font-weight: 700;">Actions<th>
        </tr>
      </thead>
      <tbody>
      <?php
    	foreach($afe_cmp_result_detail as $afe_cmp_result_detail1)
    	{  
			if(!empty($afe_cmp_result_detail1->title)) 
			{
				echo "<tr>";
				echo "<td><p style=color:firebrick>".$afe_cmp_result_detail1->title."</p></td>";
				echo "<td><p>".$afe_cmp_result_detail1->short_des."</p></td>";
				echo "<td><input type=checkbox name=afe_cmp_check_vals[] class=afe_cmp_check_val value=".$afe_cmp_result_detail1->id."></td>";
				echo "</tr>";
			}
    	}
       ?>
      </tbody>
    </table>
    </div>
    <?php } else { ?>
    <div style="overflow:hidden;height:auto">
       <table id="example_cmp_article" class="table table-striped widefat" style="width:100%;">
    	   <tr>
        	   <td><p style="text-align: center;color:firebrick"> No Result Found </p></td>
    	   </tr>
        </table>
    </div>    
    <?php } ?>    
    
    <script>
    /*
        jQuery(document).ready(function() 
        {
          var table = jQuery('#example_cmp_article').DataTable({ 
                select: false,
                "columnDefs": [{
                    className: "Name", 
                    "targets":[0],
                    "visible": false,
                    "searchable":false
                }]
            });//End of create main table
        
          
        });*/
    </script>
<?php    
exit;
}


add_action( 'wp_ajax_nopriv_ch_get_check_campaign_result', 'myajax_wpch_get_check_campaign_result' );
add_action('wp_ajax_ch_get_check_campaign_result', 'myajax_wpch_get_check_campaign_result');
function myajax_wpch_get_check_campaign_result()
{
    global $wpdb;
    
    include_once("template/class/afe_blog.php"); 

    $ajax_campaign_check_cat_result =  $_POST['afe_ajax_campaign_check_array_val'];
    $ajax_campaign_check_title_result =  $_POST['afe_ajax_campaign_title'];
    $ajax_campaign_check_keyword_result =  $_POST['afe_ajax_campaign_key'];
    $ajax_campaign_check_hour = isset($_POST['afe_ajax_campaign_hour']) ? $_POST['afe_ajax_campaign_hour'] : array();
    $ajax_campaign_check_days = isset($_POST['afe_ajax_campaign_days']) ? $_POST['afe_ajax_campaign_days'] : array();
    $ajax_campaign_check_img_key = isset($_POST['afe_ajax_campaign_img_key']) ? $_POST['afe_ajax_campaign_img_key'] : '';
    $ajax_campaign_check_vid_key = isset($_POST['afe_ajax_campaign_vid_key']) ? $_POST['afe_ajax_campaign_vid_key'] : '';

    $ajax_camp_hr = isset($ajax_campaign_check_hour[0]) ? $ajax_campaign_check_hour[0] : '';
    $ajax_camp_dayss = isset($ajax_campaign_check_days[0]) ? $ajax_campaign_check_days[0] : '';


    $spin_blog_main=new afeblogs();
    $afe_blog_main_video1 = new afeblogs();
    $ajax_video_key_val1 = $ajax_campaign_check_vid_key;
	$new_ajax_video_key_val1 = str_replace(' ', '+', $ajax_video_key_val1);
	
    $vid = $afe_blog_main_video1->afe_youtube_search_keyword1($new_ajax_video_key_val1);
	
	
	if(!empty($vid['id']['videoId']))
	{		
		$video_link = $vid['id']['videoId'];
	}
	else
	{
		$video_link = '';
	}
	
	
	$check_img_post = "https://pixabay.com/api/?key=20401270-0452e7ff0295b94110247f71d&q=".$ajax_campaign_check_img_key."&per_page=5";
    $afe_ajax_afe_spin_content = isset($_POST['afe_ajax_afe_spin_content']) ? $_POST['afe_ajax_afe_spin_content'] : '';
    $afe_ajax_spin_content_rewriter = isset($_POST['afe_ajax_spin_content_rewriter']) ? $_POST['afe_ajax_spin_content_rewriter'] : '';
    $afe_ajax_spin_content_perfecttense = isset($_POST['afe_ajax_spin_content_perfecttense']) ? $_POST['afe_ajax_spin_content_perfecttense'] : '';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $check_img_post);
    $result_img_post = curl_exec($ch);
    curl_close($ch);
    
    $afe_array_img_post = json_decode($result_img_post);
    
    $ran_img = $afe_array_img_post->hits;
    $randomElement_img_post = $ran_img[array_rand($ran_img, 1)];
    
    $featured_img_post = $randomElement_img_post->webformatURL;
    $featured_img_post_basename = $randomElement_img_post->previewURL;



    $afe_campaign_table = $wpdb->base_prefix . "ch_camapign";
    $afe_count_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_camapign WHERE c_title = '".$ajax_campaign_check_title_result."'");
    
    if (count($afe_count_campaign_check_result_detail) == 0)
    {
        $afe_campaign_data=array(
                            'c_title' => $ajax_campaign_check_title_result, 
                            'c_sub_cat' => $ajax_campaign_check_cat_result, 
                            'c_keyword' => $ajax_campaign_check_keyword_result, 
                            'c_img_key' => $ajax_campaign_check_img_key, 
                            'c_ytube_key' => $ajax_campaign_check_vid_key, 
                            'c_prod_short' => '', 
                            'c_hours' => $ajax_camp_hr, 
                            'c_days' => $ajax_camp_dayss,
                            'c_date' => ''
                           );

        $insert = $wpdb->insert( $afe_campaign_table, $afe_campaign_data); 

        $afe_count_campaign_check = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_camapign WHERE c_title = '".$ajax_campaign_check_title_result."'");
    
        if(count($afe_count_campaign_check) > 0)
        {
            $afe_campaign_post_table = $wpdb->base_prefix . "ch_campaign_post";
            
            $afe_campaign_table_subcat = $afe_count_campaign_check[0]->c_sub_cat;
            $afe_campaign_check_val = str_replace( ',', ' ', $afe_campaign_table_subcat );
            $afe_campaign_check_split_string=explode(" ",$afe_campaign_check_val);
    
            $afe_today=date('Y-m-d 00:00:00');  
			if(!empty($ajax_campaign_check_hour[0]))
			{
				$afe_schedule_hours = $ajax_campaign_check_hour[0];
			}
			else
			{
				$afe_schedule_hours = '';
			}
			if(!empty($ajax_campaign_check_days[0]))
			{
				$afe_schedule_days = $ajax_campaign_check_days[0];
			}
			else
			{
				$afe_schedule_days = '';
			}
            //$afe_current_datetime_hours=date('Y-m-d H:i:s',strtotime($afe_today . 'now +1 hour'));
            //$afe_current_datetime_days=date('Y-m-d H:i:s',strtotime($afe_today . ' +1 day'));
            if($afe_schedule_hours)
            {
                $afe_current_datetime_hours = date('Y-m-d H:i:s',strtotime("now +".$afe_schedule_hours." hour"));
            }       
            if($afe_schedule_days)
            {
                $afe_current_datetime_days = date('Y-m-d H:i:s',strtotime($afe_today . " +".$afe_schedule_days." day"));
            }       
            foreach($afe_campaign_check_split_string as $afe_campaign_check_split_string1)
            {
                //echo $afe_campaign_check_split_string1;
                $afe_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE id = '".$afe_campaign_check_split_string1."' AND type = 'article'");
                
				if($afe_ajax_afe_spin_content == 'on')
				{
					$spin_titles = $afe_campaign_check_result_detail[0]->title;
					$spin_contents = $afe_campaign_check_result_detail[0]->long_desc;
					
					$spinned_title = $spin_blog_main->spin_article($spin_titles);
					$spinned_content1 = $spin_blog_main->spin_article($spin_contents);
					
					$orig_string = ["&lt;", "&gt;"];
					$repl_string   = ["<", ">"];
					$spinned_content = str_replace($orig_string,$repl_string,$spinned_content1);
				}
				elseif($afe_ajax_afe_spin_content == 'on')
				{
                    $spin_titles = $afe_campaign_check_result_detail[0]->title;
                    $spin_contents = $afe_campaign_check_result_detail[0]->long_desc;
                    
                	$spinned_title1 = $spin_blog_main->spin_article($spin_titles);
            		$spinned_content1 = $spin_blog_main->spin_article($spin_contents);
					$orig_string = ["&lt;", "&gt;"];
					$repl_string   = ["<", ">"];
					$spinned_content11 = str_replace($orig_string,$repl_string,$spinned_content1);
					
					// Spin Rewriter API settings - authentication:
					$result_spinrewriter_email1 = get_option( 'wpch_spinrewriter_email' );
					$result_spinrewriter_api1 = get_option( 'wpch_spinrewriter_api' );

					if(!empty($result_spinrewriter_email1) && !empty($result_spinrewriter_api1)) 
					{ 							
						$afe_spinrewriter_api_title=$spin_blog_main->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$spinned_title1);
						if(!empty($afe_spinrewriter_api_title))
						{
							$spinned_title = $afe_spinrewriter_api_title['response'];
						}					
						else
						{
							$spinned_title = $spinned_title1;
						}	
						
						$afe_spinrewriter_api_content=$spin_blog_main->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$spinned_content11);
						if(!empty($afe_spinrewriter_api_content))
						{
							$spinned_content = $afe_spinrewriter_api_content['response'];							
						}								
						else
						{
							$spinned_content = $spinned_content11;
						}
						
					}				
					else
					{
						$spinned_content = $spinned_content11;
						$spinned_title = $spinned_title1;
					}
				}
				elseif($afe_ajax_spin_content_perfecttense == 'on')
				{
                    $spin_titles = $afe_campaign_check_result_detail[0]->title;
                    $spin_contents = $afe_campaign_check_result_detail[0]->long_desc;
                    
                	$spinned_title1 = $spin_blog_main->spin_article($spin_titles);
            		$spinned_content1 = $spin_blog_main->spin_article($spin_contents);
					$orig_string = ["&lt;", "&gt;"];
					$repl_string   = ["<", ">"];
					$spinned_content11 = str_replace($orig_string,$repl_string,$spinned_content1);
					
					$result_perfecttense_api = get_option( 'wpch_perfect_api_key' );
					$result_perfecttense_app = get_option( 'wpch_perfect_app_key' );

					if(!empty($result_perfecttense_api) && !empty($result_perfecttense_app)) 
					{ 											
						$afe_spinrewriter_api_title = $spin_blog_main->perfecttense_afe($result_perfecttense_api,$result_perfecttense_app,$spinned_title1);

						if(!empty($afe_spinrewriter_api_title))
						{
							$spinned_title = $afe_spinrewriter_api_title;
						}
						else
						{
							$spinned_title = $spinned_title1;
						}	
						
						$afe_spinrewriter_api_content = $spin_blog_main->perfecttense_afe($result_perfecttense_api,$result_perfecttense_app,$spinned_content11);

						if(!empty($afe_spinrewriter_api_content))
						{
							$spinned_content = $afe_spinrewriter_api_content;				
						}				
						else
						{
							$spinned_content = $spinned_content11;
						}
					}				
					else
					{
						$spinned_content = $spinned_content11;
						$spinned_title = $spinned_title1;
					}
				}
                else
                {
                    $spinned_title = $afe_campaign_check_result_detail[0]->title;
                    $spinned_content1 = $afe_campaign_check_result_detail[0]->long_desc;

                    $orig_string = ["&lt;", "&gt;"];
                    $repl_string   = ["<", ">"];
                    $spinned_content = str_replace($orig_string,$repl_string,$spinned_content1);
                }
				$youtube_embed_url = get_option( 'wpch_vid_tmp_camp' );
				
				
				if(!empty($video_link))
				{
					$vid_src = "https://www.youtube.com/embed/".$video_link;
					
					//$vid_link_option = "<iframe width=420 height=315 src=https://www.youtube.com/embed/$video_link></iframe>";
					//$vid_link_option = "<iframe width='560' height='315' src='https://www.youtube.com/embed/$video_link' frameborder='0' allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
					$vid_link_option = "<iframe width='560' height='315' src='".$vid_src ."' frameborder='0' allowfullscreen></iframe>";
				}
				else
				{
					$vid_link_option = '';
				}
                $post_desc = $spinned_content."<br/>".$vid_link_option;
                $afe_schedule_post_array = array(
                      'post_title'    => $spinned_title,
                      'post_content'  => $post_desc,
					  'post_name' 	  => str_replace('%ef%bb%bf', '', sanitize_title($spinned_title)),
                      'post_status'   => 'draft',
                    );
                     
                // Insert the post into the database
                $afe_schedule_post_id = wp_insert_post($afe_schedule_post_array,true);

                if($afe_schedule_post_id)
                {    
                    $image_url        = $featured_img_post; // Define the image URL here
                    
                    $ch = curl_init();
                
                    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_URL, $image_url);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
                
                    $data_img = curl_exec($ch);
                    curl_close($ch);
            

                    $image_name       = basename($featured_img_post_basename);
                    $upload_dir       = wp_upload_dir(); // Set upload folder
                    $image_data       = $data_img; // Get image data
                    $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
                    $filename         = basename( $unique_file_name ); // Create image file name
                    
                    // Check folder permission and define file location
                    if( wp_mkdir_p( $upload_dir['path'] ) ) {
                        $file = $upload_dir['path'] . '/' . $filename;
                    } else {
                        $file = $upload_dir['basedir'] . '/' . $filename;
                    }
                    
                    // Create the image  file on the server
                    file_put_contents( $file, $image_data );
                    
                    // Check image file type
                    $wp_filetype = wp_check_filetype( $filename, null );
                    
                    // Set attachment data
                    $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title'     => sanitize_file_name( $filename ),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );
                    
                    // Create the attachment
                    $attach_id = wp_insert_attachment( $attachment, $file, $afe_schedule_post_id );
                    
                    // Include image.php
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    
                    // Define attachment metadata
                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                    
                    // Assign metadata to attachment
                    wp_update_attachment_metadata( $attach_id, $attach_data );
                    
                    // And finally assign featured image to post
                    set_post_thumbnail( $afe_schedule_post_id, $attach_id );
                    
                    if($afe_schedule_hours)
                    {
                        $afe_campaign_post_data=array(
                                                'post_id' => $afe_schedule_post_id, 
                                                'campaign_id' => $afe_count_campaign_check[0]->id, 
                                                'schedule_date' => $afe_current_datetime_hours, 
                                                'status' => 0, 
                                               );
                        $campaign_post_insert = $wpdb->insert( $afe_campaign_post_table, $afe_campaign_post_data); 

                        $afe_next_datetime_hours=date('Y-m-d H:i:s',strtotime($afe_current_datetime_hours . "now +".$afe_schedule_hours." hour"));
                    }
                    if($afe_schedule_days)
                    {
                        $afe_campaign_post_data=array(
                                                'post_id' => $afe_schedule_post_id, 
                                                'campaign_id' => $afe_count_campaign_check[0]->id, 
                                                'schedule_date' => $afe_current_datetime_days, 
                                                'status' => 0, 
                                               );
                        $campaign_post_insert = $wpdb->insert( $afe_campaign_post_table, $afe_campaign_post_data); 

                        $afe_next_datetime_days=date('Y-m-d H:i:s',strtotime($afe_current_datetime_days . " +".$afe_schedule_days." day"));
                    }
                    $afe_current_datetime_hours=$afe_next_datetime_hours;
					if(!empty($afe_next_datetime_days))
					{
						$afe_current_datetime_days=$afe_next_datetime_days;
					}
					else
					{
						$afe_current_datetime_days='';
					}
                }
            }
        }
    ?>
    <div class="wrap">
        <div class="updated"><p>Campaign is saved</p></div>
    </div>
    <?php
    }
    else
    {?>
    <div class="wrap">
        <div class="error"><p>Campaign is alreday saved</p></div>
    </div>
    <?php }?>
    <script>
	/*
    jQuery(function() {
        setTimeout(function() {
              jQuery('.error').fadeOut('slow');
            }, 5000); // <-- time in milliseconds
        setTimeout(function(){
             jQuery('.updated').slideUp('slow').fadeOut(function() {
                window.location = "<?php echo admin_url('admin.php?page=my-campaign-details'); ?>";
             });
        }, 5000);            
    });
	*/
    </script>    
    <?php exit;
}

function mywpch_campaign_cron()
{
    global $wpdb;
    $afe_campaign_post_table_cron = $wpdb->base_prefix . "ch_campaign_post";
    
    //delete
    /*$afe_cron_del_campaign_active = $wpdb->get_results("select * from ".$afe_campaign_post_table_cron." where status=1");
    if(!empty($afe_cron_del_campaign_active))
    {
        $afe_delete_result=$wpdb->query($wpdb->prepare("DELETE FROM $afe_campaign_post_table_cron WHERE status = %d",'1'));
    }*/
    
    $afe_cron_campaign_active = $wpdb->get_results("select * from ".$afe_campaign_post_table_cron." where status=0");

    if(!empty($afe_cron_campaign_active))
    {
        $afe_cron_current_dates=date('Y-m-d H:i:s');
        $afe_cron_schedule_posts = $wpdb->get_results("select * from ".$afe_campaign_post_table_cron." where schedule_date <= '".$afe_cron_current_dates."' ORDER BY id DESC limit 0,1");
        if($afe_cron_schedule_posts)
        {
            if($afe_cron_schedule_posts[0]->id)
            {
                $wpdb->update( $afe_campaign_post_table_cron,array('status'=>'1'),array('id'=> $afe_cron_schedule_posts[0]->id));
            }   
            foreach($afe_cron_schedule_posts as $afe_cron_schedule_post)
            {
                $afe_cron_current_date=date('Y-m-d H:i:s');
                if($afe_cron_current_date >= $afe_cron_schedule_post->schedule_date)
                {
                    $afe_cron_campaign_tble = $wpdb->base_prefix . "ch_camapign";
                    $afe_cron_campaign = $wpdb->get_results("select * from ".$afe_cron_campaign_tble." where id=".$afe_cron_schedule_post->campaign_id);
                    //$afe_camp_store = $afe_cron_campaign[0]->c_title;
                    
                    $afe_cron_post_data = get_post($afe_cron_schedule_post->post_id);
                    $afe_cron_post_title = $afe_cron_post_data->post_title;
                    $afe_cron_post_desc = $afe_cron_post_data->post_content;
                    
                    $afe_cron_update_post = array(
                                                  'ID' => $afe_cron_schedule_post->post_id,
                                                  'post_status' => 'publish',
                      );

                    // Update the post into the database
                    wp_update_post( $afe_cron_update_post );
                    
                    $afe_check_scheduled_post=$wpdb->get_results("select * from ".$afe_campaign_post_table_cron." where campaign_id=".$afe_cron_campaign[0]->id);   
                    if(empty($afe_check_scheduled_post))
                    {
                        $afe_update_date=date('Y-m-d H:i:s');
                        $wpdb->update( $afe_cron_campaign_tble,array('c_date'=>$afe_update_date),array('id'=> $afe_cron_campaign[0]->id));
                    }
                }
            }       
        }
    }
    
    //delete
    $afe_cron_del_campaign_active = $wpdb->get_results("select * from ".$afe_campaign_post_table_cron." where status=1");
    if(!empty($afe_cron_del_campaign_active))
    {
        $afe_delete_result=$wpdb->query($wpdb->prepare("DELETE FROM $afe_campaign_post_table_cron WHERE status = %d",'1'));
    }
}

function mywpch_cron_schedules( $schedules ) 
{
	$schedules[ 'every1hour_ch' ] = array( 'interval' => 60 * 60, 'display' => __( 'Every One Hour', 'afe_campaign_blog' ) );

    return $schedules;
}

add_filter( 'cron_schedules', 'mywpch_cron_schedules' );

if (! wp_next_scheduled ( 'every1hour_ch_events' )) 
{
	wp_schedule_event(time(), 'every1hour_ch', 'every1hour_ch_events');
}

add_action('every1hour_ch_events', 'mywpch_campaign_cron');

add_action( 'wp_ajax_nopriv_ch_search_img_result', 'myajax_wpch_search_img_result' );
add_action('wp_ajax_ch_search_img_result', 'myajax_wpch_search_img_result');

function myajax_wpch_search_img_result ()
{
    $imgs_key = $_POST['afe_ajax_img_keyword'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $imgs_key);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $afe_array = json_decode($result);
    if(empty($afe_array))
    {
        echo "<h3>No images Found<h3>";
    }
    else
    {
        echo "<div class=img_search_ajax style=display:table;>"; 
        $i = 0;
        ?>
        <style>
            :checked + label {
              border-color: #ddd;
            }
            
            :checked + label:before {
              content: "✓";
              background-color: grey;
              transform: scale(1);
            }
            
            :checked + label img {
              transform: scale(0.9);
              /* box-shadow: 0 0 5px #333; */
              z-index: -1;
            }
        </style>
        <?php
        foreach($afe_array->hits as $hit)
        {
            if(!empty($hit)) 
            {
                ?>
                <ul style="display: inline-block;">
                  <li>
                    <input type="checkbox"  name=afe_image_check_vals[] class="img_check_cls" id="myCheckbox<?php echo $i; ?>" value="<?php echo $hit->previewURL; ?>"/>
                    <label for="myCheckbox<?php echo $i; ?>"><img src="<?php echo $hit->previewURL; ?>" style="margin:10px;padding:10px;border:2px solid #03d200;width:160px;height:160px;"></label>
                  </li>
                </ul>
                <?php
            }
        $i++;    
        }
        echo "</div>";
    }
    
    exit;
}

add_action( 'wp_ajax_nopriv_ch_img_check_results', 'myajax_wpch_img_check_results' );
add_action('wp_ajax_ch_img_check_results', 'myajax_wpch_img_check_results');

function myajax_wpch_img_check_results ()
{
    global $wpdb;
    $check_img_array = $_POST['afe_ajax_img_check_array_val'];
    foreach($check_img_array as $check_img_array1)
    {
        $file = $check_img_array1;
        $filename = basename($file);
        $ss = preg_replace('/\.[^.]+$/', '', $filename);


        $myposts = $wpdb->get_results( $wpdb->prepare("SELECT post_title FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $ss .'%') );
        if(count($myposts) == 0)
        {
            
            $ch = curl_init();
        
            curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $file);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
        
            $data = curl_exec($ch);
            curl_close($ch);
    
            $upload_file = wp_upload_bits($filename, null, $data);
            if (!$upload_file['error']) 
            {
            	$wp_filetype = wp_check_filetype($filename, null );
            	$attachment = array(
            		'post_mime_type' => $wp_filetype['type'],
            		'post_parent' => $parent_post_id,
            		'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
            		'post_content' => '',
            		'post_status' => 'inherit'
            	);
            	$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
            	if (!is_wp_error($attachment_id)) 
            	{
            		require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
            		wp_update_attachment_metadata( $attachment_id,  $attachment_data );
            	}
            } 
            $img_saved = add_post_meta( $attachment_id, 'wpch_img', 'wpch_img_saved', true  );
        }
        else
        {
            $s = "Exist";
        }
    }
    if($img_saved) {
    ?>
    <div class="wrap">
        <div class="updated"><p>Image is saved</p></div>
    </div>
    <?php }
    elseif($s == 'Exist')
    {
    ?>
    <div class="wrap">
        <div class="updated"><p>Image is already saved</p></div>
    </div>
    <?php 
    }
    exit;
}

add_action( 'wp_ajax_nopriv_ch_edit_check_campaign_result', 'myajax_wpch_edit_check_campaign_result' );
add_action('wp_ajax_ch_edit_check_campaign_result', 'myajax_wpch_edit_check_campaign_result');

function myajax_wpch_edit_check_campaign_result ()
{
    global $wpdb;
    
    include_once("template/class/afe_blog.php"); 
    include_once("template/API/google/Google_Client_v1.php"); 
    include_once("template/API/google/contrib/Google_YouTubeService.php"); 

    $ajax_edit_campaign_check_id =  $_POST['afe_ajax_campaign_id'];
    $ajax_edit_campaign_check_cat_result =  $_POST['afe_ajax_edit_campaign_check_array_val'];
    $ajax_edit_campaign_check_title_result =  $_POST['afe_ajax_edit_campaign_title'];
    $ajax_edit_campaign_check_keyword_result =  $_POST['afe_ajax_edit_campaign_key'];
    $ajax_edit_campaign_check_hour =  $_POST['afe_ajax_edit_campaign_hour'];
    $ajax_edit_campaign_check_days =  $_POST['afe_ajax_edit_campaign_days'];
    $ajax_edit_campaign_check_img_key =  $_POST['afe_ajax_edit_campaign_img_key'];
    $ajax_edit_campaign_check_vid_key =  $_POST['afe_ajax_edit_campaign_vid_key'];
    
    $spin_blog_main=new afeblogs();
    $afe_edit_blog_main_video1 = new afeblogs();
    $ajax_edit_video_key_val1 = $ajax_edit_campaign_check_vid_key;
	$new_ajax_edit_video_key_val1 = str_replace(' ', '+', $ajax_edit_video_key_val1);
	
    $afe_edit_blog_main_video1->afe_youtube_search_keyword1($new_ajax_edit_video_key_val1);

    $check_edit_img_post = "https://pixabay.com/api/?key=20401270-0452e7ff0295b94110247f71d&q=".$ajax_edit_campaign_check_img_key."&per_page=5";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $check_edit_img_post);
    $result_edit_img_post = curl_exec($ch);
    curl_close($result_edit_img_post);
    
    $afe_edit_array_img_post = json_decode($result_edit_img_post);
    
    $ran_edit_img = $afe_edit_array_img_post->hits;
    $randomElement_edit_img_post = $ran_edit_img[array_rand($ran_edit_img, 1)];
    
    $featured_edit_img_post = $randomElement_edit_img_post->webformatURL;
    $featured_edit_img_post_basename = $randomElement_edit_img_post->previewURL;

    $afe_edit_campaign_table = $wpdb->base_prefix . "ch_camapign";
    $afe_edit_count_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_camapign WHERE id = '".$ajax_edit_campaign_check_id."'");
    
    if (count($afe_edit_count_campaign_check_result_detail) == 1)
    {
        $wpdb->query( $wpdb->prepare( 
                        "
                            UPDATE ".$wpdb->base_prefix."ch_camapign
                            SET c_title = '%s', c_sub_cat = '%s', c_keyword = '%s', c_img_key = '%s', c_ytube_key = '%s', c_prod_short = '%s', c_hours = '%d', c_days = '%d', c_date = '%s'
                            WHERE `id` = '%d'
                        ",
                        $ajax_edit_campaign_check_title_result,
                        $ajax_edit_campaign_check_cat_result,
                        $ajax_edit_campaign_check_keyword_result,
                        $ajax_edit_campaign_check_img_key,
                        $ajax_edit_campaign_check_vid_key,
                        '',
                        $ajax_edit_campaign_check_hour[0],
                        $ajax_edit_campaign_check_days[0],
                        '',
                        $ajax_edit_campaign_check_id
                        ) );        
    

    $afe_edit_count_campaign_check = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_camapign WHERE id = '".$ajax_edit_campaign_check_id."'");

    if(count($afe_edit_count_campaign_check) > 0)
    {
        $afe_edit_campaign_post_table = $wpdb->base_prefix . "ch_campaign_post";
        
        $afe_edit_campaign_table_subcat = $afe_edit_count_campaign_check[0]->c_sub_cat;
        $afe_edit_campaign_check_val = str_replace( ',', ' ', $afe_edit_campaign_table_subcat );
        $afe_edit_campaign_check_split_string=explode(" ",$afe_edit_campaign_check_val);

    	$afe_edit_today=date('Y-m-d 00:00:00');	
    	$afe_edit_current_datetime=date('Y-m-d H:i:s',strtotime($afe_edit_today . ' +1 day'));
    	$afe_edit_schedule_hours = $ajax_edit_campaign_check_hour[0];
    	$afe_edit_schedule_days = $ajax_edit_campaign_check_days[0];
    	
        foreach($afe_edit_campaign_check_split_string as $afe_edit_campaign_check_split_string1)
        {
            echo $afe_campaign_check_split_string1;
            $afe_edit_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."ch_tmp_table WHERE id = '".$afe_edit_campaign_check_split_string1."' AND type = 'article'");
            
            
            if($_POST['afe_ajax_afe_spin_content'] == 'on')
            {
                $spin_edit_titles = $afe_edit_campaign_check_result_detail[0]->title;
                $spin_edit_contents = $afe_edit_campaign_check_result_detail[0]->long_desc;
                
            	$spinned_edit_title = $spin_blog_main->spin_article($spin_edit_titles);
        		$spinned_edit_content1 = $spin_blog_main->spin_article($spin_edit_contents);

                $orig_edit_string = ["&lt;", "&gt;"];
                $repl_edit_string   = ["<", ">"];
                $spinned_edit_content = str_replace($orig_edit_string,$repl_edit_string,$spinned_edit_content1);


            }
            else
            {
                $spinned_edit_title = $afe_edit_campaign_check_result_detail[0]->title;
                $spinned_edit_content1 = $afe_edit_campaign_check_result_detail[0]->long_desc;

                $orig_edit_string = ["&lt;", "&gt;"];
                $repl_edit_string   = ["<", ">"];
                $spinned_edit_content = str_replace($orig_edit_string,$repl_edit_string,$spinned_edit_content1);
            }

			$edit_youtube_embed_url = get_option( 'wpch_vid_tmp_camp' );
            //$vid_edit_link_option = "<iframe width=420 height=315 src=https://www.youtube.com/embed/$edit_youtube_embed_url></iframe>";
            $post_edit_desc = $spinned_edit_content;
            $afe_edit_schedule_post_array = array(
				  'post_title'    => $spinned_edit_title,
				  'post_content'  => $post_edit_desc,
				  'post_status'   => 'draft',
				  'post_author'   => 1,
				);
				 
			// Insert the post into the database
			$afe_edit_schedule_post_id = wp_insert_post($afe_edit_schedule_post_array,true);

			if($afe_edit_schedule_post_id)
			{    
                $edit_image_url        = $featured_edit_img_post; // Define the image URL here

                $ch = curl_init();
            
                curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_URL, $edit_image_url);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       
            
                $data_edit = curl_exec($ch);
                curl_close($ch);
        
    
                $edit_image_name       = basename($featured_edit_img_post_basename);
                $edit_upload_dir       = wp_upload_dir(); // Set upload folder
                $edit_image_data       = $data_edit; // Get image data
                $edit_unique_file_name = wp_unique_filename( $edit_upload_dir['path'], $edit_image_name ); // Generate unique name
                $edit_filename         = basename( $edit_unique_file_name ); // Create image file name
                
                // Check folder permission and define file location
                if( wp_mkdir_p( $edit_upload_dir['path'] ) ) {
                    $edit_file = $edit_upload_dir['path'] . '/' . $edit_filename;
                } else {
                    $edit_file = $edit_upload_dir['basedir'] . '/' . $edit_filename;
                }
                
                // Create the image  file on the server
                file_put_contents( $edit_file, $edit_image_data );
                
                // Check image file type
                $wp_edit_filetype = wp_check_filetype( $edit_filename, null );
                
                // Set attachment data
                $edit_attachment = array(
                    'post_mime_type' => $wp_edit_filetype['type'],
                    'post_title'     => sanitize_file_name( $edit_filename ),
                    'post_content'   => '',
                    'post_status'    => 'inherit'
                );
                
                // Create the attachment
                $edit_attach_id = wp_insert_attachment( $edit_attachment, $edit_file, $afe_edit_schedule_post_id );
                
                // Include image.php
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                
                // Define attachment metadata
                $edit_attach_data = wp_generate_attachment_metadata( $edit_attach_id, $edit_file );
                
                // Assign metadata to attachment
                wp_update_attachment_metadata( $edit_attach_id, $edit_attach_data );
                
                // And finally assign featured image to post
                set_post_thumbnail( $afe_edit_schedule_post_id, $edit_attach_id );
			    
			    $afe_edit_campaign_post_data=array(
                                        'post_id' => $afe_edit_schedule_post_id, 
                                        'campaign_id' => $afe_edit_count_campaign_check[0]->id, 
                                        'schedule_date' => $afe_edit_current_datetime, 
                                        'status' => 0, 
                                       );
                $edit_campaign_post_insert = $wpdb->insert( $afe_edit_campaign_post_table, $afe_edit_campaign_post_data); 
                
				if($afe_edit_schedule_hours)
				{
					$afe_edit_next_datetime=date('Y-m-d H:i:s',strtotime($afe_edit_current_datetime . " +".$afe_edit_schedule_hours." hours"));
				}
				if($afe_edit_schedule_days)
				{
					$afe_edit_next_datetime=date('Y-m-d H:i:s',strtotime($afe_edit_current_datetime . " +".$afe_edit_schedule_days." day"));
				}
				$afe_edit_current_datetime=$afe_edit_next_datetime;
			}
        }
    }
    ?>
    <div class="wrap">
        <div class="updated"><p>Campaign is updated</p></div>
    </div>
    <?php
    }
    else
    {?>
    <div class="wrap">
        <div class="error"><p>Campaign is alreday updated</p></div>
    </div>
    <?php }?>
    <script>
    jQuery(function() {
        setTimeout(function() {
              jQuery('.error').fadeOut('slow');
            }, 5000); // <-- time in milliseconds
        setTimeout(function(){
             jQuery('.updated').slideUp('slow').fadeOut(function() {
                window.location = "<?php echo admin_url('admin.php?page=my-campaign-details'); ?>";
             });
        }, 5000);            
    });
    </script>    
    <?php exit;
}


/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function mycp_display_callback( $post ) {
	?>
	<div id="mycp_result"></div>
    <p class="meta-options mycp_field">
		<form action="#" method="post">
			<label for="mycp_video_url" style="font-size:16px;margin-right:15px;">Video Url</label>
			<input id="mycp_video_url" type="text" name="mycp_video_url" id="mycp_video_url_id" class="mycp_video_url_cls" value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'mycp_video_url', true ) ); ?>">
			<br/><br/>
			<span style="color:#aaa;">* Enter a YouTube Video URL for example: [ https://www.youtube.com/watch?v=Tuw8hxrFBH8 ] </span>
			<br/><br/>
			<div style="display:flex;">
				<input type="button" name="mycp_content_btn_name" id="mycp_content_btn_id" class="button button-primary" value="Insert Content" />    
				<div id="afe_search_loaders" style="display: flex;justify-content: center;"><img src="<?php echo plugins_url('MyContentCreatorPro-Free/includes/assets/images/loader_afe.gif'); ?>" id="afe_loader" style="display:none;"> </div>			
			</div>
		</form>
	</p>	
	<script>
	jQuery('#mycp_content_btn_id').click(function(e)
	{
        var mycp_video_post_id = '<?php echo get_the_ID(); ?>';
        var mycp_video_url = jQuery(".mycp_video_url_cls").val();
		jQuery("#afe_loader").css("display","block");
		jQuery("#afe_loader").css("height","30px");
		jQuery("#afe_loader").css("margin","5px");
		jQuery("#afe_search_loaders").css("display","flex");
		
		if( mycp_video_url.length != 0 ) 
		{		
			var mycp_video_url_data_search = {
								action: 'mycp_video_url_results',
								mycp_ajax_video_post_id : mycp_video_post_id,
								mycp_ajax_video_url : mycp_video_url
							};
			jQuery.post(ajaxurl, mycp_video_url_data_search, function(mycp_check_response) 
			{
				if(mycp_check_response == 0)
				{
					jQuery("#mycp_result").html('Note - This plugin can only pull content from videos with subtitles, if a video does not have them, please select another video on that topic by using the search option below');
					jQuery("#afe_search_loaders").css("display","none");
				}
				else
				{
					jQuery("#mycp_result").html(mycp_check_response);
					jQuery("#afe_search_loaders").css("display","none");
				}
			});
		}
		else
		{
			e.preventDefault();
			jQuery("#mycp_result").html('<p style="color:red;">Note - Please enter the youtube url</p>');
			jQuery("#afe_search_loaders").css("display","none");
		}
	});
	</script>
	<?php
}

/*
function mycp_save_meta_box( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( $parent_id = wp_is_post_revision( $post_id ) ) {
        $post_id = $parent_id;
    }
    $fields = [
        'mycp_video_url',
    ];
    foreach ( $fields as $field ) {
        if ( array_key_exists( $field, $_POST ) ) {
            update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
        }
     }
}
add_action( 'save_post', 'mycp_save_meta_box' );
*/


function mcp_getyoutubeID($url)
{
    if (empty($url))
        return '';
    if (stristr($url, 'youtu.be/')) {
        preg_match('/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i', $url, $final_ID);
        return $final_ID[4];
    } else {
        @preg_match('/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $IDD);
        return $IDD[5];
    }
}

function mcp_getYoutubeEmbedUrl($url)
{
	$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_]+)\??/i';
	$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))(\w+)/i';

	if (preg_match($longUrlRegex, $url, $matches)) {
		$youtube_id = $matches[count($matches) - 1];
	}

	if (preg_match($shortUrlRegex, $url, $matches)) {
		$youtube_id = $matches[count($matches) - 1];
	}
	//return 'https://www.youtube.com/embed/' . $youtube_id ;
	return $youtube_id;
}

function spin_oneclickbm_punctuate($ps, $is_array = false)
{
    return spin_oneclick_punctuate_api($ps);
    return $ps;
    if (!$is_array)
        $text = $ps;
    else
        $text = implode('. ', $ps);
    $ret = spin_oneclick_punctuate_api($text);
    if (!empty($ret))
        return $ret;
    return spin_oneclickbm_breakLongText($text);
}

function spin_oneclick_punctuate_api($text)
{
    // http://bark.phon.ioc.ee/punctuator
    // wp_remote_post(  );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://bark.phon.ioc.ee/punctuator');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "text=" . urlencode($text));
    // Receive server response ...
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec($ch);
    $from = array(' & # 39 ', 'gon na');
    $to = array("'", "gonna");
    $ret = str_replace($from, $to, $server_output);
    curl_close($ch);
    return $ret;
}

function spin_oneclick_paragraphs($ps)
{
    if (empty($ps))
        return '';
    $ret = '';
    foreach ($ps as $p) {
        $ret .= '<p>' . $p . '</p>';
    }
    return $ret;
}

function spin_oneclickbm_breakLongText($text, $length = 200, $maxLength = 500)
{
    // return $text;
    //Text length
    $textLength = strlen($text);
    //initialize empty array to store split text
    $splitText = array();
    //return without breaking if text is already short
    if (!($textLength > $maxLength)) {
        $splitText[] = $text;
        return $splitText;
    }
    //Guess sentence completion
    $needle = '.';
    /*iterate over $text length
   as substr_replace deleting it*/
    while (strlen($text) > $length) {
        $end = strpos($text, $needle, $length);
        if ($end === false) {
            //Returns FALSE if the needle (in this case ".") was not found.
            $splitText[] = substr($text, 0);
            $text = '';
            break;
        }
        $end++;
        $splitText[] = substr($text, 0, $end);
        $text = substr_replace($text, '', 0, $end);
    }
    if ($text) {
        $splitText[] = substr($text, 0);
    }
    return $splitText;
}


function spin_oneclickbm_count_capitals( $string ) {
    $string = str_replace( 'I', 'i', $string );
    $lowerCase = mb_strtolower( $string );
    return strlen( $lowerCase ) - similar_text( $string, $lowerCase );
}

function spin_oneclickbm_not_formatted( $ret ) {
    if( ( substr_count ( $ret, '.' ) < 5 ) || ( spin_oneclickbm_count_capitals( $ret ) < 5 )  || ( substr_count ( $ret, "\n" ) < 4 ) )
        return true;
    return false;
}

function spin_oneclickbm_fix_content($content, $has_timer = false)
{
    $ret = '';
    foreach ($content as $chunk) {
        // var_dump($chunk);
        if ($has_timer) {
            if (!empty($chunk['start']))
                $ret .= '<br/><a style="cursor: pointer;" data-seek="' . $chunk['start'] . '" class="seek">' . $chunk['stamp'] . '</a><br/>';
        }
        $ret .= $chunk['content'];
    }
    if ($has_timer)
        return $ret;
    // var_dump(substr_count ( $ret, '.' ));
    if (spin_oneclickbm_not_formatted($ret)) {
        // if( substr_count ( $ret, '.' ) < 5 ) {
        // no puntos
        //$ret = spin_oneclickbm_punctuate($ret, false);
		$ret =$ret;
    }
    $paragraphs = spin_oneclickbm_breakLongText($ret);
    $from = array('& # 39.', ' & # 39, ');
    $to = array('\'', '\'');
    $paragraphs = str_replace($from, $to, $paragraphs);
    return spin_oneclick_paragraphs($paragraphs);
}

function spin_oneclickbm_endsWith($string, $endString) {
    // return false;
    $len = strlen( $endString );
    if ( $len == 0 ) {
        return true;
    }
    return (substr($string, -$len) === $endString);
}

function spin_oneclickbm_array_key_last( $array ) {
    if (! function_exists("array_key_last")) {
            if (!is_array($array) || empty($array)) {
                return NULL;
            }
            return array_keys($array)[count($array)-1];
    }
    else {
        return array_key_last( $array );
    }
}

function spin_oneclickbm_hmi($seconds)
{
    //return ''; //rmi353
    $t = round($seconds);
    return sprintf('%02d:%02d:%02d', ($t / 3600), ($t / 60 % 60), $t % 60);
}

function spin_oneclickbm_should_fix_scripts($scripts)
{
    $punctuations = 0;
    foreach ($scripts as $script) {
        if (spin_oneclickbm_endsWith($script['text'], '.')) {
            $punctuations++;
        }
    }
    // var_dump($punctuations);
    if ($punctuations >= 2) {
        // ok, return as is
        return false;
    }
    return true;
}
function spin_oneclickbm_fix_scripts($scripts)
{
    $ret = array();
    $text = '';
    $start = '';
    $end = '';
    $current = array();
    $n = 0;
    $i = 0;
    foreach ($scripts as $script) {
        if ($i == 0) {
            $script['text'] = trim($script['text']);
            $script['text'] = ucfirst($script['text']);
            $i++;
        }
        if (empty($n))
            $start = $script['start'];
        $text = $text . ' ' . $script['text'];
        // var_dump($i);
        // var_dump($text);
        $end = $script['end'];
        $n++;
        if ($n >= 3) {
            $current = array(
                'start' => $start,
                'end' => $end,
                'duration' => $end - $start,
                'text' => trim($text)
            );
            $ret[] = $current;
            $current = array();
            $text = '';
            $n = 0;
        }
    }
    // var_dump($ret);
    return $ret;
}
// }

add_action( 'wp_ajax_nopriv_mycp_video_url_results', 'myajax_mycp_video_url_results' );
add_action('wp_ajax_mycp_video_url_results', 'myajax_mycp_video_url_results');

function myajax_mycp_video_url_results ()
{
    global $wpdb;

	$ids = $_POST['mycp_ajax_video_post_id'];
	$video_url = $_POST['mycp_ajax_video_url']; 	
	$videoid = mcp_getyoutubeID($video_url);
	
	if(!empty($videoid))
	{
		$lang = 'en';
		$has_timer = false;

		$tube = $videoid;
		$url = "https://www.youtube.com/youtubei/v1/get_transcript?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8";

		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$headers = array(
			"Content-Type: application/json",
		);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		$b64 = base64_encode("\n\x0b" . trim($tube));
		$data = "{\"context\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.2021111\"}},\"params\":\"{$b64}\"}";
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		//for debug only!
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$resp = curl_exec($curl);
		curl_close($curl);
		$resparray = json_decode($resp, 1);
		$actionArr  = $resparray['actions']['0']['updateEngagementPanelAction']['content']['transcriptRenderer']['body']['transcriptBodyRenderer']['cueGroups'];

		//echo print_r($actionArr, 1);

		$ret = array();
		foreach ($actionArr as $cueGroup) 
		{
			$start = isset($cueGroup['transcriptCueGroupRenderer']['cues'][0]['transcriptCueRenderer']['startOffsetMs']) ? intval($cueGroup['transcriptCueGroupRenderer']['cues'][0]['transcriptCueRenderer']['startOffsetMs'] / 1000) : 0;
			$dur = isset($cueGroup['transcriptCueGroupRenderer']['cues'][0]['transcriptCueRenderer']['durationMs']) ? $cueGroup['transcriptCueGroupRenderer']['cues'][0]['transcriptCueRenderer']['durationMs'] : 0;
			$text = $cueGroup['transcriptCueGroupRenderer']['cues'][0]['transcriptCueRenderer']['cue']['simpleText'];
			// if( empty( $text ) )
			//  continue;
			$fila = array(
				'start' => $start,
				'dur' => $dur,
				'text' => $text
			);
			$ret[] = $fila;
		}

		
		if (empty($ret))
			return false;
		foreach ($ret as $node) {
			$scripts[] = array(
				"start" => (float)$node['start'],
				"end" => (float)$node['start'] + (float)$node['dur'],
				"duration" => (float)$node['dur'],
				"text" => (string)$node['text']
			);
		}

		if ($has_timer && spin_oneclickbm_should_fix_scripts($scripts)) 
		{
			$scripts = spin_oneclickbm_fix_scripts($scripts);
			foreach ($scripts as $note) {
				$dataArr['content'][] = array(
					"start" => $note['start'],
					"stamp" => spin_oneclickbm_hmi($note['start']),
					"content" => $note['text']
				);
			}
				
		} 
		else 
		{
			$last_end = 0;
			foreach ($scripts as $note) {
				$note['text'] = trim($note['text']);
				
				if ($last_end == 0) {
					$dataArr['content'][] = array(
						"start" => $note['start'],
						"stamp" => spin_oneclickbm_hmi($note['start']),
						"content" => $note['text']
					);
				} else {
					//Ongoing conversation
					if ($prev_line != "" && spin_oneclickbm_endsWith($prev_line, ".")) {
						if ($note['end'] > $last_end + 3) {
							$dataArr['content'][] = array(
								"start" => $note['start'],
								"stamp" => spin_oneclickbm_hmi($note['start']),
								"content" => ""
							);
						}
					}
					//   exit($note['text']);
					$dataArr['content'][spin_oneclickbm_array_key_last($dataArr['content'])]['content'] .= " " . $note['text'];
				}
				
				$last_end = $note['end'];
				$prev_line = $note['text'];
			} // end foreach
		} // end else
		// $dataArr[ 'content' ] = spin_oneclickbm_fix_content( $dataArr[ 'content' ], $has_timer );		
					

		//$dataArr['content'] = spin_oneclickbm_fix_content($dataArr['content'], $has_timer);

		$content = $dataArr['content'];
		$ret = '';
		foreach ($content as $chunk) {
			// var_dump($chunk);
			if ($has_timer) {
				if (!empty($chunk['start']))
					$ret .= '<br/><a style="cursor: pointer;" data-seek="' . $chunk['start'] . '" class="seek">' . $chunk['stamp'] . '</a><br/>';
			}
			$ret .= $chunk['content'];
		}
		
		if ($has_timer)
			return $ret;
		// var_dump(substr_count ( $ret, '.' ));
		if (spin_oneclickbm_not_formatted($ret)) {
			// if( substr_count ( $ret, '.' ) < 5 ) {
			// no puntos
			$ret = spin_oneclickbm_punctuate($ret, false);
			//$ret =$ret;
		}


		$paragraphs = spin_oneclickbm_breakLongText($ret);
		
		
		$from = array('& # 39.', ' & # 39, ');
		$to = array('\'', '\'');
		$paragraphs = str_replace($from, $to, $paragraphs);

		$return_para = spin_oneclick_paragraphs($paragraphs);

		$post_content = $return_para;

		$post_content = preg_replace('~\R~',' ',$post_content);
		
		
		$post_title = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=".$videoid."&key=AIzaSyCUHi5qQUffrq-lFOu-j3VpApXTgD_GZsU";	
		$chs = curl_init();

		curl_setopt($chs, CURLOPT_HEADER, 0);
		curl_setopt($chs, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($chs, CURLOPT_URL, $post_title);
		curl_setopt($chs, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($chs, CURLOPT_VERBOSE, 0);
		curl_setopt($chs, CURLOPT_SSL_VERIFYPEER, false);
		$post_title_response = curl_exec($chs);

		curl_close($chs);
		$post_title_data = json_decode($post_title_response);
		
		$post['title'] = $post_title_data->items[0]->snippet->title;
		
		$post_content .='<p>Source Link: <a href="https://www.youtube.com/watch?v='.$videoid.'">https://www.youtube.com/watch?v='.$videoid.'</a></p>';

		$post['image'] = 'https://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';

		$post_tags = $post_title_data->items[0]->snippet->tags;
		
		$post['content']=$post_content;
		
		$image_url        = $post['image']; // Define the image URL here
		$image_name       = time().'-'.$ids.'-hqdefault.jpg';
		$upload_dir       = wp_upload_dir(); // Set upload folder
		$image_data       = file_get_contents($image_url); // Get image data
		$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
		$filename         = basename( $unique_file_name ); // Create image file name

		// Check folder permission and define file location
		if( wp_mkdir_p( $upload_dir['path'] ) ) {
		  $file = $upload_dir['path'] . '/' . $filename;
		} else {
		  $file = $upload_dir['basedir'] . '/' . $filename;
		}

		// Create the image  file on the server
		file_put_contents( $file, $image_data );

		// Check image file type
		$wp_filetype = wp_check_filetype( $filename, null );

		// Set attachment data
		$attachment = array(
			'post_mime_type' => $wp_filetype['type'],
			'post_title'     => sanitize_file_name( $filename ),
			'post_content'   => '',
			'post_status'    => 'inherit'
		);

		// Create the attachment
		$attach_id = wp_insert_attachment( $attachment, $file, $ids );

		// Include image.php
		require_once(ABSPATH . 'wp-admin/includes/image.php');

		// Define attachment metadata
		$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

		// Assign metadata to attachment
		wp_update_attachment_metadata( $attach_id, $attach_data );

		// And finally assign featured image to post
		set_post_thumbnail( $ids, $attach_id );
		
        $spin_vid_edit_link_option = "<iframe width=620 height=330 src=https://www.youtube.com/embed/$videoid></iframe>";

		$my_post = array(
			  'ID'           => $ids,
			  'post_title'   => $post['title'],
			  'post_content' => $spin_vid_edit_link_option."<br/>".$post['content'],
			  'post_status'  => 'draft',
			  'tags_input' => $post_tags
		  );
			 
		// Update the post into the database
		wp_update_post( $my_post );	
		
		
		$url_post = get_admin_url().'post.php?post='.$ids.'&action=edit';	
		?>
		<script>
		jQuery(function() 
		{
			window.location = "<?php echo $url_post; ?>";
		});
		</script>    
	<?php	
	}
	else
	{
		echo "<p style=color:red;>*Please Select YouTube Video Url.</p>";
	}
	exit;
}

function mcp_trimString($haystack, $length, $search, $insert = ''){
    $str_length = strlen($haystack);

    if ($str_length <= $length){
        return $haystack;
    }

    $from = 0;
    $string_value = '';
    $search_after = $length;

    // find the last position of $search in the string
    $pos_last_dot = strrpos($haystack, $search);

    while ($search_after <= $pos_last_dot) {
        // get the position of $search after the last position
        $pos = strpos($haystack , $search, $search_after);

        // append the $search and the $insert for a new line
        $string_value .= substr(substr($haystack, 0, $pos), $from) . $search . $insert;

        // set the cursor to the next position after the finding $search
        $from = $pos + 1;

        // add the last occurence of $search
        if (($from + $length) >= $pos_last_dot && $pos != $pos_last_dot) {
            $string_value .= substr(substr($haystack, 0, $pos_last_dot), $from) . $search . $insert;
            break;
        }

        $search_after = $from + $length;
    }

    return $string_value;
}

?>