<?php
require_once INTENSE_PLUGIN_FOLDER . '/inc/Intense-photosource.php';

add_action( 'wp_ajax_intense_generic_post_action', 'intense_generic_post_action' );

function intense_generic_post_action() {
	global $shortcode_tag, $intense_post_types;

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	if ( !empty( $_POST["postType"] ) ) {
		check_ajax_referer( 'intense-plugin-noonce', 'security' );
		$post_type = strtolower( wp_filter_nohtml_kses( $_POST["postType"] ) );

		$post_type_info['post_type'] = $post_type;		

		$post_type_info['taxonomies'] = array();
		$taxonomy_names = get_object_taxonomies( $post_type, 'objects' );

		foreach ( $taxonomy_names as $taxonomy_name ) {
			$post_type_info['taxonomies'][] = array( 'key' => $taxonomy_name->name, 'value' => $taxonomy_name->label );
		}

		if ( !empty( $_POST["postTaxonomy"] ) ) {
			$taxonomy = strtolower( wp_filter_nohtml_kses( $_POST["postTaxonomy"] ) );
			$post_type_info['categories'] = array();
			$taxonomy_category = get_terms( $taxonomy );

			foreach ( $taxonomy_category as $taxonomy_cat ) {
				$post_type_info['categories'][] = array( 'key' => $taxonomy_cat->slug, 'value' => $taxonomy_cat->name );
			}
		}

		$post_type_info['templates'] = array();
		global $post, $wpdb;
		$templates_multi = array();
		$count = 0;

		$querystr = "
			SELECT $wpdb->posts.* 
			FROM $wpdb->posts
			WHERE $wpdb->posts.post_status = 'publish' 
			AND $wpdb->posts.post_type = 'intense_templates'
			ORDER BY $wpdb->posts.post_date DESC";

		$pageposts = $wpdb->get_results( $querystr, OBJECT );

		if ($pageposts) {
			foreach ( $pageposts as $template ) {
				$post = get_post( $template->ID );
				$type =  get_post_meta( $post->ID, 'intense_templates_post_type', true );
				$is_single = get_post_meta( $post->ID, 'intense_templates_type', true );

				if ( $type === str_replace( 'intense_', '', $post_type ) ) {
					if ( $is_single === 'multiple' ) {
						$templates_multi[ "template_" .  $post->ID ] = get_the_title();
					}
				}
			}
		}

		$templates = array_merge( intense_locate_available_plugin_templates( '/custom-post/post/' ),
			intense_locate_available_plugin_templates( '/custom-post/' . $post_type . '/' ), $templates_multi );

		foreach ( $templates as $key => $value ) {
			$image = intense_locate_plugin_template_image( '/custom-post/' . $post_type . '/' . $key );

			if ( !isset( $image ) ) {
				$image = intense_locate_plugin_template_image( '/custom-post/post/' . $key);
			}

			$post_type_info['templates'][] = array( "key" => $key, "value" => $value, "image" => $image );
		}

		$post_type_info['links'] = array(
			array( "key" => "none", "value" => __( "None", "intense" ) ),
			array( "key" => "single", "value" => __( "Single Post", "intense" ) )
		);

		if ( $post_type != 'page' ) {
			$post_type = $intense_post_types->get_post_type( $post_type );
			
			if ( is_null( $post_type ) ) {
				$links_array = array();
			} else {
				$links_array = $post_type->get_link_fields();
			}

			$post_type_info['links'] = array_merge( $post_type_info['links'], $links_array );
		}

		echo json_encode( $post_type_info );
	} 

	die();
}

add_action( 'wp_ajax_intense_recent_post_action', 'intense_recent_post_action' );

