<?php
/**
 * Functions related to templates
 */

// Executes a plugin template and returns the content
function intense_load_plugin_template( $template_file, $args = null ) {
	ob_start();

	if ( isset( $template_file ) ) {
		if ( $args && is_array( $args ) ) {
			extract( $args );
		}

		include( $template_file );
	} else {
		?>
		<div>
		Unable to locate template file at one of the following locations in the order listed: <br />
			- <?php echo get_stylesheet_directory() . '/intense_templates';?>
			- <?php echo get_template_directory() . '/intense_templates'; ?>
			- <?php echo INTENSE_PLUGIN_FOLDER  . '/templates'; ?>
			<hr />
		</div>
		<?php 
	}

	$var = ob_get_contents();

	ob_end_clean();

	return $var;
}

function intense_get_template_search_paths() {
	$search_paths = array(
		'child-theme' => array( 
			'path' => get_stylesheet_directory() . '/intense_templates',
			'url' => get_stylesheet_directory_uri() . '/intense_templates'
		),
		'theme' => array( 
			'path' => get_template_directory() . '/intense_templates',
			'url' => get_template_directory_uri() . '/intense_templates'
		)
	);	

	$search_paths = apply_filters( 'intense/templates/search_paths', $search_paths );

	// Search Intense last
	$search_paths['intense'] = array(
		'path' => INTENSE_PLUGIN_FOLDER  . '/templates',
		'url' => INTENSE_PLUGIN_URL . '/templates'
	);

	return $search_paths;
}

// Checks available paths for the plugin template file
function intense_locate_plugin_template( $template_name ) {
	$search_paths = intense_get_template_search_paths();

	foreach ( $search_paths as $key => $search_path ) {
		if ( is_array( $search_path ) ) {
			$search_path_base = $search_path['path'];
		} else {
			$search_path_base = $search_path;
		}

		if ( file_exists( $search_path_base . $template_name ) ) {
			return $search_path_base . $template_name;
		}
	}

	return null;
}

// Checks available paths for the plugin template image file and return URL
function intense_locate_plugin_template_image( $template_name ) {
	$search_paths = intense_get_template_search_paths();

	foreach ( $search_paths as $key => $search_path ) {
		if ( is_array( $search_path ) ) {
			$search_path_base = $search_path['path'];
		} else {
			$search_path_base = $search_path;
		}	

		if ( file_exists( $search_path_base . $template_name . '.jpg') ) {
			if ( is_array( $search_path ) ) {
				$search_path_url = $search_path['url'];		

				return $search_path_url . $template_name . '.jpg';
			} 			
		}
	}
	
	return null;
}

function intense_get_plugin_template_name( $path ) {
	$content = file_get_contents( $path );

	$lines = explode( "\n", $content);

	foreach ( $lines as $line ) {
		$remove_template_start_text =  str_replace( "Intense Template Name:", "", $line );

		// early terminate if name found
		if ( $remove_template_start_text != $line ) {
			return trim( $remove_template_start_text );
		}
	}

	return str_replace( ".php", "", substr( $path, strrpos( $path, "/" ) + 1 ) );
}

/**
 * Loads a template and returns its resulting content
 * @param  number/string/array $template the path and name of the template. If numeric, it will try to load the 
 * @param  array $args arguments to send to the template
 * @return [type]           [description]
 */
function intense_get_template( $template, $args = null ) {		
	if ( is_numeric( str_replace("template_", "", $template ) ) ) {
		require INTENSE_PLUGIN_FOLDER . '/custom-post-types/templates/templates.php';

		$template_post = get_post( str_replace("template_", "", $template ) );
		$template_file = Intense_Post_Type_Templates::get_template_cache( $template_post->ID );
	} else if ( is_array( $template ) ) {
		foreach ($template as $key => $value) {
			$template_file = intense_locate_plugin_template( $value );

			if ( !empty( $template_file ) ) {
				break;
			}
		}	
	} else {
		$template_file = intense_locate_plugin_template( $template );
	}

	if ( !empty( $template_file ) ) {
		return intense_load_plugin_template( $template_file, $args );
	} else {
		return null;
	}	
}

function intense_locate_single_cpt_templates( $template_type, $single = false ) {
    global $wpdb;
    $templates = array();
    $count = 0;

 	if ( false === ( $pageposts = wp_cache_get( 'intense_single_cpt_templates' ) ) ) {
	    $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 );

    	wp_cache_set( 'intense_single_cpt_templates', $pageposts );
	}

    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 === $template_type ) {
				if ( $single && $is_single === 'single' ) {
					$templates[ "template_" .  $post->ID ] = get_the_title($post->ID);
				} elseif ( !$single && $is_single === 'multiple' ) {
					$templates[ "template_" .  $post->ID ] = get_the_title($post->ID);
				}        
	        }

      	endforeach;
    endif;

  	return $templates;
}

function intense_locate_available_plugin_templates( $relative_path ) {
	$plugin_files = array();
	$theme_files = array();
	$child_theme_files = array();
	$templates = array();

	$search_paths = array(
		'child-theme' => get_stylesheet_directory() . '/intense_templates',
		'theme' => get_template_directory()  . '/intense_templates',		
	);

	$search_paths = apply_filters( 'intense/templates/search_paths', $search_paths );

	// Search Intense last
	$search_paths['intense'] = INTENSE_PLUGIN_FOLDER  . '/templates';

	foreach ( $search_paths as $key => $search_path ) {
		if ( file_exists( $search_path . $relative_path ) ) {
			$plugin_files = scandir( $search_path . $relative_path );
			$plugin_files = array_flip( $plugin_files );

			foreach ( $plugin_files as $key => &$value ) {
				if ($key != '.' && $key != '..' && substr( $key, -strlen( ".php" )) == ".php" ) {
					$value = intense_get_plugin_template_name( $search_path . $relative_path . $key );
					$templates[ str_replace( ".php", "", $key ) ] = $value;
				}
			}
		}
	}

	natsort( $templates );

	return array_filter( $templates );
}