<?php
/**
 * The MAIN FUNCTIONS FILE for SKT Education Lite
 *
 * Stores all the Function of the template.
 *
 * @package SKT Education Lite
 * 
 * @since SKT Education Lite 1.0
 */

//**************Complete Golbal******************//
/*CHECK IF Complete row exist in the wp_options table. Needed for Redux Conversion process*/ 
$completedb = get_option( 'complete' );

//**************Complete SETUP******************//
function Complete_setup() {
	//add_theme_support( 'custom-header' );
	add_theme_support( 'title-tag' );			//WP 4.1 Site Title
	add_theme_support( 'woocommerce' );			//Woocommerce Support
	add_theme_support('automatic-feed-links');	//RSS FEED LINK
	add_theme_support( 'post-thumbnails' );		//Post Thumbnail
	//Custom Background	
	add_theme_support( 'custom-background', array( 'default-color' => 'ffffff') );	
	//Make theme available for translation
	load_theme_textdomain('complete', get_template_directory() . '/languages/');  
	//Custom Thumbnail Size	
	/*add_image_size( 'complete_thumb', 400, 270, true );*/ /*(cropped)*/
	add_image_size( 'complete_thumb', 300, 300, false ); /*(cropped)*/
	add_image_size( 'complete_medium', 700, 387, true ); /*(cropped)*/
	add_image_size( 'footerthumb', 50, 42, false ); 
   
	//Register Menus
	register_nav_menus( array(
			'primary' => __( 'Header Navigation', 'complete' ),
			'footer' => __( 'Footer Navigation', 'complete' ),
		) );
	}
add_action( 'after_setup_theme', 'Complete_setup' );

//**************Complete FUNCTIONS******************//
require(get_template_directory() . '/sktframe/core-functions.php');			//Include Complete sktframe Core Functions 
require(get_template_directory() . '/lib/functions/core.php');					//Include Core Functions
require(get_template_directory() . '/lib/functions/enqueue.php');					//Include Enqueue CSS/JS Scripts
require(get_template_directory() . '/lib/functions/admin.php');				//Include Admin Functions (admin)
require(get_template_directory() . '/lib/functions/woocommerce.php');			//Include Woocommerce Functions
require(get_template_directory() . '/lib/functions/defaults.php');
require(get_template_directory() . '/customizer/customizer.php');
require(get_template_directory() . '/lib/functions/converter.php');
require(get_template_directory() . '/lib/includes/google_fonts.php');

//WIDGETS
require(get_template_directory() . '/sktframe/core-posts.php');		
require(get_template_directory() . '/sktframe/core-pagination.php');


define('SKT_THEME_DOC', 'http://sktthemesdemo.net/documentation/lms-documentation/','complete');
define('SKT_URL','https://www.sktthemes.net','complete');
define('SKT_PRO_THEME_URL','https://www.sktthemes.net/shop/lms-wordpress-theme/','complete');
define('SKT_LIVE_DEMO','http://sktperfectdemo.com/demos/education/','complete');
define('SKT_THEMES','https://www.sktthemes.net/themes/','complete');

require_once get_template_directory() . '/customize-pro/example-1/class-customize.php';

/*Custom template for about theme. */
require get_template_directory() . '/sktframe/about-themes.php';
//add_post_type_support( 'news', 'thumbnail' ); 
add_post_type_support( 'gallery', 'thumbnail' );
add_post_type_support( 'video-gallery', 'thumbnail' );
function create_posttype() { 
 register_post_type( 'gallery',
     array(

            'labels' => array(
                'name' => __( 'Gallery' ),
                'singular_name' => __( 'gallery' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'gallery')            
        )
    );
    register_post_type( 'video-gallery',
     array(

            'labels' => array(
                'name' => __( 'Video Gallery' ),
                'singular_name' => __( 'video-gallery' ),
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'video-gallery')            
        )
    );
}
add_action( 'init', 'create_posttype' );

function vipx_remove_cpt_slug( $post_link, $post, $leavename ) {
 
    if ( ! in_array( $post->post_type, array( 'gallery' ,'video-gallery') ) || 'publish' != $post->post_status )
        return $post_link;

   /* if (in_array( $post->post_type, array( 'gallery') ))
		$post_link = str_replace( '/' . $post->post_type . '/', '/gallery/', $post_link );
	else
		$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );*/
 
    return $post_link;
}
add_filter( 'post_type_link', 'vipx_remove_cpt_slug', 10, 3 );
 
function vipx_parse_request_tricksy( $query ) {
 
    // Only noop the main query
    if ( ! $query->is_main_query() )
        return;
 
    // Only noop our very specific rewrite rule match
    if ( 2 != count( $query->query )
        || ! isset( $query->query['page'] ) )
        return;
 
    // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match
    if ( ! empty( $query->query['name'] ) )
        $query->set( 'post_type', array( 'post', 'activity-gallary', 'page' ) );
}
add_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );

