<?php
//auto_post_schedule(78);
function myauto_post_schedule_ch($postid){
	$post = get_post($postid);
    
	$auto_post = get_post_meta($post->ID,'wpch_auto_post',true);
	
	$auto_post='yes';

	if ($auto_post == 'yes') {
		include_once('api/twitter/codebird.php');  // twitter api library
		include_once('api/tumblr/TumblrAPIClient.php');  // Tumblr api library
		include_once('api/linkedin/liOAuth.php');
		include('cores/auto-post.php');
		$check = update_post_meta($post->ID, 'wpch_auto_post', 'no');
		$_POST['wpch_auto_post'] = 'no';
	}
}

/**
 * Auto Post Action
 *
 * */

/* Multiple Posting Solution*/

function myauto_post_ch($new_status, $old_status, $post) {
	if(isset($_POST['wpch_auto_post']) || !empty($_POST['wpch_auto_post']))
	{
		$auto_post = sanitize_text_field($_POST['wpch_auto_post']);
		if(($new_status == 'publish' && $new_status !== $old_status) || $new_status == $old_status ) {
			if($new_status != 'future'){ 
				if( ($auto_post == 'yes' ) ){
					include_once('api/twitter/codebird.php');  // twitter api library
					include_once('api/tumblr/TumblrAPIClient.php');  // Tumblr api library
					include_once('api/linkedin/liOAuth.php');
					include('cores/auto-post.php');
					$check = update_post_meta($post->ID, 'wpch_auto_post', 'no');
					$_POST['wpch_auto_post'] = 'no';
				}
			}
		}
	}
}

function myadd_wpch_meta_box($post_type) {
	add_meta_box(
			'wpch_meta_box'
			, __('MyContentCreatorPro Social Auto Post', WPCH_LN)
			, 'myrender_meta_box_content_ch'
			, $post_type
			, 'side'
			, 'high'
	);
}

function myrender_meta_box_content_ch($post) {
	// Add an nonce field so we can check for it later.
	wp_nonce_field('wpch_meta_box_nonce_action', 'wpch_meta_box_nonce_field');

	// Use get_post_meta to retrieve an existing value from the database.
	$auto_post = get_post_meta($post->ID, 'wpch_auto_post', true);
	//var_dump($auto_post);
	$auto_post = ($auto_post == '' || $auto_post == 'yes') ? 'yes' : 'no';

	//echo $auto_post;

	// Display the form, using the current value.
	?>
	<label for="wpch_auto_post"><?php _e('Enable Auto Post', WPCH_LN); ?></label>
	<p>
		<select name="wpch_auto_post">
			<option value="yes" <?php selected($auto_post, 'yes'); ?>><?php _e('Yes', WPCH_LN); ?></option>
			<option value="no" <?php selected($auto_post, 'no'); ?>><?php _e('No', WPCH_LN); ?></option>
		</select>
	</p>
	<?php
}

function mysave_wpch_meta_value($post_id) {


	// Check if our nonce is set.
	if (!isset($_POST['wpch_auto_post']))
		return $post_id;

	$nonce = $_POST['wpch_meta_box_nonce_field'];

	// Verify that the nonce is valid.
	if (!wp_verify_nonce($nonce, 'wpch_meta_box_nonce_action'))
		return $post_id;

	// If this is an autosave, our form has not been submitted,
	//     so we don't want to do anything.
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
		return $post_id;

	// Check the user's permissions.
	if ('page' == $_POST['post_type']) {

		if (!current_user_can('edit_page', $post_id))
			return $post_id;
	} else {

		if (!current_user_can('edit_post', $post_id))
			return $post_id;
	}

	/* OK, its safe for us to save the data now. */

	// Sanitize the user input.
	$auto_post = sanitize_text_field($_POST['wpch_auto_post']);

	// Update the meta field.
	update_post_meta($post_id, 'wpch_auto_post', $auto_post);
}


add_action( 'wp_ajax_nopriv_save_api_settings_result', 'myajax_wpch_save_api_settings_result' );
add_action('wp_ajax_save_api_settings_result', 'myajax_wpch_save_api_settings_result');

function myajax_wpch_save_api_settings_result ()
{
	if(isset($_POST['ezinearticle_api']) && $_POST['ezinearticle_api']!=''){
		$ezinearticle_api = $_POST['ezinearticle_api'];
		update_option('wpch_ezinearticle_api', $ezinearticle_api);
		echo 'success';
	}else{
		echo 'Please enter ezine article api key.';
	}
	exit;
}

add_action( 'wp_ajax_nopriv_ch_spin_search_result', 'myajax_wpch_spin_search_result' );
add_action('wp_ajax_ch_spin_search_result', 'myajax_wpch_spin_search_result');

