<?php
new CPT_Columns( 'Event', 'Evemts', 'dw-events' );

class CPT_Columns {

	private $single;
	private $plural;
	private $slug;
	private $taxonomies;
	static $instance;

	function __construct( $post_type, $plural = '', $slug = '' ) {

		self::$instance = $this;

		$this->single = $post_type;
		$this->plural = !empty( $plural ) ? $plural : $post_type .'s';
		$this->slug = !empty( $slug ) ? $slug : sanitize_title( $this->plural );

		add_filter( 'manage_edit-'. $this->slug .'_columns', array( &$this, 'columns' ) );
		add_action( 'manage_posts_custom_column', array( &$this, 'columns_display' ) );

	}

	public function columns( $columns ) {
		$taxonomies = get_object_taxonomies( $this->slug );

		if ( !empty( $taxonomies ) ){

			foreach ( $taxonomies as $key => $tax ) {
				if ( $tax == 'post_tag' || $tax == 'post_category' ) continue;

				$object = get_taxonomy( $tax );
				if ( !$object->hierarchical ) continue;

				$this->taxonomies[] = $tax;


				$columns[$tax.'_column'] = $object->label;
			}
		}

		return $columns;
	}

	public function columns_display( $column ) {

		if ( !empty( $this->taxonomies ) ){

			foreach ( $this->taxonomies as $tax ) {
				if ( $column == $tax.'_column' ) {
					$this->taxonomy_column( $tax, ucfirst( str_replace( '-', ' ', $tax ) ) );
				}
			}
		}
	}

	public function taxonomy_column( $tax = '', $name = '' ) {
		global $post;
		$id = $post->ID;
		$categories = get_the_terms( $id, $tax );
		if ( !empty( $categories ) ) {
			$out = array();
			foreach ( $categories as $c ) {
				$out[] = sprintf( '<a href="%s">%s</a>',
				esc_url( add_query_arg( array( 'post_type' => $post->post_type, $tax => $c->slug ), 'edit.php' ) ),
				esc_html( sanitize_term_field( 'name', $c->name, $c->term_id, 'category', 'display' ) )
				);
			}
			echo join( ', ', $out );
		} else {
			_e( 'No '. $name .' Specified' );
		}

	}
}
