<?php

class Intense_Metadata extends Intense_Shortcode {

	function __construct() {
        parent::__construct();

		global $intense_visions_options;
		global $post;

		$this->title = __( 'Post Meta Data', 'intense' );
		$this->description = __( 'Easily add post metadata to your WordPress post and pages using the Metadata Shortcode. If no data is found, the shortcode will fall back to a supplied text.', 'intense' );
		$this->category = __( 'Posts', 'intense' );
		$this->show_preview = true;		
	}

	function shortcode( $atts, $content = null ) {
		global $intense_visions_options;
		extract( shortcode_atts( $this->get_shortcode_defaults( null, $atts ), $atts ) );

		if ( empty( $type ) ) $type = 'field';

		switch ( $type ) {
			case 'field':
				return $this->get_metadata_field( $post, $meta_key, $fallback );
				break;			
			case 'template':
				return $this->get_metadata_template( $post, $template, array_merge( $this->get_shortcode_defaults( null, $atts ), $atts ) );
				break;
		}
	}

	function get_metadata_field( $post, $meta_key, $fallback ) {
		if ( empty( $post ) ) {
			$post = get_the_ID();
		}

		if ( empty( $post ) ) {
			return "Error: a post must be specified";
		}

		$data = get_post_meta( $post, $meta_key, true );

		if ( empty($meta_key) ) {
			return "Error: a key must be specified. Use one of the following: <hr>" . implode( '<br>', array_filter( array_keys( $data ), array( __CLASS__, 'filter_intense_keys' ) ) );
		}

		if ( empty( $data ) ) {
			$data = $fallback;
		}

		return $data;
	}

	function get_metadata_template( $post, $template, $atts ) {
		global $intense_metadata;

		unset( $atts['post'] );
		unset( $atts['type'] );
		unset( $atts['meta_key'] );
		unset( $atts['fallback'] );

		$date_format = isset( $atts['date_format'] ) ? $atts['date_format'] : null;
		$intense_metadata = array_merge( intense_get_post_metadata( $post, $date_format ), $atts );

		return intense_get_template( '/metadata/' . $template . '.php' );
	}

	function filter_intense_keys( $var ) {
		return substr($var, 0, 8) !== '_intense';
	}
}