function myajax_wpch_spin_search_result ()
{
	$ch_spin = $_POST['ch_spin_test'];
	
	$api_url = "https://wprankbuddy.com/turbospinners/api.php";
	$api_key = "11cf79d44024d6608eca69d6e381bcf4";
	$article = $ch_spin;
	$lang    = "en";
	
	$cookie=tempnam("/tmp","CURLCOOKIE");
	$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7";
	$ch = curl_init();
	
	$data = "api_key=$api_key&article=$article&lang=$lang";
	curl_setopt($ch, CURLOPT_URL,"$api_url");    
	curl_setopt($ch, CURLOPT_USERAGENT, $agent);
	curl_setopt($ch,CURLOPT_ENCODING,"gzip,deflate");
	curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded","Accept: */*"));
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_REFERER, "http://prothemes.biz");
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"$data");
	$result_spins = curl_exec($ch);
	
	?>
	<textarea id="article_messages" name="article_gen_msg"><?php echo $result_spins; ?></textarea>
	<?php	
	exit;
}


add_action( 'wp_ajax_nopriv_ch_spin_rewriter', 'myajax_wpch_spin_rewriter' );
add_action('wp_ajax_ch_spin_rewriter', 'myajax_wpch_spin_rewriter');
function myajax_wpch_spin_rewriter()
{
	global $wpdb;
	
	include_once("auto_content/template/class/afe_blog.php");		
    $spin_blog_aticle_rewriter = new afeblogs();
		
	$ch_spin_test_rewriters = $_POST['ch_spin_test_rewriter'];	
	
	$ch_spin_test_rewriter = str_replace("<br>", " <--> ", $ch_spin_test_rewriters);		
		
	// 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_spin_api_rewriter=$spin_blog_aticle_rewriter->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$ch_spin_test_rewriter);

		$afe_spin_api_rewriter=$spin_blog_aticle_rewriter->spin_rewriter_afe($result_spinrewriter_email1,$result_spinrewriter_api1,$ch_spin_test_rewriter);
		
		if(!empty($afe_spin_api_rewriter))
		{
			$spinned_rewriter = stripslashes($afe_spin_api_rewriter['response']);
		}
		else
		{
			$spinned_rewriter = stripslashes($afe_spin_api_rewriter);
		}		
	}				
	else
	{
		$spinned_rewriter = stripslashes($afe_spin_api_rewriter);
	}					
	
	// 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) && !empty($spinned_rewriter))
	{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, 'https://api.perfecttense.com/correct');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"text\": \"'".$spinned_rewriter."'\", \"responseType\": [\"corrected\", \"grammarScore\", \"rulesApplied\", \"offset\", \"summary\"]}");

		$headers = array();
		$headers[] = 'Authorization: '.$result_perfecttense_api;
		$headers[] = 'Appauthorization: '.$result_perfecttense_app;
		$headers[] = 'Content-Type: application/json';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$result11 = curl_exec($ch);
		curl_close($ch);
		
		$corrected_arr = array();
		$corrected_arrs = array();
		$affected_arrs = array();
		$replace_affected_arrs = array();
		
		if(!empty($result11))
		{
			$pt_response = json_decode($result11);	
			
			//echo "<pre>";
			//print_r($pt_response);
			//echo "</pre>";
			
			foreach($pt_response->offset as $offset)
			{		
				if(!empty($offset->corrections))
				{
					$corrected_arr[] = $offset->corrections;
				}
			}			
		}			

		if(!empty($corrected_arr))
		{
			foreach($corrected_arr as $corrected_arr1)
			{
				foreach($corrected_arr1 as $corrected_arr2)
				{
					$correct_arr = end($corrected_arr2->options);
					$corrected_arrs[] = $correct_arr->corrected;
					$affected_arrs[] = $corrected_arr2->affected;
					$replace_affected_arrs[] = "<u style=color:red>".$corrected_arr2->affected."</u>";
				}
					
			}
		}			
		
		
		$newPhrase = str_replace($affected_arrs, $replace_affected_arrs, $spinned_rewriter);	
		$newPhrase_new = str_replace($replace_affected_arrs, $corrected_arrs, $newPhrase);	
		
	}	
	
	$newPhrase_rewriter = str_replace("<-->", "<br/>", $newPhrase);		
	$newPhrase_new_rewriter = str_replace("<-->", "<br/>", $newPhrase_new);		
		
	?>
	<h2 id="perfect_tense_title" style="margin: 20px 0 20px;">Fix Spelling & Grammer</h2>		
	<p id="article_messages_spin_rewriter"><?php echo $newPhrase_rewriter; ?></p>
	<input id="article_messages_spin_rewriter_hidden" type="hidden" value="<?php echo $newPhrase_new_rewriter; ?>" />
	<input id="old_article_messages_spin_rewriter_hidden" type="hidden" value="<?php echo $newPhrase_rewriter; ?>" />
	<?php	
	exit;
}

add_action( 'wp_ajax_nopriv_ch_spin_ignore_error', 'myajax_wpch_spin_ignore_error' );
add_action('wp_ajax_ch_spin_ignore_error', 'myajax_wpch_spin_ignore_error');
function myajax_wpch_spin_ignore_error()
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);

	$ch_spin_perfect_test_ignore_rewriter = $_POST['ch_spin_msg_tense_ignore'];	
	$newPhrase_news_ignore = str_replace("<u style=color:red>", "" , $ch_spin_perfect_test_ignore_rewriter);	
	$newPhrase_newss_ignore = str_replace("</u>", "" , $newPhrase_news_ignore);	
	
	?>
	<h2 style="margin: 20px 0 20px;">Fix Spelling & Grammer</h2>		
	<p id="article_messages_spin_rewriters"><?php echo stripslashes($newPhrase_news_ignore); ?></p>
	<input id="article_messages_spin_rewriters_hidden" type="hidden" value="<?php echo stripslashes($newPhrase_newss_ignore); ?>" />
	<?php	
	exit;
}

add_action( 'wp_ajax_nopriv_ch_spin_fix_grammer', 'myajax_wpch_spin_fix_grammer' );
add_action('wp_ajax_ch_spin_fix_grammer', 'myajax_wpch_spin_fix_grammer');
function myajax_wpch_spin_fix_grammer()
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);

	$ch_spin_perfect_test_rewriter = $_POST['ch_spin_msg_tense'];	
	$newPhrase_news = str_replace("<u style=color:red>", "" , $ch_spin_perfect_test_rewriter);	
	$newPhrase_newss = str_replace("</u>", "" , $newPhrase_news);	
	
	?>
	<h2 style="margin: 20px 0 20px;">Fix Spelling & Grammer</h2>		
	<p id="article_messages_spin_rewriters"><?php echo stripslashes($newPhrase_newss); ?></p>
	<input id="article_messages_spin_rewriters_hidden" type="hidden" value="<?php echo stripslashes($newPhrase_newss); ?>" />
	<?php	
	exit;
}

add_action( 'wp_ajax_nopriv_ch_spinner_post_result', 'myajax_wpch_spinner_post_result' );
add_action('wp_ajax_ch_spinner_post_result', 'myajax_wpch_spinner_post_result');
function myajax_wpch_spinner_post_result()
{
	global $user_ID, $wpdb;
	$postContent = $_POST['ch_spinner_msg'];
	$query = $wpdb->prepare(
		'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_content = %s',
		$postContent
	);
	$wpdb->query( $query );
	if ( $wpdb->num_rows ) 
	{
	?>
		<div class="wrap">
			<div class="error"><p>Post is alreday created</p></div>
		</div>
	<?php
	} 
	else 
	{
		$spin_my_post_insert = array(
						  'post_title'    => '',
						  'post_content'  => $postContent,
						  'post_status'   => 'publish',
						  'post_author'   => 1,
						  'post_category' => array( 8,39 )
						);
						 
						// Insert the post into the database
		$spin_post_insert = wp_insert_post( $spin_my_post_insert );
	
		if($spin_post_insert)
		{
			?><script>window.open("<?php echo admin_url('post.php?post='.$spin_post_insert.'&action=edit'); ?>");</script><?php
		}
	}
	?>
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 5000); // <-- time in milliseconds
	});
	</script>	
	<?php
	exit;
}

add_action( 'wp_ajax_nopriv_pdf_link_result', 'myajax_wpch_pdf_link_result' );
add_action('wp_ajax_pdf_link_result', 'myajax_wpch_pdf_link_result');

function myajax_wpch_pdf_link_result (){
	global $wpdb;
	$ch_pdf_link = (isset($_POST['ch_pdf_link']) && $_POST['ch_pdf_link']!=''?$_POST['ch_pdf_link']:'#');
	$link_text   = (isset($_POST['ch_link_text']) && $_POST['ch_link_text']!=''?$_POST['ch_link_text']:'Want to learn more? Click here');
	$link_position= $_POST['ch_pdf_position'];
	
	$post_id = $_POST['ch_pdf_pid'];
	$post = get_post($post_id);
    //echo"<pre>";print_r($link_position);echo"</pre>";
	
	$ch_pdf_title       = $post->post_title;
	$post->post_content = $post->post_content;
	
	if(in_array('middle',$link_position)){
    $post->post_content = mypdf_string_replace_link($post->post_content,$ch_pdf_link,$link_text);
    }
	
	$pdfprnt_options = array();
	$upload_dir = wp_upload_dir();

    $year = date("Y");   
    $month = date("m");  
    //$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $ch_pdf_title);	
    //$filename = $upload_dir["basedir"]."/".$year."/".$month. '/' . $slug . '.pdf';
	
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $post->post_name);
	$slug=rand(0,999).'-'.$slug;
	$filename = $upload_dir["basedir"].'/content-hero/' . $slug . '.pdf';
	
	define( '_MPDF_SYSTEM_TTFONTS', $upload_dir['basedir'] .'/pdf-print-fonts/' );
	/* prepare data */

	//$content = $post->post_content;
	

	if (! class_exists ( 'TCPDF' )) {
		require_once PTPDF_PATH . '/includes/tcpdf_min/tcpdf.php';
	}
	if (! class_exists ( 'pdfheader' )) {
		require_once PTPDF_PATH . '/includes/pdfheader.php';
	}
	if (! class_exists ( 'simple_html_dom_node' )) {
		require_once PTPDF_PATH . '/includes/simplehtmldom/simple_html_dom.php';
	}
	$post->post_content = apply_filters ( 'the_post_export_content', $post->post_content );
	$post->post_content = wpautop ( $post->post_content );
	//$post->post_content = do_shortcode ( $post->post_content );
	$post->post_content = preg_replace('#\[[^\]]+\]#', '',$post->post_content);;



	// new PDF document

	$pagesize = 'A4';
	$unit     = 'mm';
	$orientation ='P';

	$pdf = new CUSTOMPDF ( $orientation, $unit, $pagesize, true, 'UTF-8', false );

	// information about doc
	$pdf->SetCreator ( 'MyContentCreatorPro' );
	$pdf->SetAuthor ( get_bloginfo ( 'name' ) );
	$pdf_title = $post->post_title;


	$blog_name = get_bloginfo ( 'name' );
	$bolg_description = get_bloginfo ( 'description' );
	$home_url = home_url();


	// set header and footer fonts
	$pdf->setHeaderFont ( array ('helvetica','',12) );
	$pdf->setFooterFont ( array ('helvetica','',12) );

	$pdf->SetLeftMargin ('15');
	$pdf->SetRightMargin ('15');
	$pdf->SetTopMargin ('5');
	$pdf->SetHeaderMargin ('5');
	$pdf->SetFooterMargin ( '10' );
	// set auto page breaks
	$pdf->SetAutoPageBreak ( TRUE, '10' );
	$pdf->setImageScale ('1.25');

	// set default font subsetting mode
	$pdf->setFontSubsetting ( true );

	$pdf->SetFont ('helvetica', '',12, '', true );



	$page_format = array();
	$page_format['Rotate'] = 0;

	$pdf->AddPage('P', $page_format, false, false);
	$html = "";

	$html .= "<body>";
	$html .= "<h1 style=\"text-align:center\">".apply_filters ( 'the_post_title', $pdf_title )."</h1>";
	/* if (isset ( $this->options ['authorDetail'] ) and ! $this->options ['authorDetail'] == '') {
		$author_id = $post->post_author;
		$author_meta_key = $this->options ['authorDetail'];
		$author = get_user_meta ( $author_id );
		$html .= '<p><strong>Author : </strong>' . $author [$author_meta_key] [0] . '</p>';
	}

	if (isset ( $this->options ['postCategories'] )) {
		$categories = get_the_category ( $post->ID );
		if ($categories) {
			$html .= '<p><strong>Categories : </strong>' . $categories [0]->cat_name . '</p>';
		}
	}
	// Display tag list is set in config
	if (isset ( $this->options ['postTags'] )) {
		$tags = get_the_tags ( $post->the_tags );
		if ($tags) {
			$html .= '<p><strong>Tagged as : </strong>';
			foreach ( $tags as $tag ) {
				$tag_link = get_tag_link ( $tag->term_id );
				$html .= '<a href="' . $tag_link . '">' . $tag->name . '</a>';
				if (next ( $tags )) {
					$html .= ', ';
				}
			}
			$html .= '</p>';
		}
	}
	// Display date if set in config
	if (isset ( $this->options ['postDate'] )) {
		$newDate = date ( "d-m-Y", strtotime ( $post->post_date ) );
		$html .= '<p><strong>Date : </strong>' . $newDate . '</p>';
	} */

	// Set some content to print
	//$html .= '<h1>' . html_entity_decode ( $pdf_title, ENT_QUOTES ) . '</h1>';

	// Display feachered image if set in config on page/post

	if (has_post_thumbnail ( $post->ID )) {
		$html .= get_the_post_thumbnail ( $post->ID );
	}
	
	if(in_array('top',$link_position)){
	$html .= '<p><a href="'.$ch_pdf_link.'">'.$link_text.'</a><p>';
	}
	$post_content = $post->post_content;
	if (empty ( $post->post_content )) {
		$post_content = isset ( $this->options ['docEntryTpl'] ) ? $this->options ['docEntryTpl'] : '';
	}
	/* echo"<pre>";print_r($post_content);echo"</pre>"; */
	
	$html .= htmlspecialchars_decode ( htmlentities ( $post_content, ENT_NOQUOTES, 'UTF-8', false ), ENT_NOQUOTES );
    
	if(in_array('bottom',$link_position)){
	$html .= '<p><a href="'.$ch_pdf_link.'">'.$link_text.'</a><p>';
	}

	/* if( isset($pdf_settings) && $pdf_settings['end_text'] && !empty( $pdf_settings['end_text'] ) ) {
		$html .= '<br/>aaa'.$pdf_settings['end_text'].'bbb<br/>';
	}
	 */
	
		
	$html .="</body>";
	$dom = new simple_html_dom ();
	$dom->load ( $html );

	foreach ( $dom->find ( 'img' ) as $e ) {
		$exurl = ''; // external streams
		$imsize = FALSE;
		$file = $e->src;
		// check if we are passing an image as file or string
		if ($file [0] === '@') {
			// image from string
			$imgdata = substr ( $file, 1 );
		} else { // image file
			if ($file [0] === '*') {
				// image as external stream
				$file = substr ( $file, 1 );
				$exurl = $file;
			}
			// check if is local file
			if (! @file_exists ( $file )) {
				// encode spaces on filename (file is probably an URL)
				$file = str_replace ( ' ', '%20', $file );
			}
			if (@file_exists ( $file )) {
				// get image dimensions
				$imsize = @getimagesize ( $file );
			}
			if ($imsize === FALSE) {
				$imgdata = TCPDF_STATIC::fileGetContents ( $file );
			}
		}
		if (isset ( $imgdata ) and ($imgdata !== FALSE) and (strpos ( $file, '__tcpdf_img' ) === FALSE)) {
			// check Image size
			$imsize = @getimagesize ( $file );
		}
		if ($imsize === FALSE) {
			$e->outertext = '';
		} else {
			// End Image Check
			if (preg_match ( '/alignleft/i', $e->class )) {
				$imgalign = 'left';
			} elseif (preg_match ( '/alignright/i', $e->class )) {
				$imgalign = 'right';
			} elseif (preg_match ( '/aligncenter/i', $e->class )) {
				$imgalign = 'center';
				$htmlimgalign = 'middle';
			} else {
				$imgalign = 'none';
			}

			$e->class = null;
			$e->align = $imgalign;
			if (isset ( $htmlimgalign )) {
				$e->style = 'float:' . $htmlimgalign;
			} else {
				$e->style = 'float:' . $imgalign;
			}

			if (strtolower ( substr ( $e->src, - 4 ) ) == '.svg') {
				$e->src = null;
				$e->outertext = '<div style="text-align:' . $imgalign . '">[ SVG: ' . $e->alt . ' ]</div><br/>';
			} else {
				$e->outertext = '<div style="text-align:' . $imgalign . '">' . $e->outertext . '</div>';
			}
		}
	}
	/******parsing dom element and passing null action attribute if action attribute is not set ***/
	foreach ($dom->find ('form') as $e)
	{
		if(!isset($e->attr['action']))
		{
			$e->action = '';
		}
	}

	$html = $dom->save ();
	$dom->clear ();
	$pdf->setFormDefaultProp ( array (
			'lineWidth' => 1,
			'borderStyle' => 'solid',
			'fillColor' => array (
					255,
					255,
					200
			),
			'strokeColor' => array (
					255,
					128,
					128
			)
	) );



	// Print text using writeHTML
	$pdf->writeHTML ( $html, true, 0, true, 0 );
	// ---------------------------------------------------------
	if (! is_dir ( $upload_dir["basedir"].'/content-hero/' )) {
		mkdir ( $upload_dir["basedir"].'/content-hero/', 0755, true );
	}
	$pdf->Output( $filename, 'F' );
    
    if(file_exists( $filename))
    {
        $uploads = wp_upload_dir();
		
        $pdf_url = $uploads['baseurl'].'/content-hero/'.$slug.'.pdf';
        update_post_meta( $post_id,'wpch_link_pdf', $pdf_url );
		?>
        <script>
           window.open('<?php echo $pdf_url; ?>', '_blank');
        </script>
        <?php
    }
	
	exit;
}

