<?php

class FLCMetabox{
	private $source;
		
	public function __construct( $source ){
		$this->source = $source;
		add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
		add_action( 'publish_page', array( $this, 'save' ) );
		add_action( 'publish_post', array( $this, 'save' ) );
	}
	public function add_meta_box() {
		add_meta_box( 
				$this->source->plugin_namespace,
				__( 
					$this->source->plugin_name,
					"{$this->source->plugin_namespace}_domain" 
				),
				array( $this, 'box'),
				'post',
				'side',
				'high'
		);
		add_meta_box( 
				$this->source->plugin_namespace,
				__( 
					$this->source->plugin_name, 
					"{$this->source->plugin_namespace}_domain" 
				),
				array( $this, 'box'),
				'page',
				'side',
				'high'
		);
	}
	public function box( $post ) {
		wp_nonce_field(
			plugin_basename( __FILE__ ),
			"{$this->source->plugin_namespace}_noncename"
		);
		include("{$this->source->plugin_dir}/views/metabox.php");
	}
	public function save( $post_id ) {
		if( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
			if ( ! current_user_can( 'edit_page', $post_id ) ) {
				return;
			}
		} else {
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return;
			}
		}
		$data = array( 'post_id' => $post_id  );
		$this->source->db->delete( 
			$this->source->plugin_tables['questions'],
			$data
		);
	}
}
?>
