<?php

class RHC_Taxonomy_Images {
	private static $_instance;
	private $scripts_path;
	private $styles_path;
	public $version;

	public static function get_instance() {
		if ( ! ( self::$_instance instanceof self ) ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	protected function __construct( $args = array() ) {
		$defaults = array(
			'id'                 => 'rhcti',
			'addon'              => false,
			'options_capability' => 'manage_options',
		);

		$this->version      = RHCTI_VERSION;
		$this->scripts_path = RHCTI_URL . 'includes/js';
		$this->styles_path  = RHCTI_URL . 'includes/css';

		add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ), 9 );
		add_action( 'admin_init', array( $this, 'admin_init' ) );
	}

	private function __clone() {
	}

	private function __sleep() {
	}

	private function __wakeup() {
	}

	public function plugins_loaded() {
		load_plugin_textdomain( 'rhcti', false, RHCTI_LANGUAGE );

		add_action( 'load-edit-tags.php', array( $this, 'add_image_field' ) );

		add_action( 'created_term', array( $this, 'term_form_submit' ), 10, 2 );
		add_action( 'edited_term', array( $this, 'term_form_submit' ), 10, 2 );

		add_action( 'wp_ajax_set-term-image', array( $this, 'ajax_set_term_image' ) );
		add_action( 'wp_ajax_del-term-image', array( $this, 'ajax_del_term_image' ) );
	}

	public function admin_init() {
		global $rhc_plugin, $taxnow;

		$post_types = $rhc_plugin->get_option( 'img_post_types', RHC_EVENTS, true );
		
		if ( is_array( $post_types ) ) {
			array_push( $post_types, RHC_EVENTS );
		} else {
			$post_types = (array) $post_types;
		}

		$taxonomies = get_object_taxonomies( $post_types );
		
		foreach ( $taxonomies as $taxonomy ) {
			add_filter( 'manage_edit-' . $taxonomy . '_columns', array( $this, 'set_custom_taxonomy_columns' ) );
			add_filter( 'manage_' . $taxonomy . '_custom_column', array( $this, 'custom_taxonomy_column' ), 10, 3 );
		}
	}

	public function add_image_field() {
		global $taxnow;

		add_action( $taxnow . '_add_form_fields', array( $this, 'add_form_fields' ) );
		add_action( $taxnow . '_edit_form_fields', array( $this, 'edit_form_fields' ), 10, 2 );

		add_action( 'admin_enqueue_scripts', array( $this, 'add_scripts_styles' ) );
	}

	public function add_form_fields() {
		?>
		<div class="hide-if-no-js">
			<div class="form-field image">
				<label for="add-term-image" id="term-image-label"><?php _e( 'Image', 'rhcti' ); ?></label>
				<button type="button" class="image-handle-button button button-secondary" data-action="add"><?php _e( 'Add Image', 'rhcti' ); ?></button>
				<input type="hidden" name="term-image" id="term-image" value="">
			</div>
		</div>
		<?php
	}

	public function edit_form_fields($term, $taxonomy) {
		?>
<tr class="form-field image">
	<th scope="row" valign="top"><label for="image"><?php _e( 'Image', 'rhcti' ); ?></label></th>
	<td>
		<?php if ( $this->has_term_image( $term->term_id ) ) : ?>
			<?php echo $this->get_term_image( get_term_meta( $term->term_id, 'image', true ) ); ?>
			<button type="button" class="image-handle-button button button-secondary" data-action="delete"><?php _e( 'Delete Image', 'rhcti' ); ?></button>
			<input type="hidden" name="term-image" id="term-image" value="">
		<?php else : ?>
			<button type="button" class="image-handle-button button button-secondary" data-action="add"><?php _e( 'Add Image', 'rhcti' ); ?></button>
			<input type="hidden" name="term-image" id="term-image" value="">
		<?php endif; ?>
	</td>
</tr>
		<?php
	}