add_action( 'wp_ajax_nopriv_pdf_result', 'myajax_wpch_pdf_result' );
add_action('wp_ajax_pdf_result', 'myajax_wpch_pdf_result');
function myajax_wpch_pdf_result ()
{
	$title = $_POST['ch_pdf_title'];
	$content = $_POST['ch_pdf_content'];
	$logo = $_POST['ch_pdf_logo'];

	$pdfprnt_options = array();
	$upload_dir = wp_upload_dir();

    $year = date("Y");   
    $month = date("m");  
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $title);
    $slug=rand(0,999).'-'.$slug;	
    $filename = $upload_dir["basedir"].'/content-hero/' . $slug . '.pdf';

	define( '_MPDF_SYSTEM_TTFONTS', $upload_dir['basedir'] .'/pdf-print-fonts/' );
	/* prepare data */
	$post=array();
	$post['title']=$title;
	$post['content']=$content;
	$post['logo']=$logo;
	$post['file']=$filename;
    //require 'get_pdf.php';
	if (! class_exists ( 'TCPDF' )) {
		require_once PTPDF_PATH . '/includes/tcpdf_min/tcpdf.php';
	}
	if (! class_exists ( 'pdfheader' )) {
		require_once PTPDF_PATH . '/includes/pdfheader.php';
	}
	if (! class_exists ( 'simple_html_dom_node' )) {
		require_once PTPDF_PATH . '/includes/simplehtmldom/simple_html_dom.php';
	}
	

	
	$content = $post['content'];
	$content = preg_replace('#\[[^\]]+\]#', '',$content);;
	$content = apply_filters ( 'the_post_export_content', $content );
	$content = wpautop ( $content );
	//$post->post_content = do_shortcode ( $post->post_content );

	$filePath = $post['file'];

	$pagesize = 'A4';
	$unit     = 'mm';
	$orientation ='P';

	$pdf = new CUSTOMPDF ( $orientation, $unit, $pagesize, true, 'UTF-8', false );
	$pdf->SetCreator ( 'MyContentCreatorPro' );
	$pdf->SetAuthor ( get_bloginfo ( 'name' ) );

    $pdf_title = $title;

	$pdf->setHeaderFont ( array ('helvetica','',12) );
	$pdf->setFooterFont ( array ('helvetica','',12) );

	$pdf->SetDefaultMonospacedFont ('courier');

	$pdf->SetLeftMargin ('15');
	$pdf->SetRightMargin ('15');
	$pdf->SetTopMargin ('5');
	$pdf->SetHeaderMargin ('5');
	$pdf->SetFooterMargin ( '10' );
	// set auto page breaks
	$pdf->SetAutoPageBreak ( TRUE, '10' );
	$pdf->setImageScale ('1.25');
	// set default font subsetting mode
	$pdf->setFontSubsetting ( true );
	$pdf->SetFont ('helvetica', '',12, '', true );

	$page_format = array();
	$page_format['Rotate'] = '0';
	
	$html = '';
	$pdf->AddPage('P', $page_format, false, false);
	$html .= "<body>";


	$html .= "<center>";
	if( $post['logo'] && !empty( $post['logo'] ) ) {
		$infologo = getimagesize ( $post['logo'] );
		$html .= '<p style="text-align:center"><img style="max-width:100%;height:auto;width:'.$infologo[0].'px;" src="'.$post['logo'].'" /></p>';
	}
	$html .= "</center>";
	
	$pdf->writeHTML ( $html, true, 0, true, 0 );
	//$pdf->AddPage($this->options ['page_orientation'], $page_format, false, false);
	$html = '';

	$html .= '<p><strong>Title : </strong>'.$pdf_title.'</p>';
	$html .= '<p><strong>Text : </strong></p>';

	$post_content = $content;
	if (empty ( $post_content )) {
		$post_content = isset ( $this->options ['docEntryTpl'] ) ? $this->options ['docEntryTpl'] : '';
	}
	$html .= htmlspecialchars_decode ( htmlentities ( $post_content, ENT_NOQUOTES, 'UTF-8', false ), ENT_NOQUOTES );

	if( $pdf_settings['end_text'] && !empty( $pdf_settings['end_text'] ) ) {
		$html .= '<br/>'.nl2br( $pdf_settings['end_text'] ).'<br/>';
	}
	
	if( $pdf_settings['display_link'] && !empty( $pdf_settings['display_link'] ) ) {
		$article_link = get_permalink( $postID );
		$html .= '<br/><hr/><br/><p>Read the original article at: <a href="'.$article_link.'">'.$article_link.'</a><p>';
	}

	$html .="</body>";
	$dom = new simple_html_dom ();
	$dom->load ( $html );

	foreach ( $dom->find ( 'img' ) as $e ) {
		$exurl = ''; // external streams
		$imsize = FALSE;
		$file = $e->src;
		// check if we are passing an image as file or string
		if ($file [0] === '@') {
			// image from string
			$imgdata = substr ( $file, 1 );
		} else { // image file
			if ($file [0] === '*') {
				// image as external stream
				$file = substr ( $file, 1 );
				$exurl = $file;
			}
			// check if is local file
			if (! @file_exists ( $file )) {
				// encode spaces on filename (file is probably an URL)
				$file = str_replace ( ' ', '%20', $file );
			}
			if (@file_exists ( $file )) {
				// get image dimensions
				$imsize = @getimagesize ( $file );
			}
			if ($imsize === FALSE) {
				$imgdata = TCPDF_STATIC::fileGetContents ( $file );
			}
		}
		if (isset ( $imgdata ) and ($imgdata !== FALSE) and (strpos ( $file, '__tcpdf_img' ) === FALSE)) {
			// check Image size
			$imsize = @getimagesize ( $file );
		}
		if ($imsize === FALSE) {
			$e->outertext = '';
		} else {
			// End Image Check
			if (preg_match ( '/alignleft/i', $e->class )) {
				$imgalign = 'left';
			} elseif (preg_match ( '/alignright/i', $e->class )) {
				$imgalign = 'right';
			} elseif (preg_match ( '/aligncenter/i', $e->class )) {
				$imgalign = 'center';
				$htmlimgalign = 'middle';
			} else {
				$imgalign = 'none';
			}

			$e->class = null;
			$e->align = $imgalign;
			if (isset ( $htmlimgalign )) {
				$e->style = 'float:' . $htmlimgalign;
			} else {
				$e->style = 'float:' . $imgalign;
			}

			if (strtolower ( substr ( $e->src, - 4 ) ) == '.svg') {
				$e->src = null;
				$e->outertext = '<div style="text-align:' . $imgalign . '">[ SVG: ' . $e->alt . ' ]</div><br/>';
			} else {
				$e->outertext = '<div style="text-align:' . $imgalign . '">' . $e->outertext . '</div>';
			}
		}
	}
	$html = $dom->save ();
	$dom->clear ();
	$pdf->setFormDefaultProp ( array (
			'lineWidth' => 1,
			'borderStyle' => 'solid',
			'fillColor' => array (
					255,
					255,
					200
			),
			'strokeColor' => array (
					255,
					128,
					128
			)
	) );
	// Print text using writeHTML
	$pdf->writeHTML ( $html, true, 0, true, 0 );
	// ---------------------------------------------------------
	if (! is_dir ( $upload_dir["basedir"].'/content-hero/' )) {
		mkdir ( $upload_dir["basedir"].'/content-hero/', 0755, true );
	}
	$pdf->Output ( $filePath, 'F' );

    if(file_exists( $filename))
    {
        $uploads = wp_upload_dir();
        $pdf_url = $uploads['baseurl'].'/content-hero/' . $slug . '.pdf';
        ?>
        <script>
           window.open('<?php echo $pdf_url; ?>', '_blank');
        </script>
        <?php
    }
	
	exit;
}
function myajax_wpch_pdf_result_old ()
{
	$ch_pdf_title = $_POST['ch_pdf_title'];
	$ch_pdf_content = $_POST['ch_pdf_content'];
	$ch_pdf_logo = $_POST['ch_pdf_logo'];

	$pdfprnt_options = array();
	$upload_dir = wp_upload_dir();

    $year = date("Y");   
    $month = date("m");  
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $ch_pdf_title);	
    $filename = $upload_dir["basedir"]."/".$year."/".$month. '/' . $slug . '.pdf';

	define( '_MPDF_SYSTEM_TTFONTS', $upload_dir['basedir'] .'/pdf-print-fonts/' );
	/* prepare data */
	$titles = $authors = array();
	$authors = array('naveen','admin');
	$default_font = 0 == $pdfprnt_options['additional_fonts'] ? 'dejavusansmono' : '';

	$html =
		'<div id="content"><div class="post">' .
			'"'.$ch_pdf_title.'"' .
			'<div class="entry-content">"'.$ch_pdf_content.'"</div>
		</div>';
	$html .= '<br/><hr/><br/>';
	$html .= '</div>';
	$titles = array($ch_pdf_title);
	$titles = array_unique( $titles );
	$authors = array_unique( $authors );

	$pdfprnt_links = $pdfprnt_options['disable_links'];

	/* generate PDF-document */
		include_once("pdf/mpdf/mpdf.php"); 

		$mpdf = new mPDF(
				'+aCJK',
				'A4',
				0,
				$default_font,
				'15',
				'15',
				'16',
				'16'
		);
	//ob_start();

	$mpdf->allow_charset_conversion = true;
	$mpdf->charset_in = get_bloginfo( 'charset' );
	if ( 0 != $pdfprnt_options['additional_fonts'] ) {
		$mpdf->autoScriptToLang = true;
		$mpdf->autoLangToFont = true;
		$mpdf->baseScript = 1;
		$mpdf->autoVietnamese = true;
		$mpdf->autoArabic = true;
	}	
	$mpdf->SetTitle( htmlspecialchars_decode( implode( ',', $titles ) ) );
	$mpdf->SetAuthor( implode( ',', $authors ) );
	$mpdf->SetSubject( get_bloginfo( 'blogdescription' ) );
	//$html = ob_get_contents();
	//ob_end_clean();

	$mpdf->WriteHTML( mycontenthero_pdfprnt_generate_template( $html ) );
	$mpdf->Output($filename, 'F');

    if(file_exists( $filename))
    {
        $uploads = wp_upload_dir();
        $pdf_url = $uploads['baseurl']."/".$year."/".$month. '/' . $slug . '.pdf';
        ?>
        <script>
           window.open('<?php echo $pdf_url; ?>', '_blank');
        </script>
        <?php
    }
	
	exit;
}


	function mycontenthero_pdfprnt_generate_template( $content, $is_print = false ) {
		global $pdfprnt_options, $wp_locale, $post;
		$html =
		'<html>
			<head>';
				if ( $is_print && $post instanceof WP_Post ) {
					if ( is_archive() || is_category() || is_tax() || is_tag() || is_author() || ! pdfprnt_is_user_role_enabled() ) {
						$title = ( function_exists( 'get_the_archive_title' ) ) ? get_the_archive_title() : wp_title( '', false );
					} elseif ( is_search() ) {
						$title = sprintf( __( 'Search Results for: %s', 'pdf-print' ), get_search_query() );
					} else {
						$title = get_the_title();
					}
					$html .= sprintf(
						'<title>%s - %s</title>',
						strip_tags( $title ),
						get_bloginfo( 'name' )
					);
				}
				if ( ! empty( $pdfprnt_options['use_default_css'] ) && 1 == $pdfprnt_options['use_default_css'] ) {
					/* remove 'font-family' and 'font' styles from theme css-file if additional fonts not loaded */
					if ( 0 == $pdfprnt_options['additional_fonts'] ) {
						$css = wp_remote_get( get_bloginfo( 'stylesheet_url' ) );
						if ( is_array( $css ) && ! empty( $css['body'] ) ) {
							$html .= '<style type="text/css">' . preg_replace( "/(font:(.*?);)|(font-family(.*?);)/", "", $css['body'] ) . '</style>';
						}
					} else {
						$html .= '<link type="text/css" rel="stylesheet" href="' . get_bloginfo( 'stylesheet_url' ) . '" media="all" />';
					}
				} else {
					$html .= '<link type="text/css" rel="stylesheet" href="' . plugins_url( 'css/default.css', __FILE__ ) . '" media="all" />';
				}
				$html .= mycontenthero_pdfprnt_additional_styles( $is_print );
				if ( 1 == $pdfprnt_options['use_custom_css'] && ! empty( $pdfprnt_options['custom_css_code'] ) ) {
					$html .= '<style type="text/css">' . $pdfprnt_options['custom_css_code'] . '</style>';
				}
				if ( $is_print && 1 == $pdfprnt_options['show_print_window'] ) {
					$html .= '<script>window.onload = function(){ window.print(); };</script>';
				}
			$html .=
			'</head>
				<body class="' . ( $is_print ? 'pdfprnt_print ' : '' ) . $wp_locale->text_direction . '">';
				/* Remove inline 'font-family' and 'font' styles from content */
				if ( 0 == $pdfprnt_options['additional_fonts'] ) {
					$content = mycontenthero_pdfprnt_preg_replace( array( "font-family", "font:" ), $content );
				}
				$html .= $content .
			'</body>
		</html>';
		return $html;
	}


	function mycontenthero_pdfprnt_additional_styles( $is_print ) {
		$styles = apply_filters( 'bwsplgns_add_pdf_print_styles', array() );
		$html = '';
		if ( ! empty( $styles ) && is_array( $styles ) ) {
			$url = get_bloginfo( 'url' );
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			$path = get_home_path();
			foreach ( $styles as $style ) {
				if ( ! empty( $style[0] ) && file_exists( $path . $style[0] ) ) {
					/* if "get print" */
					if ( $is_print ) {
						if( ( isset( $style[1] ) && 'print' == $style[1] ) || ! isset( $style[1] ) ) {
							$html .= '<link type="text/css" rel="stylesheet" href="' . $url . '/' . $style[0] . '" media="all" />';
						}
					/* if "get pdf" */
					} else {
						if ( ( isset( $style[1] ) && 'pdf' == $style[1] ) || ! isset( $style[1] ) ) {
							$html .= '<link type="text/css" rel="stylesheet" href="' . $url . '/' . $style[0] . '" media="all" />';
						}
					}
				}
			}
		}
		return $html;
	}

	function mycontenthero_pdfprnt_preg_replace( $patterns, $content ) {
		foreach( $patterns as $pattern ) {
			$content = preg_replace( "/" . $pattern . "(.*?);/", "", $content );
			preg_match_all( "~style=(\"\'?)~", $content, $quotes );/* get array with quotes */
			if ( isset( $quotes[1] ) && ! empty( $quotes[1] ) ) {
				foreach ( $quotes[1] as $quote ) {
					preg_match_all( "~style=" . $quote . "(.*?)" . $quote . "~", $content, $styles );
					if ( ! empty( $styles[1] ) ) {
						foreach ( $styles[1] as $style ) {
							if ( preg_match( "/" . $pattern . "/", $style ) ) {
								$content = preg_replace( "/" . $style . "/", "", $content );
							}
						}

					}
				}
			}
		}
		return $content;
	}
	
	function mypdf_string_replace_link($string,$link,$text){
		$aWords = explode(' ',$string);
		$wdata  = array();
		$wcount = count($aWords);

		$rand_5 = round($wcount-8);
		$rand_6 = round($wcount/2);

		/* $word_1 = $aWords[$rand_1];
		$word_2 = $aWords[$rand_2];
		$word_3 = $aWords[$rand_3];
		$word_4 = $aWords[$rand_4]; */
		
		$word_51 = $aWords[$rand_5];
		$word_52 = $aWords[$rand_5+1];
		$word_5  = $word_51.' '.$word_52.' '.$aWords[$rand_5+2].' '.$aWords[$rand_5+3].' '.$aWords[$rand_5+4];
		
		$word_61 = $aWords[$rand_6];
		$word_62 = $aWords[$rand_6+1];
		$word_6  = $word_61.' '.$word_62.' '.$aWords[$rand_6+2].' '.$aWords[$rand_6+3].' '.$aWords[$rand_6+4];

		/* $string = str_replace($word_1,"<a href='".$link."'>".$word_1."</a>",$string,strlen($word_1));
		$string = str_replace($word_2,"<a href='".$link."'>".$word_2."</a>",$string,strlen($word_2));
		$string = str_replace($word_3,"<a href='".$link."'>".$word_3."</a>",$string,strlen($word_3));
		$string = str_replace($word_4,"<a href='".$link."'>".$word_4."</a>",$string,strlen($word_4));*/
		
		//$string = str_replace($word_5,'<a href="'.$link.'">['.$word_5.']</a>',$string);
		$string = str_replace($word_6,$word_6.' '.$text,$string);
		$string = str_replace($text,'<a href="'.$link.'">'.$text.'</a>',$string);

		//echo"<pre>";print_r($string);echo"</pre>";	
        return $string; 		
	} 
	
