<?php

define('blogger_plugin_dir',WP_PLUGIN_DIR.'/affiembed');



add_action( 'wp_ajax_nopriv_afe_get_subcat', 'ajax_afe_get_subcat' );
add_action('wp_ajax_afe_get_subcat', 'ajax_afe_get_subcat');

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

    $afe_blog_main=new afeblogs();

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

add_action( 'wp_ajax_nopriv_afe_get_search_result', 'ajax_afe_get_search_result' );
add_action('wp_ajax_afe_get_search_result', 'ajax_afe_get_search_result');

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

    $ajax_check_val =  $_POST['afe_ajax_array_val'];
    $ajax_key =  $_POST['afe_ajax_keyword'];
    
    $afe_blog_main1->afe_search_result($ajax_check_val,$ajax_key);
    ?>    
   <table id="example_article" class="table table-striped widefat" style="width:100%;">
      <thead>
        <tr>
          <th style="text-align: inherit;font-weight: 700;">Title</th>
          <th style="text-align: inherit;font-weight: 700;">Description</th>
          <th style="text-align: inherit;font-weight: 700;">Actions<th>
        </tr>
      </thead>
      <tbody>
      <?php
        global $wpdb;
        $afe_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_tmp_table WHERE type = 'article' ORDER BY id ASC");
        if(!empty($afe_result_detail))
        {
        	foreach($afe_result_detail as $afe_result_detail1)
        	{  
        	    echo "<tr>";
        	    echo "<td></td>";
        	    echo "<td><p style=color:firebrick>".$afe_result_detail1->title."</p></td>";
        	    echo "<td><p>".$afe_result_detail1->short_des."</p></td>";
                echo "<td><input type=checkbox name=afe_check_vals[] class=afe_check_val value=".$afe_result_detail1->id." /></td>";
                echo "</tr>";
        	}
        }
       ?>
      </tbody>
    </table>
    <script>
        jQuery(document).ready(function() 
        {
          var table_article = jQuery('#example_article').DataTable({ 
                select: false,
                "columnDefs": [{
                    className: "Name", 
                    "targets":[0],
                    "visible": false,
                    "searchable":false
                }]
            });//End of create main table
        });
    </script>
<?php    
exit;
}

add_action( 'wp_ajax_nopriv_afe_get_check_result', 'ajax_afe_get_check_result' );
add_action('wp_ajax_afe_get_check_result', 'ajax_afe_get_check_result');

function ajax_afe_get_check_result ()
{
    global $wpdb;
    $ajax_check_result =  $_POST['afe_ajax_check_array_val'];

	$afe_check_val = str_replace( ',', ' ', $ajax_check_result );
    $afe_check_split_string=explode(" ",$afe_check_val);
    
    foreach($afe_check_split_string as $afe_check_split_string1)
    {
        $afe_saved_table = $wpdb->prefix . "afe_saved_result";
        $afe_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_tmp_table WHERE id = '".$afe_check_split_string1."' AND type = 'article'");
        $afe_count_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_saved_result WHERE catg_id = '".$afe_check_result_detail[0]->catg_id."' AND type = 'article'");
        
        if (count($afe_count_check_result_detail) == 0)
        {
            $afe_saved_data=array(
                                'catg_id' => $afe_check_result_detail[0]->catg_id, 
                                'title' => $afe_check_result_detail[0]->title, 
                                'link' => $afe_check_result_detail[0]->link, 
                                'short_des' => $afe_check_result_detail[0]->short_des, 
                                'long_desc' => $afe_check_result_detail[0]->long_desc, 
                                'type' => 'article' 
                               );
    
            $insert = $wpdb->insert( $afe_saved_table, $afe_saved_data); 
        }
    }
    if($insert)
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is Saved</p></div>
    </div>
    <?php }
    else
    {?>
    <div class="wrap">
        <div class="updated"><p>Data is alreday saved</p></div>
    </div>
    <?php }?>
    <script>
    jQuery(function() {
        setTimeout(function() {
              jQuery('.updated').fadeOut('slow');
            }, 5000); // <-- time in milliseconds
    });
    </script>
    <?php
    exit;
}

add_action( 'wp_ajax_nopriv_afe_search_video_result', 'ajax_afe_search_video_result' );
add_action('wp_ajax_afe_search_video_result', 'ajax_afe_search_video_result');