function home_news() { 
$args = array(
	'post_type' => 'post',
	'posts_per_page' => '3',
	'order' => 'DESC'
	);
	  $my_posts1 = new WP_Query( $args );
ob_start(); ?>
 <div class="media-posts">
  <?php while ( $my_posts1->have_posts() ) : $my_posts1->the_post() ?>
	<div class="gal-col all">
     <div class="pic-section">
		 <a class="read-more" href="<?php the_permalink();?>"><?php the_post_thumbnail( 'medium_large' );?></a>
       </div>
         <div class="text-box">
            <a class="read-more" href="<?php the_permalink();?>"><h3 class="sub-heading"><?php the_title();?></h3></a>
            <div class="news_date"><?php echo get_the_date();?></div>
            <a class="read-more" href="<?php the_permalink();?>">Read More</a>                           
           </div>
        </div>
 	<?php endwhile;
 	   wp_reset_query();?>

    
</div>
<?php $content =  ob_get_clean();
    return $content;
     
}
add_shortcode("home_news", "home_news");
if ( function_exists( 'acf_add_options_page' ) ) {
	acf_add_options_page( 'Global Settings' );
}

function do_this_hourly_calendar(){
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,"https://api.uniqueschoolapp.ie/feeds/calendar?idschool=218&sort_order=asc&limit=9999");
	curl_setopt($ch,CURLOPT_HEADER,0);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_TIMEOUT,40);
	$response = curl_exec($ch);
	curl_close($ch);
	
	$events = json_decode($response);
	ob_start();
	
	var_dump($events);
	$args = array(
        'post_type'      => 'event',
        'posts_per_page' => -1
    );
     $posts = get_posts( $args );
    foreach ( $posts as $post ) {
		  $my_post = array(
		  'ID'           => $post->ID,
		  'post_status'    => 'draft',
		);
    //  wp_update_post( $my_post );
    }
    
    foreach ($events->data->calendar AS $event) {
		//$gallery_data == array();
		$post_array = $event_keys = array();
		$found_post = false;
					
		$found_post = post_exists( $event->title,'',$event->created_date,'event');
        if(!$found_post) {
			
			$post_array = array(
					'post_author' => 1,
					'post_content' => $event->description,  // content of the article,
					'post_title' => $event->title,
					'post_date' => $event->created_date,
					'post_status' => 'publish',   // i just published the post directly, but you can change the status as of your need
					'post_type' => 'event'  // if any custom post type, you can use it here
				);
			//echo "==";
			echo $starttime = ($event->start_time!='')?trim($event->start_time):'00:00:00';
			//echo "==";
			echo $endtime = ($event->end_time!='')?trim($event->end_time):'23:00:00';
			//echo "==";
			$start	= new DateTime( $event->start_date.' '.$starttime);
			$end 	= new DateTime( $event->end_date.' '.$endtime );		
			
			$event_data = array(
				'schedule' => 'once',
				'all_day' => '',
				'start' => $start,
				'end' => $end,
				);
			$new_cat_id = '';
			echo "<br/>category data :";
			echo $new_category_name = ($event->category->name)?$event->category->name:''; 
			echo "==data end<br/>";
			$category_color= ($event->color!='')?$event->color:''; 
			if(!empty($new_category_name)){
				if( !get_term_by( 'name', $new_category_name, 'event-category' ) ){
					$new_cat = wp_insert_term( $new_category_name, 'event-category', array('colour' => $category_color ) );
					echo '<pre>';
					print_r($new_cat);
					echo '</pre>';
			
					if( !is_wp_error( $new_cat ) && $new_cat ){
						$new_cat_id = $new_cat['term_id'];
						$re = update_option( "eo-event-category_{$new_cat_id}", array( 'colour' => $category_color ) );
					}
				}
			}
			$cat = get_term_by( 'name', $new_category_name, 'event-category' );
			if( $cat )
				$post_array['tax_input']['event-category'][] =  intval( $cat->term_id );
							
			echo '<pre>';
			print_r($event_data);
			echo '</pre>';
			$event_post_id = eo_insert_event($post_array,$event_data);
			echo "==event id ==".$event_post_id . "==<br/>";
		}
		else
		{
			 wp_update_post(array(
				'ID'    =>  $found_post,
				'post_status'   =>  'publish'
				));
				echo "event already exixts<br/>";
		}
	}
	$args = array(
        'post_type'      => 'event',
        'post_status'    => 'draft',
        'posts_per_page' => -1
    );
     $posts = get_posts( $args );
    foreach ( $posts as $post ) {
		  $my_post = array(
		  'ID'           => $post->ID,
		  'post_status'    => 'trash',
		);
     // wp_update_post( $my_post );
    }
    $log_data = ob_get_clean();
	set_transient( 'my_plugin_log', $log_data, 24 * HOUR_IN_SECONDS );

}
add_action( 'calendar_event', 'do_this_hourly_calendar' );