add_action( 'wp_ajax_nopriv_ch_spin_post_result', 'myajax_wpch_spin_post_result' );
add_action('wp_ajax_ch_spin_post_result', 'myajax_wpch_spin_post_result');
function myajax_wpch_spin_post_result ()
{
	global $user_ID, $wpdb;
	$postContent = $_POST['ch_spin_msg'];
	$query = $wpdb->prepare(
		'SELECT ID FROM ' . $wpdb->posts . ' WHERE post_content = %s',
		$postContent
	);
	$wpdb->query( $query );
	if ( $wpdb->num_rows ) 
	{
	?>
		<div class="wrap">
			<div class="error"><p>Post is alreday created</p></div>
		</div>
	<?php
	} 
	else 
	{
		$spin_my_post_insert = array(
						  'post_title'    => '',
						  'post_content'  => $postContent,
						  'post_status'   => 'publish',
						  'post_author'   => 1,
						  'post_category' => array( 8,39 )
						);
						 
						// Insert the post into the database
		$spin_post_insert = wp_insert_post( $spin_my_post_insert );
	
		if($spin_post_insert)
		{
			?><script>window.open("<?php echo admin_url('post.php?post='.$spin_post_insert.'&action=edit'); ?>");</script><?php
		}
	}
	?>
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 5000); // <-- time in milliseconds
	});
	</script>	
	<?php
	exit;
}

add_action( 'wp_ajax_nopriv_wpmy_channels_result', 'myajax_wpmy_channels_result' );
add_action('wp_ajax_wpmy_channels_result', 'myajax_wpmy_channels_result');

function myajax_wpmy_channels_result()
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';

	$channel_select_result = $_POST['ajax_channel_select_result'];
	
	if(!empty($_POST['ajax_select_ezine_category_id']))
	{
		$channel_ezine_category = $_POST['ajax_select_ezine_category_id'];
	}
	else
	{
		$channel_ezine_category = '';
	}
	if(!empty($_POST['ajax_select_ezine_subcategory_id']))
	{
		$channel_ezine_subcategory = $_POST['ajax_select_ezine_subcategory_id'];
	}
	else
	{
		$channel_ezine_subcategory = '';
	}
	
	$channel_query_id= $_POST['ajax_channel_query_id'];		

	$result_article_forge_enable = get_option('wpch_articleforge_enable');
	
	if(!empty($result_article_forge_enable))
	{
		$result_article_forge_enables = $result_article_forge_enable;
	}
	else
	{
		$result_article_forge_enables = '';
	}
	
	$channel_api_class = new channelapi();
	$channel_api_list = $channel_api_class->channel_list($channel_query_id);

	//$af_ref_id = $channel_api_class->article_forge_ref_id($channel_query_id);
	
	$af_ref_id = '';
	
	?>    
	<table id="example_channel" class="display" style="width:100%">
		<thead>
			<tr>
				<th>Image</th>
				<th>Title</th>
				<th>Description</th>
				<th>Actions</th>
			</tr>
		</thead>
		<tbody>
		<?php	
		if(!empty($channel_api_list)) 
		{	
			foreach($channel_api_list as $channel_api_list1)
			{
				//echo "<pre>";
				//print_r($channel_api_list1['channel-detail']);
				//echo "</pre>";
				if(!empty($channel_api_list1['channel-detail'])) 
				{
				$metas = $wpdb->get_results("SELECT * FROM wp_postmeta WHERE meta_value LIKE '".$channel_api_list1['channel-detail']['channel_id'] ."' AND meta_key LIKE 'mych_channels_id'");
				?>
					<tr id="mych_box_ytube_<?php if(!empty($channel_api_list1['channel-detail']['channel_id'])) { echo $channel_api_list1['channel-detail']['channel_id']; } ?>">
						<td><img alt="img-dasboard" src="<?php if(!empty($channel_api_list1['channel-detail']['thum_img_url'])) { echo $channel_api_list1['channel-detail']['thum_img_url']; } ?>" class="rounded border" width="50" height="50"></td>
						<td><span style="color:firebrick;"><?php if(!empty($channel_api_list1['channel-detail']['title'])) { echo $channel_api_list1['channel-detail']['title']; } ?></span></td>
						<td><?php if(!empty($channel_api_list1['channel-detail']['title'])) { echo $channel_api_list1['channel-detail']['desc']; } ?></td>
						<?php $view_channel_path = get_admin_url().'edit.php?post_type=mych-ytube-channels'; if(!empty($metas)) { ?>
						<td><a href="<?php echo $view_channel_path; ?>" class="button-primary alignright" target="_blank">View</a></td>
						<?php } else { ?>
						<td>
						<div style="display:grid;" id="auto_post_div">
							<input type="button" name="channel_result_name1" id="channel_result_id1" style="margin-top:15px;margin-bottom:10px;" data-enableaf="<?php echo $result_article_forge_enables; ?>" data-categ="<?php echo $channel_ezine_category; ?>" data-subcateg="<?php echo $channel_ezine_subcategory; ?>" data-aftitle="<?php if(!empty($af_ref_id)) { echo $af_ref_id; }?>" data-yid="<?php if(!empty($channel_api_list1['channel-detail']['channel_id'])) { echo $channel_api_list1['channel-detail']['channel_id']; } ?>" class="button-primary alignright" value="Save Youtube Channel" />
							<div style="padding-left:4px;">
								<p>
									<input type="hidden" id="channel_id_hidden" value="<?php if(!empty($channel_ezine_category)) { echo $channel_api_list1['channel-detail']['channel_id'] .'~'.$channel_ezine_category; } else { echo $channel_api_list1['channel-detail']['channel_id']; } ?>"/>
									<input type=checkbox name=channel_auto_post_name class=channel_auto_post_class value="<?php if(!empty($channel_ezine_category)) { echo $channel_api_list1['channel-detail']['channel_id'] .'~'.$channel_ezine_category.'~on'; } else { echo $channel_api_list1['channel-detail']['channel_id']; } ?>"/>&nbsp;<span>Autosync new videos</span>
									<select id="afytubechannel_select_cat_id" name="afytubechannel_select_cat" style="margin-top:10px;">
									<?php
									$tax_terms = get_terms('category', array('hide_empty' => false,'orderby'=>'term_id','order'=>'ASC'));
									foreach ($tax_terms as $term)
									{
									   echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
									}								
									?>
									</select>
								</p>
							</div>							
						</div>
						<a id="view_channel_btn" href="<?php echo $view_channel_path; ?>" class="button-primary alignright" target="_blank" style="display:none;">View</a></td>		
						<?php } ?>
					</tr>	
				<?php 
				}
			}
		} 
		?>
		</tbody>
	</table>        
	<script>
		jQuery(document).ready(function($) {
			$('#example_channel').DataTable();
		} );		
	</script>
	<?php    
	exit;
}	

add_action( 'wp_ajax_nopriv_wpmy_channels_detail', 'myajax_wpmy_channels_detail' );
add_action('wp_ajax_wpmy_channels_detail', 'myajax_wpmy_channels_detail');

function myajax_wpmy_channels_detail()
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);	
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';
	$channel_detail_api_class = new channelapi();
	
	$mych_ref_id = $_POST['ajax_channel_query_result'];
	
	$mych_array_check_val = $_POST['ajax_mych_array_check_val'];
	$afytubechannel_select_cat_result = $_POST['ajax_afytubechannel_select_result'];
	
	$mych_channel_query_result_categ = $_POST['ajax_channel_query_result_categ'];
	$mych_channel_query_result_subcateg = $_POST['ajax_channel_query_result_subcateg'];
	
	if(!empty($afytubechannel_select_cat_result))
	{
		$afytubechannel_category = $afytubechannel_select_cat_result;
	}
	else
	{
		$afytubechannel_category = '';
	}
	if(!empty($mych_channel_query_result_subcateg))
	{
		$afezine_subcategory = $mych_channel_query_result_subcateg;
	}
	else
	{
		$afezine_subcategory = '';
	}
	
	$mych_check_val = str_replace( ',', ' ', $mych_array_check_val );	
    $mych_check_split_string=explode(" ",$mych_check_val);
		
	foreach($mych_check_split_string as $mych_check_split_string1)
	{
		$mych_check_val1 = str_replace( '~', ' ', $mych_check_split_string1 );	
		$mych_check_split_string11=explode(" ",$mych_check_val1);
		
		$channel_api_detail = $channel_detail_api_class->channel_detail($mych_check_split_string11[0]);
		
		$channel_id = $channel_api_detail[0]['channel-detail']['channel_id'];	
		$channel_title = $channel_api_detail[0]['channel-detail']['title'];	
		$channel_desc = $channel_api_detail[0]['channel-detail']['desc'];	
		$channel_img = $channel_api_detail[0]['channel-detail']['thum_img_url'];	
		
		// Create post object
		$my_post = array(
		  'post_title'    => wp_strip_all_tags( $channel_title),
		  'post_excerpt'  => $channel_desc,
		  'post_status'   => 'publish',
		  'post_type' => 'mych-ytube-channels',
		  'post_author'   => 1
		);
		 
		// Insert the post into the database
		$ids = wp_insert_post( $my_post );
		
		$image_url        = $channel_img; // 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 );
				
		update_post_meta( $ids, 'mych_channels_id', $channel_id, true );
		if(!empty($mych_check_split_string11[1]))
		{
			update_post_meta( $ids, 'mych_channels_catid', $mych_check_split_string11[1], true );		
		}
		else
		{
			update_post_meta( $ids, 'mych_channels_catid', '', true );		
		}
		if(!empty($mych_check_split_string11[2]))
		{
			update_post_meta( $ids, 'mych_channels_autopost', $mych_check_split_string11[2], true );				
		}
		else
		{
			update_post_meta( $ids, 'mych_channels_autopost', 'off', true );		
			$mych_datetime_autopost = date("Y-m-d")."T".date("h:i:s")."Z";			
			update_post_meta( $ids, 'mych_channels_datetime', $mych_datetime_autopost, true );		
		}
		
		if(!empty($mych_ref_id))
		{
			update_post_meta( $ids, 'mych_article_forge_id', $mych_ref_id, true );
		}
		else
		{
			update_post_meta( $ids, 'mych_article_forge_id', '', true );
		}
		
		if(!empty($afezine_subcategory))
		{
			update_post_meta( $ids, 'mych_ezine_subcategory_name', $afezine_subcategory, true );
		}
		else
		{
			update_post_meta( $ids, 'mych_ezine_subcategory_name', '', true );
		}
		
		update_post_meta( $ids, 'mych_post_cat_id', $afytubechannel_category, true );
	}	
	?>
	<div class="wrap">
		<div class="updated"><p>Channel is created</p></div>
	</div>
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 5000); // <-- time in milliseconds
	});
	</script>	
	<?php
	exit;
}

function mycp_register_meta_boxes_channels_categ() 
{	
	add_meta_box( 'mycp-channel-categ', __( 'Categories', 'mycp_channels_categ' ), 'mycp_display_channels_categ_callback', 'mych-ytube-channels' , 'side', 'high');
}
add_action( 'add_meta_boxes', 'mycp_register_meta_boxes_channels_categ' );

