<?php
if ( ! class_exists( 'NISHIKI_PRO_TERM_META_IMAGE' ) ) {
	/**
	 * 各タームにアイキャッチ画像の設定を追加
	 */
	class NISHIKI_PRO_TERM_META_IMAGE {
		/**
		 * 追加したいフィールドを配列で登録
		 *
		 * @var array
		 */
		private $term_meta_array = array(
			array(
				'term' => 'eye_catch',
				'name' => 'アイキャッチ画像',
			),
			array(
				'term' => 'eye_catch_alt',
				'name' => 'アイキャッチ画像の説明（ALT）',
			),
			array(
				'term' => 'eye_catch_layout',
				'name' => 'アイキャッチ画像のレイアウト',
			),
		);

		/**
		 * レイアウト
		 *
		 * @var array
		 */
		private $layout_array = array(
			'background'   => 'タイトルの背景',
			'top'          => 'タイトルの上',
			'bottom'       => 'タイトルの下',
			'content'      => '本文の先頭',
			'content-wide' => '本文の先頭（広め）',
			'none'         => '非表示',
		);

		/**
		 * Nonce 用文字列
		 *
		 * @var string
		 */
		private $nonce = 'term_meta_nishiki_pro_image_nonce';

		/**
		 * Constructor.
		 */
		public function __construct() {
			// meta登録
			add_action( 'init', array( $this, 'register_term_meta' ), 100, 3 );
		}

		/**
		 * 登録
		 *
		 * @return void
		 */
		public function register_term_meta() {
			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];
				register_meta( 'term', $term, array( $this, 'sanitize_meta_box' ) );
			}

			// 表示したいフィールドのタクソノミーを配列で登録
			$taxonomies = $this->get_taxonomies();

			foreach ( $taxonomies as $taxonomy ) {
				add_action( $taxonomy . '_edit_form_fields', array( $this, 'edit_term_meta_field' ), 10, 3 );
				add_action( 'edit_' . $taxonomy, array( $this, 'save_term_meta' ), 10, 3 );
				add_action( 'create_' . $taxonomy, array( $this, 'save_term_meta' ), 10, 3 );
				add_filter( 'manage_edit-' . $taxonomy . '_columns', array( $this, 'add_term_columns' ), 10, 3 );
				add_action( 'manage_' . $taxonomy . '_custom_column', array( $this, 'add_term_value' ), 10, 3 );
			}
		}

		/**
		 * 入力された値を無害化
		 *
		 * @param string $text 文字列
		 * @return $text
		 */
		public function sanitize_meta_box( $text ) {
			return esc_html( $text );
		}

		/**
		 * 入力フィールド追加(画面に表示するため)
		 *
		 * @return void
		 */
		public function new_term_meta_field() {
			wp_nonce_field( basename( __FILE__ ), $this->nonce );
			$fields = '';
			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];
				$name = $data['name'];

				$fields .= '<label for="' . $term . '">' . $name . '</label><input type="text" name="' . $term . '" id="' . $term . '" value=""/>';
			}
			echo '<div class="form-field">' . wp_kses_post( $fields ) . '</div>';
		}

		/**
		 * 入力フィールド編集
		 *
		 * @param array $current_term ターム
		 * @return void
		 */
		public function edit_term_meta_field( $current_term ) {
			wp_nonce_field( basename( __FILE__ ), $this->nonce );
			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];
				$name = $data['name'];

				$value = get_term_meta( $current_term->term_id, $term, true ) ? get_term_meta( $current_term->term_id, $term, true ) : '';

				echo '<tr class="form-field"><th scope="row"><label for="' . esc_attr( $term ) . '">' . esc_html( $name ) . '</label></th><td>';

				if ( 'eye_catch' === $term ) {
					if ( $value ) {
						$eye_catch = wp_get_attachment_thumb_url( $value );

						echo '<p class="nishiki-pro-image-current" style="max-width:320px; margin-bottom:1rem;"><img alt="" style="max-width:100%; height: auto;" src="' . esc_url( $eye_catch ) . '"></p>';
					}
					echo '<input type="hidden" name="' . esc_attr( $term ) . '" id="' . esc_attr( $term ) . '" value="' . esc_attr( $value ) . '" />';
					echo '<a href="#" style="margin-right:1rem;" class="nishiki-pro-image-uploader button">画像を選択</a>';
					if ( $value ) {
						echo '<a href="#" class="nishiki-pro-remove-image button">画像を削除</a>';
					}
				} elseif ( 'eye_catch_layout' === $term ) {
					$default_layout = '';

					if ( get_theme_mod( 'setting_archive_eye_catch', false ) === false ) {
						$default_layout = 'none';
					} else {
						$default_layout = get_theme_mod( 'setting_archive_eye_catch_layout', 'background' );
					}

					// $eye_catch_layout = get_theme_mod( 'setting_archive_eye_catch_layout', 'background' );
					echo '<select name="' . esc_attr( $term ) . '" id="' . esc_attr( $term ) . '">';
					echo '<option value="" ' . selected( $value, '', false ) . '>デフォルト：' . esc_html( $this->layout_array[ $default_layout ] ) . '</option>';
					foreach ( $this->layout_array as $key => $val ) {
						echo '<option value="' . esc_attr( $key ) . '" ' . selected( $value, $key, false ) . '>' . esc_html( $val ) . '</option>';
					}
					echo '</select>';
				} else {
					echo '<input type="text" name="' . esc_attr( $term ) . '" id="' . esc_attr( $term ) . '" value="' . esc_attr( $value ) . '"/>';
				}

				echo '</td></tr>';
			}
		}

		/**
		 * 保存
		 *
		 * @param int $term_id ターム ID
		 * @return void
		 */
		public function save_term_meta( $term_id ) {
			if ( ! isset( $_POST[ $this->nonce ] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $this->nonce ] ) ), basename( __FILE__ ) ) ) {
				return;
			}

			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];

				$old_data = get_term_meta( $term_id, $term, true );
				$new_data = isset( $_POST[ $term ] ) ? $this->sanitize_meta_box( sanitize_text_field( wp_unslash( $_POST[ $term ] ) ) ) : '';

				if ( $old_data && '' === $new_data ) {
					delete_term_meta( $term_id, $term );

				} elseif ( $old_data !== $new_data ) {
					update_term_meta( $term_id, $term, $new_data );
				}
			}
		}

		/**
		 * カラムに表示
		 *
		 * @param array $columns カラム
		 * @return $columns
		 */
		public function add_term_columns( $columns ) {
			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];
				$name = $data['name'];
				if ( 'eye_catch_layout' !== $term ) {
					$columns[ $term ] = $name;
				}
			}
			return $columns;
		}

		/**
		 * カラムに値を出力
		 *
		 * @param string $value 値
		 * @param string $column_name カラム名
		 * @param string $term_id ターム ID
		 * @return void
		 */
		public function add_term_value( $value, $column_name, $term_id ) {
			foreach ( $this->term_meta_array as $data ) {
				$term = $data['term'];

				if ( $column_name === $term ) {
					$val = get_term_meta( $term_id, $term, true );

					if ( 'eye_catch' === $term ) {
						$eye_catch = wp_get_attachment_thumb_url( get_term_meta( $term_id, $term, true ) );
						$val       = '<img alt="" style="max-width:100px; height: auto;" src="' . esc_url( $eye_catch ) . '">';
					}

					echo wp_kses_post( $val );
				}
			}
		}

		/**
		 * カスタムタクソノミー全部取得
		 *
		 * @return $result
		 */
		public function get_taxonomies() {
			$builtin_taxonomy = array(
				'category',
				'post_tag',
			);
			$args             = array(
				'public'   => true,
				'_builtin' => false,

			);
			$output     = 'names'; // or objects
			$operator   = 'and'; // 'and' or 'or'
			$taxonomies = get_taxonomies( $args, $output, $operator );

			$result = array_merge( $builtin_taxonomy, $taxonomies );

			return $result;
		}

	}
}

$output = new NISHIKI_PRO_TERM_META_IMAGE();
