<?php
if ( ! class_exists( 'NISHIKI_PRO_META_BOX_TITLE' ) ) {
	/**
	 * Meta box 追加(タイトル変更)
	 *
	 * @author     AnimaGate, Inc.
	 * @link       https://support.animagate.com/product/wp-nishiki-pro/
	 */
	class NISHIKI_PRO_META_BOX_TITLE {
		/**
		 * 名前
		 *
		 * @var string
		 */
		private $meta_box_name = 'nishiki_pro_meta_box_title';

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ), 10 );
			add_action( 'save_post', array( $this, 'save_meta_box' ), 10 );
			add_action( 'save_post', array( $this, 'save_meta_box_title_disable' ), 10 );
		}

		/**
		 * Adds a box to the main column on the Post and Page edit screens.
		 */
		public function add_meta_box() {

			$screens = nishiki_pro_get_all_post_types();
			foreach ( $screens as $screen ) {
				add_meta_box(
					$this->meta_box_name . '_' . $screen,
					__( 'ページタイトルを変更する（上級者向け）', 'nishiki_pro' ),
					array( $this, 'meta_box_change_title_callback' ),
					$screen
				);
			}

			foreach ( $screens as $screen ) {
				add_meta_box(
					$this->meta_box_name . '_disable_' . $screen,
					__( 'ページタイトルを非表示にする', 'nishiki_pro' ),
					array( $this, 'meta_box_title_disable_callback' ),
					$screen,
					'side'
				);
			}
		}

		/**
		 * Prints the box content.
		 *
		 * @return void
		 */
		public function meta_box_change_title_callback() {
			$name = $this->meta_box_name;
			$key  = '_' . $name . '_' . get_post_type();

			// Add a nonce field so we can check for it later.
			wp_nonce_field( $name . '_save', $name . '_nonce' );

			/*
			 * Use get_post_meta() to retrieve an existing value
			 * from the database and use the value for the form.
			 */
			$value = get_post_meta( get_the_ID(), $key, true );
			echo '<label for="' . esc_attr( $name ) . '"><input type="text" id="' . esc_attr( $name ) . '" class="regular-text" name="' . esc_attr( $name ) . '_new_field" value="' . esc_html( $value ) . '"/></label>';
			echo '<p><small>title 要素、OGP（og:title）, Twitter カード（twitter:title）のタイトルを書き換えます。</small></p>';
		}

		/**
		 * Prints the box content.
		 */
		public function meta_box_title_disable_callback() {

			$name = $this->meta_box_name . '_disable';
			$key  = '_' . $name . '_' . get_post_type();

			// Add a nonce field so we can check for it later.
			wp_nonce_field( $name . '_save', $name . '_nonce' );

			$value = get_post_meta( get_the_ID(), $key, true );

			$checked = ( $value ) ? ' checked="checked"' : '';

			echo '<label for="' . esc_attr( $name ) . '"><input type="checkbox" id="' . esc_attr( $name ) . '" name="' . esc_attr( $name ) . '_new_field" value="1" ' . esc_attr( $checked ) . ' /> 非表示</label>';
			echo '<p><small>ページタイトルを非表示にしたい場合はチェックしてください。</small></p>';
			echo '<p><small>※ ページ属性のテンプレートを「全幅（タイトルなし）」「本文コンテンツのみ」を選択している場合は、チェックする/しないに関わらず、ページタイトルが表示されません。</small></p>';
		}

		/**
		 * When the post is saved, saves our custom data.
		 *
		 * @param int $post_id 投稿 ID
		 * @return void
		 */
		public function save_meta_box( $post_id ) {
			$name = $this->meta_box_name;
			$key  = '_' . $name . '_' . get_post_type();

			// Check if our nonce is set.
			if ( ! isset( $_POST[ $name . '_nonce' ] ) ) {
				return;
			}

			// Verify that the nonce is valid.
			if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $name . '_nonce' ] ) ), $name . '_save' ) ) {
				return;
			}

			// If this is an autosave, our form has not been submitted, so we don't want to do anything.
			if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
				return;
			}

			// Check the user's permissions.
			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;
				}
			}

			/* OK, it's safe for us to save the data now. */

			$value = get_post_meta( $post_id, $key, true );

			// 値がポストされていなかったら
			if ( ! isset( $_POST[ $name . '_new_field' ] ) ) {
				if ( $value ) {
					delete_post_meta( $post_id, $key, 1 );
				}
				return;
			} else {
				// Sanitize user input.
				$my_data = sanitize_text_field( wp_unslash( $_POST[ $name . '_new_field' ] ) );

				// Update the meta field in the database.
				update_post_meta( $post_id, $key, $my_data );
			}
		}

		/**
		 * When the post is saved, saves our custom data.
		 *
		 * @param int $post_id 投稿 ID
		 * @return void
		 */
		public function save_meta_box_title_disable( $post_id ) {
			$name = $this->meta_box_name . '_disable';
			$key  = '_' . $name . '_' . get_post_type();

			// Check if our nonce is set.
			if ( ! isset( $_POST[ $name . '_nonce' ] ) ) {
				return;
			}

			// Verify that the nonce is valid.
			if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $name . '_nonce' ] ) ), $name . '_save' ) ) {
				return;
			}

			// If this is an autosave, our form has not been submitted, so we don't want to do anything.
			if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
				return;
			}

			// Check the user's permissions.
			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;
				}
			}

			/* OK, it's safe for us to save the data now. */

			$value = get_post_meta( $post_id, $key, true );

			// 値がポストされていなかったら
			if ( ! isset( $_POST[ $name . '_new_field' ] ) ) {
				if ( $value ) {
					delete_post_meta( $post_id, $key, 1 );
				}
				return;
			} else {
				// Sanitize user input.
				$my_data = sanitize_text_field( wp_unslash( $_POST[ $name . '_new_field' ] ) );

				// Update the meta field in the database.
				update_post_meta( $post_id, $key, $my_data );
			}
		}

	}
}

$output = new NISHIKI_PRO_META_BOX_TITLE();