add_action( 'gallery_event', 'do_this_hourly' );
function do_this_hourly() {
	//$url = 'https://api.uniqueschoolapp.ie/feeds/gallary?idschool=220';
	$ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://api.uniqueschoolapp.ie/feeds/gallary?idschool=218");
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_TIMEOUT,40);
        
        
	
	$response = curl_exec($ch);
	 curl_close($ch);
	
	create_posts($response);
	wp_die();    
}
function create_posts($response){
	$galleries = json_decode($response, true);
ob_start();

	
	foreach ($galleries['data']['albums'] AS $gallery) {
		var_dump( $gallery );
		$gallery_data == array();
		$found_post = post_exists( $gallery['title'],'','','gallery');
        if(!$found_post) {
			$postdate = date("Y-m-d H:i:s", $gallery['datee']);
			$gallery_post_id = wp_insert_post(
				array(
					'post_author' => 1,
					'post_content' => $gallery['description'],  // content of the article,
					'post_title' => $gallery['title'],
					 'post_date'=> $postdate,  // title of the article
					'post_status' => 'publish',   // i just published the post directly, but you can change the status as of your need
					'post_type' => 'gallery'  // if any custom post type, you can use it here
				)
			);
			$gallery_data['gallery_id'] = $gallery['id'];

			update_post_meta($gallery_post_id, 'gallery_data', $gallery_data);
			
			$image_url = $gallery['thumbnil'];

			$file = array();
			$file['name'] = wp_basename($image_url);
			$file['tmp_name'] = download_url($image_url);

			$attachmentId = media_handle_sideload($file, $gallery_post_id);
			wp_update_attachment_metadata( $attachmentId, $file );
			 
			set_post_thumbnail( $gallery_post_id, $attachmentId );
			if ( is_wp_error($attachmentId) ) {
				@unlink($file['tmp_name']);
				echo "Could not do media_handle_sideload";
			}

			$galleries_img = $gallery['content'];
			$counter = 0;
			$items = array();
			$value = array();
			foreach ($galleries_img AS $gallery_media) {
					$gallery_media == array();
					
					$file1 = array();
					$file1['name'] = wp_basename($gallery_media['url']);
					$file1['tmp_name'] = download_url($gallery_media['url']);

					echo $attachmentIds = media_handle_sideload($file1, 0);
					 
						$image_name	= "images_".$counter."_gallery_image";
						$items['\''.$image_name.'\''] = $attachmentIds;
						$value[] = array( 'field_5f69d9a898341' => $attachmentIds );
						$counter++;
					
				}
			   
			update_field( 'field_5f69d99298340', $value, $gallery_post_id );
		}
		else
		{
			 wp_update_post(array(
				'ID'    =>  $found_post,
				'post_status'   =>  'publish'
				));
		}
	}
}
/*
$log_data = ob_get_clean();
set_transient( 'my_plugin_log', $log_data, 24 * HOUR_IN_SECONDS );
}
*/