function ajax_afe_search_video_result ()
{
    include_once("template/class/afe_blog.php"); 
    include_once("template/API/google/Google_Client_v1.php"); 
    include_once("template/API/google/contrib/Google_YouTubeService.php"); 

    $afe_blog_main_video = new afeblogs();

    $ajax_video_key_val = $_REQUEST['afe_ajax_vid_keyword'];

    $afe_blog_main_video->afe_youtube_search_keyword($ajax_video_key_val);
    ?>    
   <table id="example_videos" class="table table-striped widefat" style="width:100%;">
      <thead>
        <tr>
          <th style="text-align: inherit;font-weight: 700;"></th>
          <th style="text-align: inherit;font-weight: 700;">Image</th>
          <th style="text-align: inherit;font-weight: 700;">Title</th>
          <th style="text-align: inherit;font-weight: 700;">Description</th>
          <th style="text-align: inherit;font-weight: 700;">Actions<h>
        </tr>
      </thead>
      <tbody>
      <?php
        global $wpdb;
        $afe_result_detail_video = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_tmp_table WHERE type = 'video' ORDER BY id ASC");
        
        if(!empty($afe_result_detail_video))
        {
            foreach($afe_result_detail_video as $afe_result_detail_video1)
            {  
                $afe_fetch_link_data = unserialize($afe_result_detail_video1->link);
    		    $afe_video_url = $afe_fetch_link_data['link'];
    		    $afe_video_image = $afe_fetch_link_data['thum_img_url'];
        	    echo "<tr>";
        	    echo "<td></td>";
        	    echo "<td><a href=https://www.youtube.com/watch?v=$afe_video_url target=_blank><img src='".$afe_video_image."'/></a></td>";
        	    echo "<td><p style=color:firebrick>".$afe_result_detail_video1->title."</p></td>";
        	    echo "<td><p>".wp_trim_words($afe_result_detail_video1->short_des,10)."</p></td>";
                echo "<td><input type=checkbox name=afe_video_check_vals[] class=afe_video_check_val value=".$afe_result_detail_video1->id."></td>";
                echo "</tr>";
            }
        }
        ?>
       </tbody>
    </table>
    <script>
        jQuery(document).ready(function() 
        {
          var table = jQuery('#example_videos').DataTable({ 
                select: false,
                "columnDefs": [{
                    className: "Name", 
                    "targets":[0],
                    "visible": false,
                    "searchable":false
                }]
            });//End of create main table
        });
    </script>
    <?php    
    exit;
}
add_action( 'wp_ajax_nopriv_afe_video_check_results', 'ajax_afe_video_check_results' );
add_action('wp_ajax_afe_video_check_results', 'ajax_afe_video_check_results');

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

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


add_action( 'wp_ajax_nopriv_afe_campaign_search_result', 'ajax_afe_campaign_search_result' );
add_action('wp_ajax_afe_campaign_search_result', 'ajax_afe_campaign_search_result');

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

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