function intense_recent_post_action() {
	global $shortcode_tag, $intense_post_types;
	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	if ( !empty( $_POST["postType"] ) ) {
		check_ajax_referer( 'intense-plugin-noonce', 'security' );
		$post_type = strtolower( wp_filter_nohtml_kses( $_POST["postType"] ) );

		$post_type_info['post_type'] = $post_type;

		$post_type_info['taxonomies'] = array();
		$taxonomy_names = get_object_taxonomies( $post_type, 'objects' );

		foreach ( $taxonomy_names as $taxonomy_name ) {
			$post_type_info['taxonomies'][] = array( 'key' => $taxonomy_name->name, 'value' => $taxonomy_name->label );
		}

		if ( !empty( $_POST["postTaxonomy"] ) ) {
			$taxonomy = strtolower( wp_filter_nohtml_kses( $_POST["postTaxonomy"] ) );
			$post_type_info['categories'] = array();
			$taxonomy_category = get_terms( $taxonomy );

			foreach ( $taxonomy_category as $taxonomy_cat ) {
				$post_type_info['categories'][] = array( 'key' => $taxonomy_cat->slug, 'value' => $taxonomy_cat->name );
			}
		}

		$post_type_info['templates'] = array();

		$templates = array_merge( intense_locate_available_plugin_templates( '/recent-post/post/' ),
			intense_locate_available_plugin_templates( '/recent-post/' . $post_type . '/' ) );

		foreach ( $templates as $key => $value ) {
			$post_type_info['templates'][] = array( "key" => $key, "value" => $value );
		}

		$post_type_info['links'] = array(
			array( "key" => "none", "value" => __( "None", "intense" ) ),
			array( "key" => "single", "value" => __( "Single Post", "intense" ) )
		);

		$post_type = $intense_post_types->get_post_type( $post_type );

		foreach ( $post_type->fields as $key => $field ) {
			if ( $field['type'] === 'url' ) {
				$post_type_info['links'][] = array( "key" => $field['name'], "value" => $field['label'] );
			}
		}

		echo json_encode( $post_type_info );
	} 

	die();
}

add_action( 'wp_ajax_intense_widget_form_action', 'intense_widget_form_action' );
function intense_widget_form_action() {
	global $intense_shortcodes;

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );	

	if ( !empty( $_POST['widget'] ) ) {
		global $wp_widget_factory;	    

		$widget = $_POST['widget'];
	    
	    $widget_factory = $wp_widget_factory->widgets[ $widget ];
	    $widget_class = get_class( $widget_factory );
	    $widget_instance = new $widget_class( $widget_factory->id_base, $widget_factory->name, $widget_factory->widget_options );

	    $widget_settings = array();

	    echo '<form id="widget-form" style="padding: 10px; border: 1px solid #CCC; border-radius: 3px; margin: 10px 0; box-shadow: 0 0 3px #AAA;">'; 
	    echo $widget_instance->form( $widget_settings ); 
		echo '</form>';
	}

	die();
}

add_action( 'wp_ajax_intense_gallery_preview', 'intense_gallery_preview' );