/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function mycp_display_channels_categ_callback( $post ) 
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';
	
	$postmeta_channel_categ = get_post_meta( $post->ID, 'mych_post_cat_id', true );	
	
	?>	
	<form>
		<div style="display:inline-block;width:100%;">
			<label for="staticEmail" class="col-sm-2 col-form-label" style="font-size:14px;padding:0">Select Category:</label><br/>
			<select id="afytubechannel_select_categ_id" name="afytubechannel_select_categ_name" style="margin-top:10px;width:100%;">
			<?php
			$tax_terms = get_terms('category', array('hide_empty' => false,'orderby'=>'term_id','order'=>'ASC'));
			foreach ($tax_terms as $term)
			{
				?>
				<option value="<?php echo $term->term_id; ?>" <?php if($term->term_id == $postmeta_channel_categ) { echo "selected"; } ?> ><?php echo $term->name; ?></option>
				<?php
			}								
			?>
			</select>
			<br/>
			<input type="button" name="channel_categ_name" id="channel_categ_id" data-id="<?php echo $post->ID; ?>" style="margin-top:15px;margin-bottom:10px;" class="button-primary" value="Save" />
		</div>			
	</form>	
	<script>
		jQuery(document).ready(function($){
			$(document).on('click', '#channel_categ_id', function() {
				var channel_post_id1 = $(this).data('id');
				var channel_categ_id1 = $("#afytubechannel_select_categ_id").val();
				
				var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
				jQuery.ajax({
					url:  ajaxurl,
					type: "POST",
					data: {
						action:'channel_video_categ_post',
						ajax_channel_post_id:channel_post_id1,
						ajax_channel_categ_id : channel_categ_id1,
					},
					beforeSend: function(){
						$("#channel_categ_id").prop("value", 'Saving...');
					},
					success: function (response) {
						$("#channel_categ_id").prop("value", 'Saved');
						setTimeout(function() 
						{
							$("#channel_categ_id").prop("value", 'Save');
						}, 4000);
					}
				});	
				return false;		
			});
		});
	</script>
	<?php
}


add_action( 'wp_ajax_nopriv_channel_video_categ_post', 'myajax_channel_video_categ_post' );
add_action('wp_ajax_channel_video_categ_post', 'myajax_channel_video_categ_post');

function myajax_channel_video_categ_post()
{
	global $wpdb;
	
	$channel_post_id = $_POST['ajax_channel_post_id'];
	$channel_categ_id = $_POST['ajax_channel_categ_id'];
	
	update_post_meta( $channel_post_id, 'mych_post_cat_id', $channel_categ_id);
	
	exit;
}
function mycp_register_meta_boxes_channels_autopost() 
{	
	add_meta_box( 'mycp-channel-autopost', __( 'Auto Sync', 'mycp_channels_autopost' ), 'mycp_display_channels_autopost_callback', 'mych-ytube-channels' , 'side', 'high');
}
add_action( 'add_meta_boxes', 'mycp_register_meta_boxes_channels_autopost' );

/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function mycp_display_channels_autopost_callback( $post ) 
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';
	
	$postmeta_channel_autopost = get_post_meta( $post->ID, 'mych_channels_autopost' , true);
	$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	?>	
	<form>
		<div style="display:inline-block;width:100%;">
			<label for="staticEmail" class="col-sm-2 col-form-label" style="font-size:14px;padding:0">AutoSync Video</label><br/>
			<select id="afytubechannel_select_autopost_id" name="afytubechannel_select_autopost_name" style="margin-top:10px;width:100%;">
				<option value="on" <?php if($postmeta_channel_autopost == 'on') { echo "selected"; } ?> >On</option>
				<option value="off" <?php if($postmeta_channel_autopost == 'off') { echo "selected"; } ?> >Off</option>
			</select>
			<br/>
			<input type="button" name="channel_autopost_name" id="channel_autopost_id" data-id="<?php echo $post->ID; ?>" style="margin-top:15px;margin-bottom:10px;" class="button-primary" value="Save" />
			
		</div>			
	</form>	
	<script>
		jQuery(document).ready(function($){
			$(document).on('click', '#channel_autopost_id', function() {
				var channel_post_id1 = $(this).data('id');
				var channel_autopost_id1 = $("#afytubechannel_select_autopost_id").val();
				
				var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
				jQuery.ajax({
					url:  ajaxurl,
					type: "POST",
					data: {
						action:'channel_video_autopost',
						ajax_channel_post_id:channel_post_id1,
						ajax_channel_autopost_id1 : channel_autopost_id1,
					},
					beforeSend: function(){
						$("#channel_autopost_id").prop("value", 'Saving...');
					},
					success: function (response) {
						$("#channel_autopost_id").prop("value", 'Saved');
						setTimeout(function() 
						{
							$("#channel_autopost_id").prop("value", 'Save');
						}, 4000);
					}
				});	
				return false;		
			});
		});
	</script>
	<?php
}


add_action( 'wp_ajax_nopriv_channel_video_autopost', 'myajax_channel_video_autopost' );
add_action('wp_ajax_channel_video_autopost', 'myajax_channel_video_autopost');

function myajax_channel_video_autopost()
{
	global $wpdb;
	
	$channel_post_id = $_POST['ajax_channel_post_id'];
	$channel_autopost_id1 = $_POST['ajax_channel_autopost_id1'];
	
	update_post_meta( $channel_post_id, 'mych_channels_autopost', $channel_autopost_id1);
	
	if($channel_autopost_id1 == 'on')
	{
		delete_post_meta($channel_post_id, 'mych_channels_datetime');
	}
	elseif($channel_autopost_id1 == 'off')
	{
		$mych_datetime_autopost = date("Y-m-d")."T".date("h:i:s")."Z";			
		update_post_meta( $channel_post_id, 'mych_channels_datetime', $mych_datetime_autopost);		
	}
		
	exit;
}
function mycp_register_meta_boxes_channels() 
{	
	add_meta_box( 'mycp-channel', __( 'Videos', 'mycp_channels' ), 'mycp_display_channels_callback', 'mych-ytube-channels' , 'normal', 'high');
}
add_action( 'add_meta_boxes', 'mycp_register_meta_boxes_channels' );

/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function mycp_display_channels_callback( $post ) 
{
	global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';
	
	$postmeta_channel_id = get_post_meta( $post->ID, 'mych_channels_id', true );	
	$postmeta_autopost_date1 = get_post_meta( $post->ID, 'mych_channels_datetime', true );	
	$postmeta_autopost1 = get_post_meta( $post->ID, 'mych_channels_autopost', true );	
	
	if(!empty($postmeta_autopost1) && $postmeta_autopost1 == 'off') 
	{
		if(!empty($postmeta_autopost_date1))
		{
			$postmeta_autopost = $postmeta_autopost_date1;
		}
	}
	elseif($postmeta_autopost1 == 'on')
	{
		$postmeta_autopost = '1';
	}	
	$channel_detail_api_class = new channelapi();

	$channel_api_list = array();
	$channel_videos_pagetoken = $channel_detail_api_class->youtube_search($postmeta_channel_id, $next_page_token='');
	$channel_videos_pagetoken1 = $channel_detail_api_class->youtube_search1($postmeta_channel_id, $channel_videos_pagetoken);
	$channel_videos_pagetoken2 = $channel_detail_api_class->youtube_search2($postmeta_channel_id, $channel_videos_pagetoken1);
	$channel_videos_pagestoken = array($channel_videos_pagetoken,$channel_videos_pagetoken1,$channel_videos_pagetoken2);
	
	foreach($channel_videos_pagestoken as $channel_videos_pagestoken1)
	{	
		if(!empty($channel_videos_pagestoken1))
		{
			$channel_api_list = array_merge($channel_api_list,$channel_detail_api_class->channel_video_list($postmeta_channel_id,$channel_videos_pagestoken1));
		}
	}

	$channel_videos_pagestoken1s = '';
	if(!empty($channel_api_list))
	{
		$channel_api_detail = array_merge($channel_detail_api_class->channel_video_list($postmeta_channel_id,$channel_videos_pagestoken1s),$channel_api_list);
	}
	else
	{
		$channel_api_detail = '';
	}
	
	//$channel_api_detail = $channel_detail_api_class->channel_video_list($postmeta_channel_id);

	?>    
	<div class="wrap"><div class="alert-warning" style="background:#ffba006b;"><p style="padding:5px 10px;">Note :- Video will be added automatically to the post. It will take some minutes for article forge to complete the request. </p></div></div>
	<?php		
	$af_post_table = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_afarticles WHERE channel_post_id = '".$post->ID."' AND status = 2");	    
	if(!empty($af_post_table))
	{
		echo "<div class=wrap><div class=alert-warning style=background:#f16666;color:#fff;font-weight:500;><p style=padding:5px 10px;>Note :- Unfortunately, There is any issue with article forge api. So Following ";
		echo count($af_post_table);
		echo " posts are not created. After 24hours it will try again. </p></div></div>";
	}
	?>
	<table id="example_channel_video" class="display" style="width:100%">
		<thead>
			<tr>
				<th>Image</th>
				<th>Title</th>
				<th>Description</th>
				<th>Actions</th>
			</tr>
		</thead>
		<tbody>
		<?php	
		if(!empty($channel_api_detail)) 
		{	
			foreach($channel_api_detail as $channel_api_detail1)
			{
				if(!empty($channel_api_detail1['channel-detail'])) 
				{
				$post_vid_id = $channel_api_detail1['channel-detail']['vid_id'];
				
				$channel_post_meta_key_id = "mych_channels_video_post_id_".$post_vid_id;
				
				$channel_post_meta_value = get_post_meta( $post->ID, $channel_post_meta_key_id , true );				
				$postmeta_channel_video_id = get_post_meta( $channel_post_meta_value, 'mych_channels_video_id' , true );
				if(!empty($channel_api_detail1['channel-detail']['vid_id'])) {
					$vid_published_time = $channel_api_detail1['channel-detail']['published_time'];
					if($postmeta_autopost1 == 'off') { if($vid_published_time < $postmeta_autopost) {
				?>
					<tr class="channel_cls_<?php if(!empty($channel_api_detail1['channel-detail']['vid_id'])) { echo $channel_api_detail1['channel-detail']['vid_id']; } ?>">
						<td><img alt="img-dasboard" src="<?php if(!empty($channel_api_detail1['channel-detail']['thum_img_url'])) { echo $channel_api_detail1['channel-detail']['thum_img_url']; } ?>" class="rounded border" width="50" height="50"></td>
						<td><span style="color:firebrick;"><?php if(!empty($channel_api_detail1['channel-detail']['title'])) { echo $channel_api_detail1['channel-detail']['title']; } ?></span></td>
						<td><?php if(!empty($channel_api_detail1['channel-detail']['desc'])) { echo $channel_api_detail1['channel-detail']['desc']; } ?></td>
						<td>
						<?php 
						
						$af_select_post_table_cron = $wpdb->base_prefix . "mych_afarticles";
						$af_table_result_detail_new = $wpdb->get_results("select * from ".$af_select_post_table_cron." where vid_id = '".$channel_api_detail1['channel-detail']['vid_id']."'");										
						
						if($postmeta_channel_video_id == $channel_api_detail1['channel-detail']['vid_id']) { ?>
						<a href="<?php echo get_permalink($channel_post_meta_value); ?>" target="_blank" class="button-primary alignright">View</a></td>							
						<?php }
						elseif(!empty($af_table_result_detail_new))
						{
						?>
						<p class="button-primary alignright" style="cursor:context-menu;">Saved</p>
						<?php
						}							
						else { ?>
						<div class="response_post">
							<input type="button" name="channel_result_name" data-postid="<?php if(!empty($post->ID)) { echo $post->ID; } ?>" data-id="<?php if(!empty($channel_api_detail1['channel-detail']['vid_id'])) { echo $channel_api_detail1['channel-detail']['vid_id']; } ?>" id="channel_result_id" class="button-primary alignright" value="Post Video" />							
						</div>
						<?php }?>		
						</td>
					</tr>			
				<?php 
					} } elseif($postmeta_autopost1 == 'on') { ?>
					<tr class="channel_cls_<?php if(!empty($channel_api_detail1['channel-detail']['vid_id'])) { echo $channel_api_detail1['channel-detail']['vid_id']; } ?>">
						<td><img alt="img-dasboard" src="<?php if(!empty($channel_api_detail1['channel-detail']['thum_img_url'])) { echo $channel_api_detail1['channel-detail']['thum_img_url']; } ?>" class="rounded border" width="50" height="50"></td>
						<td><span style="color:firebrick;"><?php if(!empty($channel_api_detail1['channel-detail']['title'])) { echo $channel_api_detail1['channel-detail']['title']; } ?></span></td>
						<td><?php if(!empty($channel_api_detail1['channel-detail']['desc'])) { echo $channel_api_detail1['channel-detail']['desc']; } ?></td>
						<td>
						<?php 
						$af_select_post_table_cron = $wpdb->base_prefix . "mych_afarticles";
						$af_table_result_detail_new = $wpdb->get_results("select * from ".$af_select_post_table_cron." where vid_id = '".$channel_api_detail1['channel-detail']['vid_id']."'");										
						if($postmeta_channel_video_id == $channel_api_detail1['channel-detail']['vid_id']) { ?>
						<a href="<?php echo get_permalink($channel_post_meta_value); ?>" target="_blank" class="button-primary alignright">View</a></td>							
						<?php } 
						elseif(!empty($af_table_result_detail_new))
						{
						?>
						<p class="button-primary alignright" style="cursor:context-menu;">Saved</p>
						<?php
						}													
						else { ?>
						<div class="response_post">
							<input type="button" name="channel_result_name" data-postid="<?php if(!empty($post->ID)) { echo $post->ID; } ?>" data-id="<?php if(!empty($channel_api_detail1['channel-detail']['vid_id'])) { echo $channel_api_detail1['channel-detail']['vid_id']; } ?>" id="channel_result_id" class="button-primary alignright" value="Post Video" />							
						</div>
						<?php }?>		
						</td>
					</tr>									
					<?php }
				} }
			}
		} 
		?>
		</tbody>
	</table>        
	<script>
		jQuery(document).ready(function($) {
			$('#example_channel_video').DataTable();
		} );
		
		jQuery(document).ready(function($){
			$(document).on('click', '#channel_result_id', function() {
				var channel_video_id = $(this).data('id');
				var channel_post_id = $(this).data('postid');
				
				var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
				jQuery.ajax({
					url:  ajaxurl,
					type: "POST",
					data: {
						action:'channel_video_post',
						ajax_channel_video_id:channel_video_id,
						ajax_channel_post_id : channel_post_id,
					},
					beforeSend: function(){
						$(".channel_cls_"+channel_video_id+" #channel_result_id").prop("value", 'Posting...');
					},
					success: function (response) {
						$(".channel_cls_"+channel_video_id+" #channel_result_id").prop("value", 'Posted...');
						//$(".channel_cls_"+channel_video_id+" #channel_result_id").attr("disabled", true);
						$(".channel_cls_"+channel_video_id+" #channel_result_id"). css("display", "none");;
						$(".channel_cls_"+channel_video_id+" .response_post"). html(response);
					}
				});	
				return false;		
			});
		});
	</script>
	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"> 
	<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
	<?php
}

