<?php
/*
Plugin Name: Custom Metaboxes for Core

*/

class WP_Meta_Box {
	/**
	 * The screen where the meta box will be shown.
	 */
	public $screen;

	/**
	 * A unique slug to allow multiple meta boxes of the same class
	 * to exist on the same screen.
	 */
	public $slug;

	/**
	 * A unique identifier for the meta box.
	 *
	 * A string composed from the meta box class, screen, and slug.
	 */
	public $unique_id;

	/**
	 * Arguments passed to the meta box constructor.
	 */
	public $args;

	/**
	 * A registry that tracks each meta box instance.
	 */
	public static $registry;

	/**
	 * All registered meta 
	 */
	public $registered_meta;


	/**
	 * Constructor.
	 *
	 * Any subclasses MUST call parent::_construct( $screen, $args ).
	 *
	 * @param string $screen - The ID (string) for the screen where the meta box will be shown.
	 * @param array  $args - An array of supplied arguments. Optional.
	 *
	 * $args recognized by default:
	 *    title    - The title of the meta box.
	 *    context  - The context within the page where the box should show ('normal', 'advanced').
	 *    priority - The priority within the context where the boxes should show ('high', 'low').
	 *    slug     - A unique string to identify the meta box.
	 */
	public function __construct( $screen, $args = array() ) {
		// Set variables
		$this->screen = $screen;
		$this->slug   = empty( $args['slug'] ) ? '' : $args['slug'];

		// Remove slug from args
		unset( $args['slug'] );

		// Set default args
		$defaults = array(
			'title'         => __( 'Untitled' , 'wordcampbase'),
			'context'       => 'side',
			'priority'      => 'default',
		);
		$this->args = wp_parse_args( $args, $defaults );

		// Add the meta box to the registry.
		// Generates a slug if one doesn't already exist.
		WP_Meta_Box::registry()->add( $this );

		// Construct the meta box's unique ID.
		$this->unique_id = get_class( $this ) . "_{$this->screen}_{$this->slug}";

		// Bind hooks
		add_action( 'admin_init',            array( $this, '_register' ) );
		add_action( 'admin_enqueue_scripts', array( $this, '_enqueue_scripts' ) );
	}

	/**
	 * Fetches the meta box registry.
	 */
	public static function registry() {
		if ( ! isset( WP_Meta_Box::$registry ) )
			WP_Meta_Box::$registry = new WP_Meta_Box_Registry();
		return WP_Meta_Box::$registry;
	}

	/**
	 * Remove the meta box.
	 */
	public function remove() {
		// Make sure we've removed any data from the registry.
		WP_Meta_Box::registry()->remove( get_class( $this ), $this->screen, $this->slug );

		// Unbind actions.
		remove_action( 'admin_init',            array( $this, '_register' ) );
		remove_action( 'admin_enqueue_scripts', array( $this, '_enqueue_scripts' ) );
	}

	/**
	 * Render the meta box. Implement in a subclass.
	 */
	protected function render() {}

	/**
	 * Save the meta box. Implement in a subclass.
	 */
	protected function save() {}

	/**
	 * Fires when the meta box is registered. Override in a subclass.
	 */
	protected function register() {}

	/**
	 * Enqueue meta box scripts. Override in a subclass.
	 */
	protected function enqueue_scripts() {}

	/**
	 * Determine whether the meta box will be saved. Override in a subclass.
	 *
	 * Return true to save, false to cancel.
	 */
	protected function maybe_save( $post_id, $post ) {
		// Bail if we're autosaving
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
			return;

		// @TODO Add revision check

		// Cap check
		if ( ! current_user_can( 'edit_post', $post_id ) )
			return;

		return true;
	}

	/**
	 * Add an action to trigger save.
	 *
	 * Due to the different types of meta boxes, save will not be triggered by default.
	 */
	public function add_save_action( $name, $priority = 10 ) {
		add_action( $name, array( $this, '_save' ), $priority, 99 ); // Effectively infinite args.
	}

	/**
	 * Remove a save action.
	 */
	public function remove_save_action( $name, $priority = 10 ) {
		remove_action( $name, array( $this, '_save' ), $priority, 99 ); // Effectively infinite args.
	}

	public function register_meta( $meta_key, $args_array = array() ) {
		$defaults = array( 'field_type' => 'text', 'default_display' => true, 'title_label' => $meta_key, 'attrs' => array() );

		$args_array = wp_parse_args($args_array, $defaults);
		
		// export array as variables
		extract($args_array);
		// var_dump($title_label);
		$this->registered_meta[] = array( 'meta_key' => $meta_key, 'default_display' => $default_display, 'title_label' => $title_label, 'field_type' => $field_type, 'attrs' => $attrs );
	}

	/* =====================================================================
	 * INTERNAL FUNCTIONS
	 * ===================================================================== */

	/**
	 * Internal function. Registers the meta box.
	 */
	public final function _register() {
		$id = "{$this->unique_id}-meta-box";

		add_meta_box( $id, $this->args['title'], array( $this, '_render' ),
			$this->screen, $this->args['context'], $this->args['priority'],
			$this->args );

		$this->register();
	}