/*
 * Produce the log reports
 */
 /*
function my_log_report()
{
        echo "<h1>Log Viewer</h1>";
        echo '<pre class="logs">'. get_transient( 'my_plugin_log' ).'</pre>';
}
add_submenu_page( 'edit.php', 'Log Viewer', 'View Logs', 'manage_options', 'my-post-logs', 'my_log_report' );

*/

add_action('wp_enqueue_scripts', function(){
	// Register first the ajax.js script
	//wp_enqueue_script('handle_of_script', 'link/to/ajax.js');

	// Now send variable to the script
	wp_localize_script('handle_of_script', "Object_var", [
		"ajax_url_attr" => admin_url( 'admin-ajax.php' )
	]);
});
add_action( 'wp_ajax_nopriv_myfilter_event', 'myfilter_event' );
add_action( 'wp_ajax_myfilter_event', 'myfilter_event' );
function myfilter_event(){ 

	$filter_req = $_POST['filter_req'];

	// Run filter of whatever
	if(!empty($filter_req)){
		$events = eo_get_events(array(
				 'numberposts'=>100,
				 'event_start_after'=>'today',
				 'showpastevents'=>false,
				 'tax_query'=>array( array(
					  'taxonomy'=>'event-category',
					  'operator' => 'IN',
					  'field'=>'slug',
					  'terms'=>array($filter_req)
					  ))));
	}
	else{
		$events = eo_get_events(array(
					  'numberposts'=>100,
					  'event_start_after'=>'today',
					  'showpastevents'=>false,//Will be deprecated, but set it to true to play it safe.
				 ));
	}	// Convert values to html/text
	$html_text = convert_to_html_text($events);
	$atts['event_category'] = $filter_req;
	$calendar_text = eo_get_event_fullcalendar($atts);
	//$calendar_text = do_shortcode( '[eo_fullcalendar category='.$filter_req.']' );
$return = array('html_text' => $html_text,'calendar_text' => $calendar_text);
 //$result = json_encode($return);
  // echo $result;
   //die();

	// Send data to jQuery AJAX
	wp_send_json($return);

	wp_exit();
};

function convert_to_html_text($events) {
	
	$html_text = "";

	ob_start();
		// Maybe check if query is valid or have post ...
	
		if($events){?>
							  <ul>
							<?php  foreach ($events as $event):
								   //Check if all day, set format accordingly
								   $format = ( eo_is_all_day($event->ID) ? get_option('date_format') : get_option('date_format').' '.get_option('time_format') );
								   $circle_color	= (!empty(eo_get_event_color($event->ID)))?eo_get_event_color($event->ID):'#007DC3';
								   ?>
									<li>
										<span class="color_circle" style="background-color:<?php echo $circle_color;?>">&nbsp;</span>
										<a href="<?php echo get_permalink($event->ID);?>"> <?php echo get_the_title($event->ID);?></a>
										<br/> 
										<span class="calendar"></span> 
										<?php echo eo_get_the_start( $format, $event->ID, $event->occurrence_id );?> 
									</li>  
								<?php
							  endforeach; ?>
							  </ul>
							  <?php }
							  else{ ?>
							  <ul>
									<li>No Incoming Event.</li>
							  </ul>
							  <?php };
	
	$html_text = ob_get_clean();

	return $html_text;
}

function eo_assign_default_event_color( $color, $event_id ){
    if( empty( $color ) ){
        $color = '#0D3216'; //rust
    } 
    return $color;
}

add_filter( 'eventorganiser_event_color', 'eo_assign_default_event_color', 10, 2 );
function my_error_notice() { ?>
<div class="error notice">
<p><?php _e( 'For More Options buy pro version <a href="https://www.sktthemes.net/shop/lms-wordpress-theme/" target="_blank">Buy Now</a>', 'complete');?></p>
</div>
<?php } add_action( 'admin_notices', 'my_error_notice' );
