<?php

/**
* 
*/
class Phosphor_Meta_Framework
{
	
	function __construct()
	{
		$this->load_dependencies();

		$this->form 		= new Phosphor_Backend_Form();
		$this->metaboxes 	= $this->get_metaboxes();
		$this->fields 		= $this->get_fields();

		$this->register_hooks();
	}

	function set_metabox_default($metabox) {
		$defaults = array(
			'title' 	=> '',
			'screen' 	=> null,
			'context' 	=> null,
			'priority' 	=> null
		);

		return wp_parse_args($metabox, $defaults);
	}

	function load_dependencies() {
		require_once 'class.backend-form.php';
	}

	function register_hooks() {
		add_action( 'load-post.php', array($this, 'setup_metaboxes') );
		add_action( 'load-post-new.php', array($this, 'setup_metaboxes') );
	}

	function setup_metaboxes() {
		/* Add meta boxes on the 'add_meta_boxes' hook. */
		add_action( 'add_meta_boxes', array($this, 'add_metaboxes') );

		/* Save post meta on the 'save_post' hook. */
		add_action( 'save_post', array($this, 'save_meta'), 10, 2 );
	}

	function add_metaboxes() {
		foreach ($this->metaboxes as $key => $metabox) {

			$metabox = $this->set_metabox_default($metabox);

			add_meta_box(
				$key,
				$metabox['title'],
				array($this, 'metabox_callback'),
				$metabox['screen'],
				$metabox['context'],
				$metabox['priority'],
				array(
					'id' => $key
				)
			);
		}
	}

	function metabox_callback($post, $args) {
		$meta = get_post_meta($post->ID, $args['id'], true);

		foreach ($this->fields[ $args['id'] ] as $field_key => $field) {
			$indices = array( $field_key );
			$args = array(
				'current' 		=> $this->form->get_current_val($meta, $indices),
				'field_name' 	=> $this->form->make_field_name($args['id'], $indices)
			);

			$args = array_merge($args, $field);
			$this->form->render_with_label($args);
		}
	}

	function save_meta($post_id, $post) {
		foreach ($this->metaboxes as $key => $metabox) {
			if( !$_POST[ $key ] )
				return;

			$user_val = $_POST[ $key ];

			if( $user_val )
				update_post_meta( $post_id, $key, $user_val );
			else
				delete_post_meta( $post_id, $key );
		}
	}

	protected function get_metaboxes(){
		die('get_metaboxes() is an abstract function and needs to be overridden by a child class');
	}

	protected function get_fields() {
		die('get_fields() is an abstract function and needs to be overridden by a child class');
	}
}

?>