	/**
	 * Internal function. Ensures scripts are only loaded when necessary.
	 */
	public final function _enqueue_scripts() {
		$current_screen = get_current_screen();

		if ( isset( $current_screen ) && $this->screen == $current_screen->id )
			$this->enqueue_scripts();
	}

	/**
	 * Internal function, initiates the rendering process.
	 */
	public final function _render( $object, $box ) {
		wp_nonce_field( "{$this->unique_id}_nonce", "_wpnonce_{$this->unique_id}", false );
		
		// Render registered meta boxes with default_display set to true 
		foreach ( $this->registered_meta as $meta )
			if ( $meta['default_display'] )
				$this->_render_form_field( $meta );

		$this->render();
	}

	/**
	 * Internal function, initiates the saving process.
	 */
	public final function _save() {
		global $post;
		// Nonce check (sorry, you don't have a choice about this one).
		check_admin_referer( "{$this->unique_id}_nonce", "_wpnonce_{$this->unique_id}" );

		$args = func_get_args();

		// Only save if maybe_save returns true.
		if ( call_user_func_array( array( $this, 'maybe_save' ), $args ) ) {

			// Save registered meta boxes
			foreach ( $this->registered_meta as $meta )
				if ( $_REQUEST[$meta['meta_key']] )
					update_post_meta( $post->ID, $meta['meta_key'], $_REQUEST[$meta['meta_key']] );

			call_user_func_array( array( $this, 'save' ), $args );
		}
			
	}

	public function _render_form_field( $args ) {
		global $post;
		extract($args);
		$value = get_post_meta($post->ID, $meta_key, true );

		echo "<h4>$title_label</h4>";
		switch( $field_type ) {
			case 'text' :
				$value = get_post_meta($post->ID, $meta_key, true);
				echo "<input type='text' name='$meta_key' value='$value'>";
			break;
		}	
	}

}



/**
 * Meta Box Registry
 *
 * Implemented as singleton
 *
 */
class WP_Meta_Box_Registry {

	/**
	 * WP_Meta_Box_Registry singleton implementation
	 *
	 * @var WP_Meta_Box_Registry
	 */
	private static $instance;

	private $instances = array();

	/**
	 * WP_Meta_Box_Registry singleton implementation
	 *
	 * @return WP_Meta_Box_Registry
	 */
	public static function instance() {
		if (null === self::$instance)
			self::$instance = new self();
		return self::$instance;
	}

	/**
	 * Search registry for meta box instances
	 *
	 * @return array result
	 */
	public function search($class_or_object, $screen = false, $slug = false) {
		$instances = array();

		foreach($this->instances as $instance) {

			if ( ! $instance instanceof $class_or_object )
				continue;

			if ( $screen !== false && $instance->screen !== $screen )
				continue;

			if ( $slug !== false && $instance->slug !== $slug )
				continue;

			$instances[] = $instance;
		}

		return $instances;
	}

	/**
	 * Adds a meta box instance.
	 *
	 * If $instance->slug is defined, will use $slug.
	 * If a meta box with the same slug exists, it will be overwritten.
	 *
	 * @param WP_Meta_Box $instance
	 */
	public function add( WP_Meta_Box $instance ) {
		static $counter = 0;

		$hash = spl_object_hash( $instance );

		if ( !empty( $instance->slug ) ) {
			// If slug is specified, remove existing instance
			$instances = $this->find($instance, $instance->screen, $instance->slug);

			if ($instances) 
				$this->remove($instances[0]);

		} else {
			// If no slug is specified, get the numerical index.
			// alternatively get the number of this instances' class by screen and count plus one.
			$instance->slug = ++$counter;
		}

		$this->instances[ $hash ] = $instance;
	}

	// in case this is still needed.
	public function get( WP_Meta_Box $instance ) {
		$hash = spl_object_hash( $instance );

		if ( isset( $this->instances[ $hash ] ) )
			return $instance;

		return false;
	}

	/**
	 * Remove instance from registry
	 *
	 * @param WP_Meta_Box $instance
	 */
	public function remove( WP_Meta_Box $instance ) {
		$hash = spl_object_hash( $instance );

		if ( isset( $this->instances[ $hash ] ) )
			unset( $this->instances[ $hash ] );
	}
}

class WP_Basic_Meta_Box extends WP_Meta_Box {
	function __construct( $screen, $args = array() ) {
		// Call the WP_Meta_Box constructor.
		parent::__construct( $screen, $args );

		// Save the meta box contents when 'save_post' is triggered.
		$this->add_save_action( 'save_post' );
		$this->register_meta( 'test_form_field' );
	}
}

$a = new WP_Basic_Meta_Box( 'post', array( 'title' => 'Basic Meta Box' ) );

class WP_Basic_Meta_Box_with_Custom_Render extends WP_Meta_Box {
	function __construct( $screen, $args = array() ) {
		// Call the WP_Meta_Box constructor.
		parent::__construct( $screen, $args );

		// Save the meta box contents when 'save_post' is triggered.
		$this->add_save_action( 'save_post' );
		$this->register_meta( 'test_form_field', array( 'default_display' => false, 'title_label' => 'test' ) );
	}

	function render() {
		echo 'custom meta box form rendering here';
	}
}

$b = new WP_Basic_Meta_Box_with_Custom_Render( 'post', array( 'title' => 'Basic Meta Box with Custom Form rendering' ) );