	public function add_scripts_styles() {
		wp_register_style( 'taxonomy-images-css', $this->styles_path . '/style.css' );
		wp_register_script('taxonomy-images-js', $this->scripts_path . '/rhc_taxonomy_images.js', array( 'jquery' ), $this->version, true );

		wp_localize_script( 'taxonomy-images-js', 'rhc_taxonomy_images', array(
			'add'     => __( 'Add Image', 'rhcti' ),
			'delete'  => __( 'Delete Image', 'rhcti' ),
			'select'  => __( 'Select or upload an image', 'rhcti' ),
			'use'     => __( 'Use this image', 'rhcti' ),
		) );

		wp_enqueue_media();
		wp_enqueue_style( 'taxonomy-images-css' );
		wp_enqueue_script( 'taxonomy-images-js' );
	}

	public function term_form_submit( $term_id, $tt_id ) {
		if ( ! isset( $_POST['term-image'] ) ) {
			return;
		}

		if ( ( $_POST['action'] !== 'add-tag' && $_POST['action'] !== 'editedtag' ) || empty( $_POST['action'] ) ) {
			return;
		}

		$term_image_id = $_POST['term-image'];

		if ( $term_image_id ) {
			$this->set_term_image( $term_id, $term_image_id );
		}
		else {
			$this->del_term_image( $term_id );
		}
	}

	public function set_term_image( $term_id, $attachment_id ) {
		$term_id = $term_id;
		$attachment_id = $attachment_id;
		$attachment_image_src = wp_get_attachment_image_src( $attachment_id, 'full' );

		update_term_meta( $term_id, 'image', $attachment_image_src[0] );
	}

	public function del_term_image( $term_id ) {
		update_term_meta( $term_id, 'image', '' );
	}

	public function set_custom_taxonomy_columns( $columns ) {
		$columns['image'] = __( 'Image', 'rhcti' );

		return $columns;
	}

	public function custom_taxonomy_column( $content, $column_name, $term_id ) {
		global $taxnow;

		$html = '<div class="hide-if-no-js">';

		switch ( $column_name ) {
			case 'image' :
				if ( $this->has_term_image( $term_id ) ) {
					$html .= $this->get_term_image( get_term_meta( $term_id, 'image', true ) );
					$html .= sprintf( '<button type="button" class="image-handle-button button" data-action="delete" data-ajax="1" data-taxonomy="%s" data-term="%s">%s</button>',
						esc_attr( $taxnow ),
						esc_attr( $term_id ),
						__( 'Delete Image', 'rhcti' )
					);
				} else {
					$html .= sprintf( '<button type="button" class="button image-handle-button" data-action="add" data-ajax="1" data-taxonomy="%s" data-term="%s">%s</button>',
						esc_attr( $taxnow ),
						esc_attr( $term_id ),
						__( 'Add Image', 'rhcti' )
					);
				}

				break;
		}

		$html .= '</div>';

		return $html;
	}

	public function has_term_image( $term_id ) {
		if ( get_term_meta( $term_id, 'image', true ) ) {
			return true;
		}

		return false;
	}

	public function get_term_image( $image_src ) {
		return sprintf( '<div class="term-image-box"><img src="%s" alt="" class="term-image"></div>',
			esc_url( $image_src )
		);
	}

	public function ajax_set_term_image() {
		$taxonomy = get_taxonomy( $_POST['taxonomy'] );

		if ( current_user_can( $taxonomy->cap->manage_terms ) )  {
			$this->set_term_image( $_POST['term_id'], $_POST['attachment_id'] );
			$image_attributes = wp_get_attachment_image_src( $_POST['attachment_id'] );

			$response = (object) array(
				'MSG'  => 'OK',
				'HTML' => $this->get_term_image( $image_attributes[0] )
			);
			die( json_encode( $response ) );
		}
	}

	public function ajax_del_term_image() {
		$taxonomy = get_taxonomy( $_POST['taxonomy'] );

		if ( current_user_can( $taxonomy->cap->manage_terms ) ) {
			$this->del_term_image( $_POST['term_id'] );
		}

		$response = (object) array(
			'MSG' => 'OK'
		);
		die( json_encode( $response ) );
	}
}