function ab_curl_post($url, $data, &$info){

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ab_curl_postData($data));
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_REFERER, $url);
  $html = trim(curl_exec($ch));
  curl_close($ch);

  return $html;
}

function ab_curl_postData($data){

  $fdata = "";
  foreach($data as $key => $val){
    $fdata .= "$key=" . urlencode($val) . "&";
  }

  return $fdata;

}


add_action( 'wp_ajax_nopriv_channel_video_post', 'myajax_channel_video_post' );
add_action('wp_ajax_channel_video_post', 'myajax_channel_video_post');

function myajax_channel_video_post()
{
	global $wpdb;
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';

	$channel_video_id = $_POST['ajax_channel_video_id'];		
	$channel_post_id = $_POST['ajax_channel_post_id'];	
	
	$postmeta_cat_id = get_post_meta( $channel_post_id, 'mych_channels_catid', true );			
	$postmeta_article_forge_id = get_post_meta( $channel_post_id, 'mych_article_forge_id', true );		
	$postmeta_ytubechannel_cat_id = get_post_meta( $channel_post_id, 'mych_post_cat_id', true );			
	$postmeta_ytubechannel_subcat_id = get_post_meta( $channel_post_id, 'mych_ezine_subcategory_name', true );			
	
	if(!empty($postmeta_ytubechannel_cat_id))
	{
		 $ytubechannel_post_catid = $postmeta_ytubechannel_cat_id;
	}
	else
	{
		$ytubechannel_post_catid = '';
	}
	
	if(!empty($postmeta_ytubechannel_subcat_id))
	{
		 $ytubechannel_post_subcatid = $postmeta_ytubechannel_subcat_id;
	}
	else
	{
		$ytubechannel_post_subcatid = '';
	}
	/*
	$channel_detail_api_class1 = new channelapi();	
	$article_forge_final_result = $channel_detail_api_class1->article_forge_result($postmeta_article_forge_id);
	
	if(!empty($article_forge_final_result))
	{
		$article_forge_final_result1 = $article_forge_final_result;
	}
	else
	{
		$article_forge_final_result1 = '';
	}
	*/
	
	$article_forge_final_result1 = '';
	
	$api_key='6JpqLclM4Ht5rvLCkpQYEJBr3TsEoe';
	
	$result_ezine_article_limitss = get_option('wpch_articleezine_limit');
	
	if(!empty($result_ezine_article_limitss))
	{
		$result_ezine_article_limits = $result_ezine_article_limitss;
	}
	else
	{
		$result_ezine_article_limits = '1';
	}

	$result_article_ezine_enables = get_option('wpch_articleezine_enable');

	if(!empty($result_article_ezine_enables) && $result_article_ezine_enables == 'on')
	{
		if(isset($postmeta_cat_id) && !empty($postmeta_cat_id))
		{
			$ez_update_table = $wpdb->base_prefix."mych_ezarticles";

			$ez_table_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_ezarticles WHERE cat = '".$postmeta_cat_id."' AND scat = '".$ytubechannel_post_subcatid."' AND used = 0 ORDER BY `id` ASC LIMIT 0, $result_ezine_article_limits");
					
			foreach($ez_table_result_detail as $ez_table_result_details)
			{
				$title = $ez_table_result_details->title;
				$summary = $ez_table_result_details->summary;						
				
				$ezine_article_contents .= "<h2 style=font-weight:normal;font-size:24px;margin-top:60px;margin-bottom:-15px;>".$title."</h2><br/>".$summary."<br/><br/>";			
				
				$wpdb->update( $ez_update_table,array('used'=>'1'),array('id'=> $ez_table_result_details->id));
			}

			$ezine_article_content = $ezine_article_contents;
			
			/*
			if(!empty($api_key))
			{
				$url='http://api.ezinearticles.com/api.php?search=articles&category='.$postmeta_cat_id.'&subcategory='.$ytubechannel_post_subcatid.'&response_format=json&key='.$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);
				$mych_ezine_article_result = json_decode($data);
				$rand_keys = array_rand($mych_ezine_article_result->articles, $result_ezine_article_limits);
			}
			
			foreach($rand_keys as $rand_keyss)
			{
				$title = $mych_ezine_article_result->articles[$rand_keyss]->article->title;
				$summary = $mych_ezine_article_result->articles[$rand_keyss]->article->summary;						
				
				$ezine_article_contents .= "<h2 style=font-weight:normal;font-size:24px;margin-top:60px;margin-bottom:-15px;>".$title."</h2><br/>".$summary."<br/><br/>";			
			}
			
			$ezine_article_content = $ezine_article_contents;
			*/
			
			/*
			$title1 = $mych_ezine_article_result->articles[$rand_keys[0]]->article->title;
			$summary1 = $mych_ezine_article_result->articles[$rand_keys[0]]->article->summary;
			$title2 = $mych_ezine_article_result->articles[$rand_keys[1]]->article->title;
			$summary2 = $mych_ezine_article_result->articles[$rand_keys[1]]->article->summary;
			$title3 = $mych_ezine_article_result->articles[$rand_keys[2]]->article->title;
			$summary3 = $mych_ezine_article_result->articles[$rand_keys[2]]->article->summary;
			$title4 = $mych_ezine_article_result->articles[$rand_keys[3]]->article->title;
			$summary4 = $mych_ezine_article_result->articles[$rand_keys[3]]->article->summary;
			$title5 = $mych_ezine_article_result->articles[$rand_keys[4]]->article->title;
			$summary5 = $mych_ezine_article_result->articles[$rand_keys[4]]->article->summary;
			
			$ezine_article_content = "<h2 style=font-weight:normal;font-size:24px;margin-top:60px;margin-bottom:-15px;>".$title1."</h2><br/>".$summary1."<br/><br/><h2 style=font-weight:normal;font-size:24px;margin-top:40px;margin-bottom:-15px;>".$title2."</h2><br/>".$summary2."<br/><br/><h2 style=font-weight:normal;font-size:24px;margin-top:40px;margin-bottom:-15px;>".$title3."</h2><br/>".$summary3."<br/><br/><h2 style=font-weight:normal;font-size:24px;margin-top:40px;margin-bottom:-15px;>".$title4."</h2><br/>".$summary4."<br/><br/><h2 style=font-weight:normal;font-size:24px;margin-top:40px;margin-bottom:-15px;>".$title5."</h2><br/>".$summary5."<br/><br/>";
			*/
			
		}
		else
		{
			$ezine_article_content = '';
		}	
	}
	else
	{
		$ezine_article_content = '';
	}	
	
	$mych_channel_ytube_apis = get_option('wpch_ytube_api_key');
	if(!empty($mych_channel_ytube_apis))
	{
		$mych_channel_ytube_api = $mych_channel_ytube_apis;
	}
	else
	{
		$mych_channel_ytube_api = 'AIzaSyCiomcpDbV8jBVu2YpOC8dcYpA_JFaqmrw';
	}

	$mych_channel_api_detail = 'https://www.googleapis.com/youtube/v3/videos?key='.$mych_channel_ytube_api.'&id='.$channel_video_id.'&part=snippet,id';
	
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $mych_channel_api_detail);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$mych_channel_response_detail = curl_exec($ch);

	curl_close($ch);
	$mych_channel_data_detail = json_decode($mych_channel_response_detail);			
	$mych_channel_response_details = json_decode(json_encode($mych_channel_data_detail), true);	

	foreach ($mych_channel_response_details['items'] as $mych_channel_key_resp1_detail) 
	{						
		if ($mych_channel_key_resp1_detail['kind'] == "youtube#video") 
		{
			$mych_channel_title_detail = stripslashes(str_replace('"','`',$mych_channel_key_resp1_detail['snippet']['title']));
								
			$mych_channel_desc_detail = str_replace('"','`',$mych_channel_key_resp1_detail['snippet']['description']);
			
			$mych_channel_img_detail = $mych_channel_key_resp1_detail['snippet']['thumbnails']['high']['url'];
			$mych_channel_link_arr_detail=array('title'=>$mych_channel_title_detail,'desc'=>$mych_channel_desc_detail,'thum_img_url'=>$mych_channel_img_detail);					
			$mych_channel_result_output_arr1_detail[] = array('channel-detail'=>$mych_channel_link_arr_detail);
		}
	}				

	$title = $mych_channel_result_output_arr1_detail[0]['channel-detail']['title'];
	
	$result_ytube_enable = get_option('wpch_ytube_enable');
	if(!empty($result_ytube_enable))
	{
		if($result_ytube_enable == 'on')
		{
			$description1 = $mych_channel_result_output_arr1_detail[0]['channel-detail']['desc'];
			$description = preg_replace('@(?<!href="|">)(https?:\/\/[\w\-\.!~?&=+\*\'(),\/]+)((?!\<\/\a\>).)*@i','<a href="$1">$1</a>',$description1);
		}
		elseif($result_ytube_enable == 'off')
		{
			$description = ''; 
		}
	}
	else
	{
		$description1 = $mych_channel_result_output_arr1_detail[0]['channel-detail']['desc'];
		$description = preg_replace('@(?<!href="|">)(https?:\/\/[\w\-\.!~?&=+\*\'(),\/]+)((?!\<\/\a\>).)*@i','<a href="$1">$1</a>',$description1);
	}	

	$result_articlebuilder_enable = get_option('wpch_articlebuilder_enable');
	if($result_articlebuilder_enable == 'on' && !empty($result_articlebuilder_enable))
	{	
		$ab_url = 'http://articlebuilder.net/api.php';
		$ab_username = get_option('wpch_articlebuilder_username');
		$ab_password = get_option('wpch_articlebuilder_passowrd');
		$ab_limit = get_option('wpch_articlebuilder_limit');
		$ab_category = get_option('wpch_articlebuilder_category');

		if(!empty($ab_limit))
		{
			$ab_limit1 = $ab_limit;
		}
		else
		{
			$ab_limit1 = '250';
		}

		if(!empty($ab_username) && !empty($ab_password) && !empty($ab_category))
		{
			$ab_username1 = $ab_username;
			$ab_password1 = $ab_password;
			$ab_category1 = $ab_category;

			$testmethod = 'buildArticle';

			# Build the data array for authenticating.

			$data = array();
			$data['action'] = 'authenticate';
			$data['format'] = 'php'; # You can also specify 'xml' as the format.

			# Change to your own username/password.

			$data['username'] = $ab_username1;
			$data['password'] = $ab_password1;

			# Authenticate and get back the session id.
			# You only need to authenticate once per session.
			# A session is good for 24 hours.
			$output = unserialize(ab_curl_post($ab_url, $data, $info));

			if($output['success']=='true'){
			  # Success.
			  $session = $output['session'];
		
			  # Build the data array for the example.
			  $data = array();
			  $data['session'] = $session;
			  $data['format'] = 'php'; # You can also specify 'xml' as the format.
			  $data['action'] = $testmethod;  
			  #$data['apikey'] = $apikey;
			  $data['category'] = $ab_category1;
			  
			  if($testmethod=='buildArticle'){
			    $data['subtopics'] = "";
			    $data['wordcount'] = $ab_limit1;
			  }

			  # Post to API and get back results.
			  $output = ab_curl_post($ab_url, $data, $info);
			  $output = unserialize($output);
			  

			  if($output['success']=='true')
			  {		  	
			  	$article_builder_desc = str_replace("\r", "<br>", str_replace("\n\n", "<p>", $output['output']));		    
			  }
			}
		}
		else
		{
			$article_builder_desc = '';				
		}

	}
	else
	{
		$article_builder_desc = '';
	}
	
	$image = $mych_channel_result_output_arr1_detail[0]['channel-detail']['thum_img_url'];
	
	$spin_vid_edit_link_option = "<iframe width=620 height=330 src=https://www.youtube.com/embed/$channel_video_id></iframe>";

	$title_video_post_table = wp_strip_all_tags( $title);
	$key_video_post_table = get_option('wpch_articleforge_setting_keyword');
	$subkey_video_post_table = get_option('wpch_articleforge_setting_sub_key');

	$description_video_post_table = $spin_vid_edit_link_option."<br/>".$description."<br/>".$ezine_article_content."<br/>".$article_builder_desc;

	$channel_af_enable1 = get_option('wpch_articleforge_enable');
	if(!empty($channel_af_enable1))
	{
		$channel_af_enable = $channel_af_enable1;
	}
	else
	{
		$channel_af_enable = 'off';
	}


	//$result_article_forge_enable1 = get_option('wpch_articleforge_enable');
	if(!empty($channel_af_enable1) && $channel_af_enable1 == 'on')
	{	
		$mych_af_table = $wpdb->base_prefix . "mych_afarticles";

		$data = serialize(array($ytubechannel_post_catid));
		
		$mych_af_data=array(
							'title' => wp_strip_all_tags($title_video_post_table), 
							'keyword' => wp_strip_all_tags($key_video_post_table),
							'subkey' => $subkey_video_post_table,
							'description' => $description_video_post_table, 
							'image' => $image, 
							'category' => $data, 
							'vid_id' => $channel_video_id, 
							'channel_post_id' => $channel_post_id, 
							'af_enable' => $channel_af_enable, 
							'schedule_date' => date('Y-m-d H:i:s'), 
							'status' => 0,
						   );

		$wpdb->insert( $mych_af_table, $mych_af_data); 
		?>
		<p class="button-primary alignright" style="cursor:context-menu;">Saved</p>
		<?php
	}
	elseif($channel_af_enable1 == 'off')
	{
		$af_desc = str_replace('<a', '<a target="_blank"', $description);
			
		// Create post object
		$my_post = array(
		  'post_title'    => wp_strip_all_tags($title_video_post_table),
		  'keyword' => wp_strip_all_tags($key_video_post_table),
		  'subkey' => $subkey_video_post_table,
		  'post_content'  => $spin_vid_edit_link_option."<br/>".$af_desc."<br/>".$ezine_article_content."<br/>".$article_builder_desc,
		  'post_category' => array($ytubechannel_post_catid),
		  'post_status'   => 'publish'	  
		);
		 
		// Insert the post into the database
		$ids = wp_insert_post( $my_post );

		if(!empty($article_forge_final_result))
		{
			$article_forge_final_result_id = '';
			update_post_meta( $ids, 'mych_channels_forge_status', '0', true );
		}
		else
		{
			update_post_meta( $ids, 'mych_channels_forge_id', $postmeta_article_forge_id, true );
			update_post_meta( $ids, 'mych_channels_forge_status', '1', true );
		}
		
		if(!empty($image))
		{
			$image_url        = $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 );		
		}
		
			
		$channel_post_meta_key_id = "mych_channels_video_post_id_".$channel_video_id;
		
		delete_post_meta_by_key($channel_post_meta_key_id);
		update_post_meta( $ids, 'mych_channels_video_id', $channel_video_id, true );
		update_post_meta( $channel_post_id, $channel_post_meta_key_id, $ids, true );
		?>	
		<a href="<?php echo get_permalink($ids); ?>" target="_blank" id="btn_view" class="button-primary alignright">View</a>	
		<?php
	}
	exit;
}