add_action( 'wp_ajax_nopriv_afe_get_check_campaign_result', 'ajax_afe_get_check_campaign_result' );
add_action('wp_ajax_afe_get_check_campaign_result', 'ajax_afe_get_check_campaign_result');
function ajax_afe_get_check_campaign_result()
{
    global $wpdb;
    
    include_once("template/class/afe_blog.php"); 
    include_once("template/API/google/Google_Client_v1.php"); 
    include_once("template/API/google/contrib/Google_YouTubeService.php"); 

    $ajax_campaign_check_cat_result =  $_POST['afe_ajax_campaign_check_array_val'];
    $ajax_campaign_check_title_result =  $_POST['afe_ajax_campaign_title'];
    $ajax_campaign_check_keyword_result =  $_POST['afe_ajax_campaign_key'];
    $ajax_campaign_check_hour =  $_POST['afe_ajax_campaign_hour'];
    $ajax_campaign_check_days =  $_POST['afe_ajax_campaign_days'];
    $ajax_campaign_check_img_key =  $_POST['afe_ajax_campaign_img_key'];
    $ajax_campaign_check_vid_key =  $_POST['afe_ajax_campaign_vid_key'];
    $ajax_campaign_check_product_shortcode =  $_POST['afe_ajax_product_shortcode'];
    if(!empty($ajax_campaign_check_product_shortcode))
    {
        $ajax_campaign_check_product_shortcode1 = $ajax_campaign_check_product_shortcode;
    }

    $afe_blog_main_video1 = new afeblogs();
    $ajax_video_key_val1 = $ajax_campaign_check_vid_key;
    $afe_blog_main_video1->afe_youtube_search_keyword1($ajax_video_key_val1);

    $check_img_post = "https://pixabay.com/api/?key=13567124-98ebe95018edbf2b8743e43d6&q=".$ajax_campaign_check_img_key."&per_page=5";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $check_img_post);
    $result_img_post = curl_exec($ch);
    curl_close($result_img_post);
    
    $afe_array_img_post = json_decode($result_img_post);
    
    $ran_img = $afe_array_img_post->hits;
    $randomElement_img_post = $ran_img[array_rand($ran_img, 1)];
    
    $featured_img_post = $randomElement_img_post->webformatURL;
    $featured_img_post_basename = $randomElement_img_post->previewURL;



    $afe_campaign_table = $wpdb->prefix . "afe_camapign";
    $afe_count_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_camapign WHERE c_title = '".$ajax_campaign_check_title_result."'");
    
    if (count($afe_count_campaign_check_result_detail) == 0)
    {
        $afe_campaign_data=array(
                            'c_title' => $ajax_campaign_check_title_result, 
                            'c_sub_cat' => $ajax_campaign_check_cat_result, 
                            'c_keyword' => $ajax_campaign_check_keyword_result, 
                            'c_img_key' => $ajax_campaign_check_img_key, 
                            'c_ytube_key' => $ajax_campaign_check_vid_key, 
                            'c_prod_short' => stripslashes($ajax_campaign_check_product_shortcode), 
                            'c_hours' => $ajax_campaign_check_hour[0], 
                            'c_days' => $ajax_campaign_check_days[0],
                            'c_date' => ''
                           );

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

        $afe_count_campaign_check = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_camapign WHERE c_title = '".$ajax_campaign_check_title_result."'");
    
        if(count($afe_count_campaign_check) > 0)
        {
            $afe_campaign_post_table = $wpdb->prefix . "afe_campaign_post";
            
            $afe_campaign_table_subcat = $afe_count_campaign_check[0]->c_sub_cat;
            $afe_campaign_check_val = str_replace( ',', ' ', $afe_campaign_table_subcat );
            $afe_campaign_check_split_string=explode(" ",$afe_campaign_check_val);
    
            $afe_today=date('Y-m-d 00:00:00');  
            $afe_schedule_hours = $ajax_campaign_check_hour[0];
            $afe_schedule_days = $ajax_campaign_check_days[0];
            //$afe_current_datetime_hours=date('Y-m-d H:i:s',strtotime($afe_today . 'now +1 hour'));
            //$afe_current_datetime_days=date('Y-m-d H:i:s',strtotime($afe_today . ' +1 day'));
            if($afe_schedule_hours)
            {
                $afe_current_datetime_hours = date('Y-m-d H:i:s',strtotime("now +".$afe_schedule_hours." hour"));
            }       
            if($afe_schedule_days)
            {
                $afe_current_datetime_days = date('Y-m-d H:i:s',strtotime($afe_today . " +".$afe_schedule_days." day"));
            }       
            foreach($afe_campaign_check_split_string as $afe_campaign_check_split_string1)
            {
                //echo $afe_campaign_check_split_string1;
                $afe_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_tmp_table WHERE id = '".$afe_campaign_check_split_string1."' AND type = 'article'");
                
                if(!empty(get_option( 'afe_spin_api_setting' )))
                {
                    if($_POST['afe_ajax_afe_spin_content'] == 'on')
                    {
                        $spin_titles = $afe_campaign_check_result_detail[0]->title;
                        $spin_contents = $afe_campaign_check_result_detail[0]->long_desc;
                        
                        $ap_key = "ff1c034a-d3d3-11e9-9b14-022f908df96c";
                        $post_data=array('negativekeyword'=>'','originaltext'=>$spin_titles,'quality'=>10,'apikey'=>$ap_key);
                        $post_data_content=array('negativekeyword'=>'','originaltext'=>$spin_contents,'quality'=>10,'apikey'=>$ap_key);
                        
                        $url = 'http://spinnerbros.com/api/turningarticlev2';
                        
                        $curl = curl_init();
                        curl_setopt($curl, CURLOPT_URL, $url);
                        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                        curl_setopt($curl, CURLOPT_POSTFIELDS,$post_data);
                        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                        
                        $response = curl_exec($curl);
                        
                        $data=json_decode($response, true);
                        if($data['status']=="success")
                        {
                            $spinned_title = $data['uniqarticle'];
                        }
                        
    
                        $curl1 = curl_init();
                        curl_setopt($curl1, CURLOPT_URL, $url);
                        curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($curl1, CURLOPT_CUSTOMREQUEST, "POST");
                        curl_setopt($curl1, CURLOPT_POSTFIELDS,$post_data_content);
                        curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
                        
                        $response1 = curl_exec($curl1);
                        
                        $data1=json_decode($response1, true);
                        if($data1['status']=="success")
                        {
                            $spinned_content = $data1['uniqarticle'];
                        }
                        
                    }
                    else
                    {
                        $spinned_title = $afe_campaign_check_result_detail[0]->title;
                        $spinned_content = $afe_campaign_check_result_detail[0]->long_desc;
                    }
                }
                else
                {
                    $spinned_title = $afe_campaign_check_result_detail[0]->title;
                    $spinned_content = $afe_campaign_check_result_detail[0]->long_desc;
                }
                $vid_link_option = "https://youtu.be/".get_option( 'vid_tmp_camp' );
                $post_desc = $spinned_content ."<br/><br/>".$ajax_campaign_check_product_shortcode1."<br/><br/>".$vid_link_option;
                $afe_schedule_post_array = array(
                      'post_title'    => $spinned_title,
                      'post_content'  => $post_desc,
                      'post_status'   => 'draft',
                      'post_author'   => 1,
                    );
                     
                // Insert the post into the database
                $afe_schedule_post_id = wp_insert_post($afe_schedule_post_array,true);

                if($afe_schedule_post_id)
                {    
                    $image_url        = $featured_img_post; // Define the image URL here
                    $image_name       = basename($featured_img_post_basename);
                    $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, $afe_schedule_post_id );
                    
                    // Include image.php
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    
                    // Define attachment metadata
                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                    
                    // Assign metadata to attachment
                    wp_update_attachment_metadata( $attach_id, $attach_data );
                    
                    // And finally assign featured image to post
                    set_post_thumbnail( $afe_schedule_post_id, $attach_id );
                    
                    if($afe_schedule_hours)
                    {
                        $afe_campaign_post_data=array(
                                                'post_id' => $afe_schedule_post_id, 
                                                'campaign_id' => $afe_count_campaign_check[0]->id, 
                                                'schedule_date' => $afe_current_datetime_hours, 
                                                'status' => 0, 
                                               );
                        $campaign_post_insert = $wpdb->insert( $afe_campaign_post_table, $afe_campaign_post_data); 

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

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

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

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

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

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

    return $schedules;
}

add_filter( 'cron_schedules', 'afe_cron_schedules' );

if (! wp_next_scheduled ( 'every1hour_events' )) 
{
	wp_schedule_event(time(), 'every1hour', 'every1hour_events');
}

add_action('every1hour_events', 'afe_campaign_cron');

add_action( 'wp_ajax_nopriv_afe_search_img_result', 'ajax_afe_search_img_result' );
add_action('wp_ajax_afe_search_img_result', 'ajax_afe_search_img_result');

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

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

add_action( 'wp_ajax_nopriv_afe_img_check_results', 'ajax_afe_img_check_results' );
add_action('wp_ajax_afe_img_check_results', 'ajax_afe_img_check_results');

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


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

add_action( 'wp_ajax_nopriv_afe_edit_check_campaign_result', 'ajax_afe_edit_check_campaign_result' );
add_action('wp_ajax_afe_edit_check_campaign_result', 'ajax_afe_edit_check_campaign_result');

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

    $ajax_edit_campaign_check_id =  $_POST['afe_ajax_campaign_id'];
    $ajax_edit_campaign_check_cat_result =  $_POST['afe_ajax_edit_campaign_check_array_val'];
    $ajax_edit_campaign_check_title_result =  $_POST['afe_ajax_edit_campaign_title'];
    $ajax_edit_campaign_check_keyword_result =  $_POST['afe_ajax_edit_campaign_key'];
    $ajax_edit_campaign_check_hour =  $_POST['afe_ajax_edit_campaign_hour'];
    $ajax_edit_campaign_check_days =  $_POST['afe_ajax_edit_campaign_days'];
    $ajax_edit_campaign_check_img_key =  $_POST['afe_ajax_edit_campaign_img_key'];
    $ajax_edit_campaign_check_vid_key =  $_POST['afe_ajax_edit_campaign_vid_key'];
    $ajax_edit_campaign_check_product_shortcode =  $_POST['afe_ajax_edit_product_shortcode'];
    
    if(!empty($ajax_edit_campaign_check_product_shortcode))
    {
        $ajax_edit_campaign_check_product_shortcode1 = $ajax_edit_campaign_check_product_shortcode;
    }
    
    $afe_edit_blog_main_video1 = new afeblogs();
    $ajax_edit_video_key_val1 = $ajax_edit_campaign_check_vid_key;
    $afe_edit_blog_main_video1->afe_youtube_search_keyword1($ajax_edit_video_key_val1);

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

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

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

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

    	$afe_edit_today=date('Y-m-d 00:00:00');	
    	$afe_edit_current_datetime=date('Y-m-d H:i:s',strtotime($afe_edit_today . ' +1 day'));
    	$afe_edit_schedule_hours = $ajax_edit_campaign_check_hour[0];
    	$afe_edit_schedule_days = $ajax_edit_campaign_check_days[0];
    	
        foreach($afe_edit_campaign_check_split_string as $afe_edit_campaign_check_split_string1)
        {
            echo $afe_campaign_check_split_string1;
            $afe_edit_campaign_check_result_detail = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."afe_tmp_table WHERE id = '".$afe_edit_campaign_check_split_string1."' AND type = 'article'");
            
            
            if(!empty(get_option( 'afe_spin_api_setting' )))
            {
                if($_POST['afe_ajax_afe_spin_content'] == 'on')
                {
                    $spin_edit_titles = $afe_edit_campaign_check_result_detail[0]->title;
                    $spin_edit_contents = $afe_edit_campaign_check_result_detail[0]->long_desc;
                    
                    $ap_edit_key = "ff1c034a-d3d3-11e9-9b14-022f908df96c";
                    $post_edit_data=array('negativekeyword'=>'','originaltext'=>$spin_edit_titles,'quality'=>10,'apikey'=>$ap_edit_key);
                    $post_edit_data_content=array('negativekeyword'=>'','originaltext'=>$spin_edit_contents,'quality'=>10,'apikey'=>$ap_edit_key);
                    
                    $edit_url = 'http://spinnerbros.com/api/turningarticlev2';
                    
                    $curl = curl_init();
                    curl_setopt($curl, CURLOPT_URL, $edit_url);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($curl, CURLOPT_POSTFIELDS,$post_edit_data);
                    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                    
                    $edit_response = curl_exec($curl);
                    
                    $edit_data=json_decode($edit_response, true);
                    if($edit_data['status']=="success")
                    {
                    	$spinned_edit_title = $edit_data['uniqarticle'];
                    }
                    

                    $curl1 = curl_init();
                    curl_setopt($curl1, CURLOPT_URL, $edit_url);
                    curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl1, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($curl1, CURLOPT_POSTFIELDS,$post_edit_data_content);
                    curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
                    
                    $edit_response1 = curl_exec($curl1);
                    
                    $edit_data1=json_decode($edit_response1, true);
                    if($edit_data1['status']=="success")
                    {
                    	$spinned_edit_content = $edit_data1['uniqarticle'];
                    }
                    
                }
                else
                {
                    $spinned_edit_title = $afe_edit_campaign_check_result_detail[0]->title;
                    $spinned_edit_content = $afe_edit_campaign_check_result_detail[0]->long_desc;
                }
            }
            else
            {
                $spinned_edit_title = $afe_edit_campaign_check_result_detail[0]->title;
                $spinned_edit_content = $afe_edit_campaign_check_result_detail[0]->long_desc;
            }
            $vid_edit_link_option = "https://youtu.be/".get_option( 'vid_tmp_camp' );
            $post_edit_desc = $spinned_edit_content ."<br/><br/>".$ajax_edit_campaign_check_product_shortcode1."<br/><br/>".$vid_edit_link_option;
            $afe_edit_schedule_post_array = array(
				  'post_title'    => $spinned_edit_title,
				  'post_content'  => $post_edit_desc,
				  'post_status'   => 'draft',
				  'post_author'   => 1,
				);
				 
			// Insert the post into the database
			$afe_edit_schedule_post_id = wp_insert_post($afe_edit_schedule_post_array,true);

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