function intense_gallery_preview() {
	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	check_ajax_referer( 'intense-plugin-noonce', 'security' );
	$attachments = null;
	$source = strtolower( wp_filter_nohtml_kses( $_POST["source"] ) );
	$user = wp_filter_nohtml_kses( $_POST["user"] );
	$groupid = wp_filter_nohtml_kses( $_POST["group"] );
	$tag = wp_filter_nohtml_kses( $_POST["tag"] );
	$setid = wp_filter_nohtml_kses( $_POST["set"] );
	$album = wp_filter_nohtml_kses( $_POST["album"] );
	$facebookpage = wp_filter_nohtml_kses( $_POST["facebookpage"] );
	$pagesize = wp_filter_nohtml_kses( $_POST["pagesize"] );
	$page = wp_filter_nohtml_kses( $_POST["page"] );

	if ( $source == 'wordpress' || $source == 'post_featured' ) {
		$postid = intval( wp_filter_nohtml_kses( $_POST["postid"] ) );
		$order = wp_filter_nohtml_kses( $_POST["order"] );
		$orderby = wp_filter_nohtml_kses( $_POST['orderby'] );
		$exclude = wp_filter_nohtml_kses( $_POST['excludedids'] );

		if ( $source == 'post_featured' ) {
			$include = intense_get_post_thumbnail_ids( $postid, null);
		} else {
			$include = wp_filter_nohtml_kses( $_POST['ids'] );
		}

		if ( 'RAND' == $order )
			$orderby = 'none';

		if ( !empty( $include ) ) {
			$_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );

			$attachments = array();
			foreach ( $_attachments as $key => $val ) {
				$attachments[$val->ID] = $_attachments[$key];
			}
		} elseif ( !empty( $exclude ) ) {
			$attachments = get_children( array( 'post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
		} else {
			$attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
		}
	}

	$photo_source = new Intense_Photo_Source( $source, $attachments, $user, ( $groupid ? $groupid : $tag ), ( $setid ? $setid : $album ), $facebookpage );
	$photos = $photo_source->get_photos( $pagesize, $page );

	if ( count( $photos ) > 0 ) {
		$output = "";
		foreach ( $photos as $photo ) {
			$photo_size = $photo->get_closest_size( 75, 75 );
			$output .= "<img src='" . $photo_size['sourceurl'] . "' title='" . esc_attr( $photo->title ) . "' alt='" . esc_attr( $photo->description ) . "' />";
		}
	} else {
		$output = __( "No Images Found", "intense" );
	}

	echo $output;	

	die();
}

add_action( 'wp_ajax_intense_image_preview_action', 'intense_image_preview_action' );

function intense_image_preview_action() {
	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	if ( !empty( $_POST["imageid"] ) ) {
		check_ajax_referer( 'intense-plugin-noonce', 'security' );
		$photo_info = wp_get_attachment_image_src( wp_filter_nohtml_kses( $_POST["imageid"] ), "thumbnail" );

		if ( !empty( $photo_info ) && !empty ( $photo_info[0] ) ) {
			$photo_url = $photo_info[0];
		} else {
			$photo_url = INTENSE_PLUGIN_URL . '/assets/img/missing_image.png';
		}

		echo $photo_url;
	}

	die();
}

add_action( 'wp_ajax_intense_shortcode_preview_action', 'intense_shortcode_preview_action' );

function intense_shortcode_preview_action() {
	check_ajax_referer( 'intense-plugin-noonce', 'security' );

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	$shortcode_class = $_POST['shortcode-class'];
	$shortcode_object = new $shortcode_class;

	// The dialog scripts need to be enqueued again because
	// jQuery will be included and will be reloaded undoing
	// any plugins that have been added onto jQuery.
	// jQuery gets loaded again because it is a dependency to a lot
	// of the assets.
	Intense_Shortcodes::enqueue_dialog_scripts();

	do_action( 'intense/preview/before' );

	echo '<ul class="nav nav-tabs">';

	if ( $shortcode_object->show_preview && empty( $shortcode_object->parent ) ) {
		echo '<li class="active"><a href="#previewcontent" data-toggle="tab">' . __( "Preview", 'intense' ) . '</a></li>';
	}

	echo '<li' . ( !$shortcode_object->show_preview? ' class="active"' : '' ) . '><a href="#previewcode" data-toggle="tab">' . __( "Shortcode", 'intense' ) . '</a></li>
		  </ul>
		  <div class="tab-content" style="border: 1px solid #ddd; border-top: none;">';

	if ( $shortcode_object->show_preview && empty( $shortcode_object->parent ) ) {
		echo '<div class="tab-pane active" id="previewcontent">';
		echo $shortcode_object->preview_wrapper_start;
		echo do_shortcode( str_replace( '\"', '"', $_POST['shortcode'] ) );
		echo $shortcode_object->preview_wrapper_end;
		echo '</div>';
	}

	echo '<div class="tab-pane' . ( !$shortcode_object->show_preview ? ' active' : '' ) . '" id="previewcode">';
	echo str_replace( '\"', '"', $_POST['shortcode'] );
	echo   '</div>
		</div>';

	do_action( 'intense/preview/after' );

	die();
}

// add_action( 'wp_ajax_intense_shortcode_save_action', 'intense_shortcode_save_action' );
// function intense_shortcode_save_action() {
// 	check_ajax_referer( 'intense-plugin-noonce', 'security' );

// 	// check for rights
// 	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
// 		die( __( "You are not allowed to be here" ) );

// 	$key = $_POST['key'];
// 	$shortcode_class = $_POST['shortcode-class'];
// 	$shortcode_object = new $shortcode_class;
// 	$shortcode_string = $_POST['shortcode'];
// 	$shortcode_string = str_replace( $shortcode_object->preview_content, '', $shortcode_string );
// 	$shortcode_string = str_replace( '\"', '"', $shortcode_string );

// 	$shortcode_object->save_preset( $key, $shortcode_string );

// 	die();
// }

// add_action( 'wp_ajax_intense_shortcode_remove_action', 'intense_shortcode_remove_action' );
// function intense_shortcode_remove_action() {
// 	global $intense_shortcodes;

// 	check_ajax_referer( 'intense-plugin-noonce', 'security' );

// 	// check for rights
// 	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
// 		die( __( "You are not allowed to be here" ) );

// 	$key = $_POST['key'];
// 	$shortcode = $intense_shortcodes->get_shortcode( $_POST['shortcode'] );
// 	$shortcode->remove_preset( $key );

// 	die();
// }

// add_action( 'wp_ajax_intense_shortcode_presets_action', 'intense_shortcode_presets_action' );
// function intense_shortcode_presets_action() {
// 	global $intense_shortcodes;

// 	check_ajax_referer( 'intense-plugin-noonce', 'security' );

// 	// check for rights
// 	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
// 		die( __( "You are not allowed to be here" ) );

// 	$shortcode = $intense_shortcodes->get_shortcode( strtolower( $_POST['shortcode'] ) );
// 	echo $shortcode->render_presets();

// 	die();
// }

add_action( 'wp_ajax_intense_shortcode_dialog_action', 'intense_shortcode_dialog_action' );
function intense_shortcode_dialog_action() {
	global $intense_shortcodes;

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	$shortcode = $intense_shortcodes->get_shortcode( $_GET['shortcode'] );

	if ( !empty( $_GET['preset'] ) ) {
		$shortcode->load_preset( $_GET['preset'] );
	}

	$is_skin_dialog = isset( $_GET['is_skin_dialog'] ) ? true : false;
	$skin_key = isset( $_GET['skin'] ) ? $_GET['skin'] : null;

	$shortcode->render_dialog( $is_skin_dialog, $skin_key );

	die();
}

add_action( 'wp_ajax_intense_load_snippets_action', 'intense_load_snippets_action' );
function intense_load_snippets_action() {
	check_ajax_referer( 'intense-plugin-noonce', 'security' );

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	$query = new WP_Query( array( 'post_type' => 'intense_snippets', 'nopaging' => 'true' ) );

	$snippets = array();

	$snippets['Saved in WordPress'] = array(
		'title' => 'Saved in WordPress',
		'snippets' => array()
	);

	while ( $query->have_posts() ) : $query->the_post();
		$id = get_the_ID();
		$title = get_the_title( $id );
		$content = get_the_content();

		$snippets['Saved in WordPress']['snippets'][] = array(			
			'id' => $id,			
			'title' => $title,
			'content' => $content
		);
	endwhile;

	$file_snippets = intense_locate_available_plugin_snippets();

	foreach ( $file_snippets as $snippet_location_name => $snippet_location ) {	
		$root = intense_get_snippet_location_path( $snippet_location_name );		

		foreach ( $snippet_location as $directory => $snippet_list ) {
			$location_key = $snippet_location_name . ( !empty( $directory ) ? ' - ' . $directory : '' );

			if ( !isset( $snippets[ $location_key ] ) ) {
				$snippets[ $location_key ] = array( 
						'title' => $location_key,
						'snippets' => array()
				);
			}

			foreach ($snippet_list as $snippet => $title) {				
				$snippet_path = $root . ( !empty( $directory) ? $directory . '/' : '' ) . $snippet . '.php';
				$content = intense_load_plugin_snippet( $snippet_path );

				$snippets[ $location_key ]['snippets'][] = array(
					'id' => $snippet_location_name . ' | ' . str_replace( '.php', '', str_replace( $root, '', $snippet_path ) ),					
					'title' => $title,
					'content' => $content
				);
			}	
		}
	}

	echo json_encode( $snippets );

	die();
}

add_action( 'wp_ajax_intense_shortcode_help_action', 'intense_shortcode_help_action' );

function intense_shortcode_help_action() {
	global $intense_shortcodes;

	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	if ( !empty( $_POST["shortcode"] ) ) {
		check_ajax_referer( 'intense-plugin-noonce', 'security' );
		$shortcode = $intense_shortcodes->get_shortcode( $_POST["shortcode"] );

		$info = $shortcode->to_documentation();

		echo '<div style="background: #F0EB61;font-size: 15px;border-radius: 5px 5px 0 0;padding: 10px;margin: -20px -20px 0; text-align:center">' . $shortcode->title . ' ' . __( 'Help', 'intense' ) . '</div>';
		
		if ( !empty( $shortcode->description ) ) {
			echo '<div style="font-size: 15px; margin: 25px 0;">' . $shortcode->description . '</div>';
		}

		$class_name = strtolower( get_class( $shortcode ) );

		echo '<h2>[' . $class_name . '] attributes</h2>' . $info;

		// get info for repeater fields and show them in a separate grid		
		$fields = $shortcode->get_fields();

		foreach ( $fields as $key => $field ) {
			if ( $field['type'] == 'repeater' ) {
				$repeater_shortcode = $intense_shortcodes->get_shortcode( 'intense_' . $key );

				$info = $repeater_shortcode->to_documentation();

				echo '<h2>[' . strtolower( get_class( $repeater_shortcode ) ) . '] attributes</h2>' . $info;
			}
		}

		// $docs_path = INTENSE_PLUGIN_FOLDER . '/inc/shortcodes/docs/' . str_replace( 'intense_', '', $class_name ) . '.md';

		// if ( file_exists( $docs_path ) ) {
		// 	$markdown = file_get_contents( $docs_path );

		// 	require_once INTENSE_PLUGIN_FOLDER . '/inc/libraries/parsedown/Parsedown.php';

		// 	$Parsedown = new Parsedown();

		// 	echo $Parsedown->text( $markdown );
		// }
	} 

	die();
}

add_action( 'wp_ajax_intense_icon_type_action', 'intense_icon_type_action' );

function intense_icon_type_action() {
	global $shortcode_tag;
	// check for rights
	if ( !current_user_can( 'edit_pages' ) && !current_user_can( 'edit_posts' ) )
		die( __( "You are not allowed to be here" ) );

	if ( !empty( $_POST["source"] ) ) {
		check_ajax_referer( 'intense-plugin-noonce', 'security' );

		$raw_icons = Intense_Icon::get_source_icons( $_POST["source"] );
		$results = array();
		$intense_icon = new Intense_Icon();
		$svg = '';

		foreach ($raw_icons as $key => $value) {
			$results['icons'][] = array(
				'text' => $value,
				'value' => $value,
				'svg' => $intense_icon->get_svg( $_POST["source"], $value, 'svg' )
			);

			//$svg .= $intense_icon->get_svg( $_POST["source"], $value );
		}

		$results['type_id'] = $_POST["type_id"];

		//$results['svg'] = '<svg>' . $svg . '</svg>';

		echo json_encode( $results );
	} 

	die();
}