add_filter( 'admin_url', 'wpse_271288_change_add_new_link_for_post_type', 10, 2 );
function wpse_271288_change_add_new_link_for_post_type( $url, $path ){
    if( $path === 'post-new.php?post_type=mych-ytube-channels' ) 
	{
		$url = 	get_admin_url().'admin.php?page=wpmy_add_channels';
    }
    return $url;
}

add_action( 'wp_ajax_nopriv_wpmy_article_forge_post_result', 'myajax_wpmy_article_forge_post_result' );
add_action('wp_ajax_wpmy_article_forge_post_result', 'myajax_wpmy_article_forge_post_result');

function myajax_wpmy_article_forge_post_result()
{
	global $wpdb;
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';
	
	$channel_detail_api_class1 = new channelapi();	
	
	$article_forge_heading = $_POST['ajax_article_forge_heading'];
	$article_forge_keyword = $_POST['ajax_article_forge_keyword'];
	$article_forge_subkeyword = $_POST['ajax_article_forge_subkeyword'];
	$article_forge_stitle = $_POST['ajax_article_forge_stitle'];
	$article_forge_simage = $_POST['ajax_article_forge_simage'];
	$article_forge_svideo = $_POST['ajax_article_forge_svideo'];
	$article_forge_slength = $_POST['ajax_article_forge_slength'];
	$article_forge_sheading = $_POST['ajax_article_forge_sheading'];
	$article_forge_category = $_POST['ajax_article_forge_category'];
	$article_forge_post_status = $_POST['ajax_article_forge_post_status'];
	$article_forge_auto_sheading = $_POST['ajax_article_forge_auto_sheading'];
		
	if($article_forge_auto_sheading == 'off')
	{		
		if($article_forge_slength == 'medium')
		{	
			if(!empty($_POST['ajax_article_forge_med_subhead_id1']))
			{
				$article_forge_med_subhead_id1 = ",".$_POST['ajax_article_forge_med_subhead_id1'];
			}
			else
			{
				$article_forge_med_subhead_id1 = '';
			}
			if(!empty($_POST['ajax_article_forge_med_subhead_id2']))
			{
				$article_forge_med_subhead_id2 = ",".$_POST['ajax_article_forge_med_subhead_id2'];
			}
			else
			{
				$article_forge_med_subhead_id2 = '';
			}
			if(!empty($_POST['ajax_article_forge_med_subhead_id3']))
			{
				$article_forge_med_subhead_id3 = ",".$_POST['ajax_article_forge_med_subhead_id3'];
			}
			else
			{
				$article_forge_med_subhead_id3 = '';
			}
			
				$section_headings_all = $article_forge_med_subhead_id1.$article_forge_med_subhead_id2.$article_forge_med_subhead_id3;
			
		}
		elseif($article_forge_slength == 'long')
		{
			if(!empty($_POST['ajax_article_forge_long_subhead_id1']))
			{
				$article_forge_long_subhead_id1 = ",".$_POST['ajax_article_forge_long_subhead_id1'];
			}
			else
			{
				$article_forge_long_subhead_id1 = '';
			}
			if(!empty($_POST['ajax_article_forge_long_subhead_id2']))
			{
				$article_forge_long_subhead_id2 = ",".$_POST['ajax_article_forge_long_subhead_id2'];
			}
			else
			{
				$article_forge_long_subhead_id2 = '';
			}
			if(!empty($_POST['ajax_article_forge_long_subhead_id3']))
			{
				$article_forge_long_subhead_id3 = ",".$_POST['ajax_article_forge_long_subhead_id3'];
			}
			else
			{
				$article_forge_long_subhead_id3 = '';
			}
			if(!empty($_POST['ajax_article_forge_long_subhead_id4']))
			{
				$article_forge_long_subhead_id4 = ",".$_POST['ajax_article_forge_long_subhead_id4'];
			}
			else
			{
				$article_forge_long_subhead_id4 = '';
			}
			if(!empty($_POST['ajax_article_forge_long_subhead_id5']))
			{
				$article_forge_long_subhead_id5 = ",".$_POST['ajax_article_forge_long_subhead_id5'];
			}
			else
			{
				$article_forge_long_subhead_id5 = '';
			}
			
			$section_headings_all = $article_forge_long_subhead_id1.$article_forge_long_subhead_id2.$article_forge_long_subhead_id3.$article_forge_long_subhead_id4.$article_forge_long_subhead_id5;
			
		}
		elseif($article_forge_slength == 'very_long')
		{
			$article_forge_vlong_subhead_id1 = $_POST['ajax_article_forge_vlong_subhead_id1'];
			$article_forge_vlong_subhead_id2 = $_POST['ajax_article_forge_vlong_subhead_id2'];
			$article_forge_vlong_subhead_id3 = $_POST['ajax_article_forge_vlong_subhead_id3'];
			$article_forge_vlong_subhead_id4 = $_POST['ajax_article_forge_vlong_subhead_id4'];
			
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id1']))
			{
				$article_forge_vlong_subhead_id1 = ",".$_POST['ajax_article_forge_vlong_subhead_id1'];
			}
			else
			{
				$article_forge_vlong_subhead_id1 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id2']))
			{
				$article_forge_vlong_subhead_id2 = ",".$_POST['ajax_article_forge_vlong_subhead_id2'];
			}
			else
			{
				$article_forge_vlong_subhead_id2 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id3']))
			{
				$article_forge_vlong_subhead_id3 = ",".$_POST['ajax_article_forge_vlong_subhead_id3'];
			}
			else
			{
				$article_forge_vlong_subhead_id3 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id4']))
			{
				$article_forge_vlong_subhead_id4 = ",".$_POST['ajax_article_forge_vlong_subhead_id4'];
			}
			else
			{
				$article_forge_vlong_subhead_id4 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id5']))
			{
				$article_forge_vlong_subhead_id5 = ",".$_POST['ajax_article_forge_vlong_subhead_id5'];
			}
			else
			{
				$article_forge_vlong_subhead_id5 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id6']))
			{
				$article_forge_vlong_subhead_id6 = ",".$_POST['ajax_article_forge_vlong_subhead_id6'];
			}
			else
			{
				$article_forge_vlong_subhead_id6 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id7']))
			{
				$article_forge_vlong_subhead_id7 = ",".$_POST['ajax_article_forge_vlong_subhead_id7'];
			}
			else
			{
				$article_forge_vlong_subhead_id7 = '';
			}
			if(!empty($_POST['ajax_article_forge_vlong_subhead_id8']))
			{
				$article_forge_vlong_subhead_id8 = ",".$_POST['ajax_article_forge_vlong_subhead_id8'];
			}
			else
			{
				$article_forge_vlong_subhead_id8 = '';
			}
			
			$section_headings_all = $article_forge_vlong_subhead_id1.$article_forge_vlong_subhead_id2.$article_forge_vlong_subhead_id3.$article_forge_vlong_subhead_id4.$article_forge_vlong_subhead_id5.$article_forge_vlong_subhead_id6.$article_forge_vlong_subhead_id7.$article_forge_vlong_subhead_id8;			
		}
	}
	else
	{
		$section_headings_all = '';
	}	
	
	
	$section_headings_all = ltrim($section_headings_all,",");
	
	if(!empty($article_forge_keyword))
	{
		$article_forge_final_result = $channel_detail_api_class1->article_forge_ref_id_new($article_forge_keyword,$article_forge_subkeyword,$article_forge_stitle,$article_forge_simage,$article_forge_svideo,$article_forge_slength,$article_forge_sheading,$section_headings_all);

		if(is_numeric($article_forge_final_result))
		{
			if(!empty($article_forge_final_result))
			{
				$wpch_article_forge_ref = update_option('wpch_articleforge_singlepost',$article_forge_final_result);
				$wpch_article_forge_cat = update_option('wpch_articleforge_singlepost_cat',$article_forge_category);
				$wpch_article_forge_heading = update_option('wpch_articleforge_singlepost_heading',$article_forge_heading);
				$wpch_article_forge_post_status = update_option('wpch_articleforge_singlepost_status',$article_forge_post_status);
				?>
				<div class="wrap">
					<div class="updated"><p>Article creation process has been started. It will take few minutes to complete the article. Once its completed, it will available in the posts section.</p></div>
				</div>
				<?php
			}
			else
			{
			?>
			<div class="wrap">
				<div class="error"><p>Your earlier article creation is still in process. Please wait for few minutes to initiate new request.</p></div>
			</div>
			<?php
			}
		}
		else
		{
			?>
			<div class="wrap">
				<div class="error"><p><?php echo $article_forge_final_result; ?></p></div>
			</div>
			<?php
		}
	}
	else
	{
	?>
	<div class="wrap">
		<div class="error"><p>Please enter the section heading. </p></div>
	</div>
	<?php
	}
	?>
	<script>
	jQuery(function() {
		setTimeout(function() {
			  jQuery('.updated').fadeOut('slow');
			}, 10000); // <-- time in milliseconds
		setTimeout(function() {
			  jQuery('.error').fadeOut('slow');
			}, 10000); // <-- time in milliseconds
	});
	</script>	
	<?php
	exit;
}

function mywpch_article_forge_cron_schedules( $schedules ) 
{
	$schedules[ 'every1minute_articleforge' ] = array( 'interval' => 60 * 1, 'display' => __( 'Every One Minute', 'article_forge_post' ) );

    return $schedules;
}

add_filter( 'cron_schedules', 'mywpch_article_forge_cron_schedules' );

if (! wp_next_scheduled ( 'every1minute_articleforge_events' )) 
{
	wp_schedule_event(time(), 'every1minute_articleforge', 'every1minute_articleforge_events');
}

add_action('every1minute_articleforge_events', 'mywpch_article_forge_cron');

function mywpch_article_forge_cron()
{
    global $wpdb;
	
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';	
	$channel_detail_api_class_cron = new channelapi();	
	
	$result_article_forge_ref = get_option('wpch_articleforge_singlepost');	
	$result_article_forge_cat = get_option('wpch_articleforge_singlepost_cat');
	$result_article_forge_heading = get_option('wpch_articleforge_singlepost_heading');
	$result_article_forge_status = get_option('wpch_articleforge_singlepost_status');
	if(!empty($result_article_forge_status))
	{
		$result_article_forge_status1 = $result_article_forge_status;
	}
	else
	{
		$result_article_forge_status1 = 'publish';
	}
	
	if(!empty($result_article_forge_cat))
	{
		$article_cat1 = $result_article_forge_cat;
	}
	else
	{
		$article_cat1 = '';
	}
	
	if(!empty($result_article_forge_heading))
	{
		$result_article_forge_heading1 = $result_article_forge_heading;
	}
	else
	{
		$result_article_forge_heading1 = '';
	}
	
	if(!empty($result_article_forge_ref))
	{		
		$article_forge_cron_result = $channel_detail_api_class_cron->article_forge_result_new($result_article_forge_ref);
		
		if(!empty($article_forge_cron_result))
		{
			$article_forge_cron_result1 = $article_forge_cron_result;
			remove_filter('content_save_pre', 'wp_filter_post_kses'); 	
			remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');

			$channel_videos_title = $channel_detail_api_class_cron->fnextractHeadins('h1', $article_forge_cron_result1);
			if(!empty($channel_videos_title))
			{
				$channel_videos_title1 = $channel_videos_title;
				$channel_videos_content = str_replace($channel_videos_title,"",$article_forge_cron_result1);
			}
			else
			{
				$channel_videos_title1 = '';
				$channel_videos_content = $article_forge_cron_result1;
			}

			$spin_my_post_inserts = array(
							  'post_title'    => $channel_videos_title1,
							  'post_content'  => $channel_videos_content,
							  'post_category' => array($article_cat1),
							  'post_status'   => $result_article_forge_status1
							);
							 
			
			// Insert the post into the database
			wp_insert_post($spin_my_post_inserts);
			
			add_filter('content_save_pre', 'wp_filter_post_kses');
			add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
			
			$wpch_aforge_id = 'success';
			$wpch_aforge_cat = '';
			$wpch_aforge_heading = '';
			$wpch_aforge_status = '';
			
			update_option('wpch_articleforge_singlepost',$wpch_aforge_id);
			update_option('wpch_articleforge_singlepost_cat',$wpch_aforge_cat);
			update_option('wpch_articleforge_singlepost_heading',$wpch_aforge_heading);
			update_option('wpch_articleforge_singlepost_status',$wpch_aforge_status);
		}
	}
}

function mywpch_article_forge_posts_cron_schedules( $schedules ) 
{
	$schedules[ 'every2minute_articleforge_posts' ] = array( 'interval' => 60 * 2, 'display' => __( 'Every Two Minute', 'article_forge_posts' ) );

    return $schedules;
}

add_filter( 'cron_schedules', 'mywpch_article_forge_posts_cron_schedules' );

if (! wp_next_scheduled ( 'every2minute_articleforgepost' )) 
{
	wp_schedule_event(time(), 'every2minute_articleforge_posts', 'every2minute_articleforgepost');
}

add_action('every2minute_articleforgepost', 'mywpch_article_forge_post_cron');


//mywpch_article_forge_post_cronsss();
function mywpch_article_forge_post_cron()
{
    global $wpdb,$post;
	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';	
	
	$af_cron_ref_id = get_option('wpch_af_cron_ref_id');	
	$channel_detail_api_class_cron = new channelapi();	
	//$result_article_forge_enable1 = get_option('wpch_articleforge_enable');

	$af_del_post_table_name = $wpdb->base_prefix . "mych_afarticles";
    $af_del_post_table = $wpdb->get_results("select * from ".$af_del_post_table_name." where status=1");
    if(!empty($af_del_post_table))
    {
        $wpdb->query($wpdb->prepare("DELETE FROM $af_del_post_table_name WHERE status = %d",'1'));
    }
	
	$af_table_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_afarticles WHERE status = 0 ORDER BY id ASC limit 0,1");				

	if(!empty($af_table_result_detail))
	{
		$result_article_forge_enable1 = $af_table_result_detail[0]->af_enable;
		if(!empty($result_article_forge_enable1) && $result_article_forge_enable1 == 'on')
		{
			if(!empty($af_cron_ref_id))
			{
				$af_cron_table_id = get_option('wpch_af_cron_table_id');
				
				$af_table_result_detail_new = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_afarticles WHERE id = ".$af_cron_table_id);				
				
				if(!empty($af_table_result_detail_new))
				{					
					$api_key = get_option('wpch_articleforge_app_key');
					if(!empty($api_key))
					{
						$ch = curl_init('https://af.articleforge.com/api/view_article');
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
						curl_setopt ($ch, CURLOPT_POST, 1);
						curl_setopt ($ch, CURLOPT_POSTFIELDS,
						"key=$api_key&article_id=$af_cron_ref_id");
						$result = curl_exec($ch);
						curl_close ($ch);

						$result_resp = json_decode($result);
						if($result_resp->status == 'Fail')
						{
							$status_updateds = 2;
							$af_cron_tble = $wpdb->base_prefix . "mych_afarticles";
							$wpdb->update( $af_cron_tble,array('status'=>$status_updateds),array('id'=> $af_cron_table_id));
											
							delete_option( 'wpch_af_cron_ref_id' );
							delete_option( 'wpch_af_cron_table_id' );
						}
						else
						{
							if(!empty($result_resp->data))
							{
								$article_forge_final_result1 = $result_resp->data;	
								
								$src = array (); // array for src's
								preg_match_all ( '/src="([^"]+)"/', $article_forge_final_result1, $src );
								$just_urls = $src[1];
								
								$af_img = "<div style='display:flex;justify-content:center;'><img src=".$just_urls[0]." style='height:auto;width:auto;max-height:500px;max-width:600px;margin:10px;' /></div>";
								$content = preg_replace("/<img[^>]+\>/i", "", $article_forge_final_result1); 
								$af_content = "<div>".$content."</div>";
								$af_word_count = "<div>word count: ".str_word_count($content)."</div>";

								
								
								$image = $af_table_result_detail_new[0]->image;
								$iframe_video_id = $af_table_result_detail_new[0]->vid_id;
								$iframe_video = "<iframe width=620 height=330 src=https://www.youtube.com/embed/$iframe_video_id></iframe>";

								remove_filter('content_save_pre', 'wp_filter_post_kses');
								remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
								
								$af_desc = str_replace('<a', '<a target="_blank"', $af_table_result_detail_new[0]->description);
				
								// Create post object
								$my_post = array(
								  'post_title'    => wp_strip_all_tags( $af_table_result_detail_new[0]->title),
								  'post_content'  => $af_desc."<br/><br/>".$af_img."<br/>".$af_content."<br/>".$af_word_count,
								  'post_category' => unserialize($af_table_result_detail_new[0]->category),
								  'post_status'   => 'publish'	  
								);
								 
								// Insert the post into the database
								$ids = wp_insert_post( $my_post );
								
								add_filter('content_save_pre', 'wp_filter_post_kses');
								add_filter('content_filtered_save_pre', 'wp_filter_post_kses');

								if(!empty($image))
								{
									$image_url        = $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 );		
								}
								
								$status_updateds = 1;
								$af_cron_tble = $wpdb->base_prefix . "mych_afarticles";
								$wpdb->update( $af_cron_tble,array('status'=>$status_updateds),array('id'=> $af_cron_table_id));
												
								delete_option( 'wpch_af_cron_ref_id' );
								delete_option( 'wpch_af_cron_table_id' );
							}
						}
					}
				}
			}
			else 
			{
				//$title_updated = str_replace( array( '\'', '"',',' , ';', '<', '>', '.', '-' ), '', $af_table_result_detail[0]->title);

				$key_updated = $af_table_result_detail[0]->keyword;								
				$subkey_updated = $af_table_result_detail[0]->subkey;							
				$af_ref_id = $channel_detail_api_class_cron->article_forge_ref_id($key_updated,$subkey_updated);	
				
				if(!empty($af_ref_id))
				{
					update_option('wpch_af_cron_ref_id',$af_ref_id);
					update_option('wpch_af_cron_table_id',$af_table_result_detail[0]->id);
				}	
			}			
		}
		else
		{
			$article_forge_final_result1 = '';	
			
			$image = $af_table_result_detail[0]->image;
			$iframe_video_id = $af_table_result_detail[0]->vid_id;
			$iframe_video = "<iframe width=620 height=330 src=https://www.youtube.com/embed/$iframe_video_id></iframe>";
							
			remove_filter('content_save_pre', 'wp_filter_post_kses');
			remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
						
			$af_desc = str_replace('<a', '<a target="_blank"', $af_table_result_detail[0]->description);
		
			// Create post object
			$my_post = array(
			  'post_title'    => wp_strip_all_tags( $af_table_result_detail[0]->title),
			  'post_content'  => $af_desc."<br/><br/>".$article_forge_final_result1,
			  'post_category' => unserialize($af_table_result_detail[0]->category),
			  'post_status'   => 'publish'	  
			);
			 
			// Insert the post into the database
			$ids = wp_insert_post( $my_post );
			
			add_filter('content_save_pre', 'wp_filter_post_kses');
			add_filter('content_filtered_save_pre', 'wp_filter_post_kses');			
			
			if(!empty($image))
			{
				$image_url        = $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 );		
			}
			
			$status_updateds = 1;
			$af_cron_tble = $wpdb->base_prefix . "mych_afarticles";
			$wpdb->update( $af_cron_tble,array('status'=>$status_updateds),array('id'=> $af_table_result_detail[0]->id));						
		}
		
		if(!empty($ids))
		{
			$channel_post_meta_key_id = "mych_channels_video_post_id_".$af_table_result_detail[0]->vid_id;
			
			delete_post_meta_by_key($channel_post_meta_key_id);
			update_post_meta( $ids, 'mych_channels_video_id', $af_table_result_detail[0]->vid_id, true );
			update_post_meta( $af_table_result_detail[0]->channel_post_id, $channel_post_meta_key_id, $ids, true );		
		}
	}
}

function mywpch_article_forge_posts_24hour_cron_schedules( $schedules ) 
{
	$schedules[ 'every2minute_articleforge_24hour_posts' ] = array( 'interval' => 60 * 24, 'display' => __( 'Every 24 hour', 'article_forge_posts_24hour' ) );

    return $schedules;
}

add_filter( 'cron_schedules', 'mywpch_article_forge_posts_24hour_cron_schedules' );

if (! wp_next_scheduled ( 'every24hour_articleforgepost' )) 
{
	wp_schedule_event(time(), 'every2minute_articleforge_24hour_posts', 'every24hour_articleforgepost');
}

add_action('every24hour_articleforgepost', 'mywpch_article_forge_post_cron_24hour');

function mywpch_article_forge_post_cron_24hour()
{
    global $wpdb,$post;	
	require_once plugin_dir_path( __FILE__ ) .'ytube_channels/class/channels_api.php';		
	
	$af_table_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->base_prefix."mych_afarticles WHERE status = 2");

	foreach($af_table_result_detail as $af_table_result_detail1)
	{		
		$status_updateds = 0;
		$af_cron_tble = $wpdb->base_prefix . "mych_afarticles";
		$wpdb->update( $af_cron_tble,array('status'=>$status_updateds),array('status'=> $af_table_result_detail1->status));						
	}		
}