<?php
if ( ! function_exists( 'nishiki_pro_share_customizer' ) ) {
	add_action( 'customize_register', 'nishiki_pro_share_customizer' );
	/**
	 * カスタマイザーの設定
	 *
	 * @param instance $wp_customize インスタンス
	 * @return void
	 */
	function nishiki_pro_share_customizer( $wp_customize ) {

		// Section
		$wp_customize->add_section(
			'section_' . NISHIKI_PRO_PREFIX_SHARE,
			array(
				'title'    => __( 'シェアボタン', 'nishiki_pro' ),
				'priority' => 500,
				'panel'    => 'panel_' . NISHIKI_PRO_PREFIX,
			)
		);

		// シェアボタンの表示
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display',
			array(
				'default'           => 'bottom',
				'sanitize_callback' => 'nishiki_pro_sanitize_choices_share',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display',
			array(
				'label'    => __( '表示箇所', 'nishiki_pro' ),
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display',
				'priority' => 1000,
				'type'     => 'select',
				'choices'  => array(
					'top'    => __( '本文の上', 'nishiki_pro' ),
					'bottom' => __( '本文の下', 'nishiki_pro' ),
					'both'   => __( '本文の上下両方', 'nishiki_pro' ),
					'none'   => __( '非表示', 'nishiki_pro' ),
				),
			)
		);

		// シェアボタンのデザインの適用
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_css',
			array(
				'default'           => true,
				'sanitize_callback' => 'nishiki_pro_sanitize_checkbox',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_button_css',
			array(
				'label'    => __( 'デザイン適用（チェックを入れるとデフォルトのデザインを適用します）', 'nishiki_pro' ),
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_css',
				'priority' => 700,
				'type'     => 'checkbox',
			)
		);

		// デザインパターン
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_design_pattern',
			array(
				'default'           => '02',
				'sanitize_callback' => 'nishiki_pro_sanitize_choices_share_design_pattern',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_design_pattern',
			array(
				'label'    => __( 'デザインパターン', 'nishiki_pro' ),
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_design_pattern',
				'priority' => 800,
				'type'     => 'select',
				'choices'  => array(
					'01' => __( '01', 'nishiki_pro' ),
					'02' => __( '02（デフォルト）', 'nishiki_pro' ),
					'03' => __( '03', 'nishiki_pro' ),
				),
			)
		);

		// シェアボタン上のテキスト
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_before_text',
			array(
				'default'           => '',
				'sanitize_callback' => 'nishiki_pro_sanitize_text',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_before_text',
			array(
				'label'    => __( 'シェアボタンの上 テキスト', 'nishiki_pro' ),
				'type'     => 'text',
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_before_text',
				'priority' => 800,
			)
		);

		// シェアボタン下のテキスト
		$wp_customize->add_setting(
			'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_after_text',
			array(
				'default'           => '',
				'sanitize_callback' => 'nishiki_pro_sanitize_text',
			)
		);

		$wp_customize->add_control(
			'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_after_text',
			array(
				'label'    => __( 'シェアボタンの下 テキスト', 'nishiki_pro' ),
				'type'     => 'text',
				'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
				'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_after_text',
				'priority' => 800,
			)
		);

		$nishiki_pro_share_button_type = array(
			'LINE'     => true,
			'Twitter'  => false,
			'X'        => true,
			'Facebook' => true,
			'hatena'   => false,
			'copy-url' => true,
		);

		foreach ( $nishiki_pro_share_button_type as $button => $flag ) {
			$wp_customize->add_setting(
				'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_' . $button,
				array(
					'default'           => $flag,
					'sanitize_callback' => 'nishiki_pro_sanitize_checkbox',
				)
			);

			$label = $button;

			if ( 'copy-url' === $button ) {
				$label = 'URL をコピー';
			}

			$wp_customize->add_control(
				'ctrl_' . NISHIKI_PRO_PREFIX_SHARE . '_button_' . $button,
				array(
					'label'    => $label,
					'section'  => 'section_' . NISHIKI_PRO_PREFIX_SHARE,
					'settings' => 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_' . $button,
					'priority' => 1000,
					'type'     => 'checkbox',
				)
			);
		}

	}
}

if ( ! function_exists( 'nishiki_pro_share_button' ) ) {
	/**
	 * Share button
	 *
	 * @return $output
	 */
	function nishiki_pro_share_button() {

		$plugin_dir_root = nishiki_pro_plugin_dir_root();

		$page_title         = ( mb_strlen( get_the_title() ) > 100 ) ? mb_substr( get_the_title(), 0, 100 ) . '...' : get_the_title();
		$separator          = rawurlencode( ' | ' );
		$site_title         = get_bloginfo( 'name' );
		$twitter_title_text = esc_html( $page_title . $separator . $site_title );
		$class              = '';

		// Text
		$tweet_text = apply_filters( NISHIKI_PRO_PREFIX_SHARE . '_twitter_title_text', $twitter_title_text, $page_title, $separator, $site_title );
		$link       = rawurlencode( esc_url( get_permalink() ) );

		// Hashtag
		$twitter_tag = apply_filters( NISHIKI_PRO_PREFIX_SHARE . '_twitter_tag', '' );

		$facebook_tag = apply_filters( NISHIKI_PRO_PREFIX_SHARE . '_facebook_tag', '' );
		$fb_tag       = ( ! empty( $facebook_tag ) ) ? '&amp;hashtag=' . rawurlencode( '#' . $facebook_tag ) : '';

		// URL
		$tw_url = 'http://twitter.com/intent/tweet?url=' . $link . '&amp;text=' . $tweet_text . '&amp;hashtags=' . rawurlencode( $twitter_tag );
		$fb_url = 'https://www.facebook.com/sharer/sharer.php?u=' . $link . $fb_tag;

		$output      = '';
		$button      = '';
		$before_text = '';
		$after_text  = '';

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_before_text', false ) ) {
			$before_text = '<p class="before-text">' . wp_kses_post( apply_filters( NISHIKI_PRO_PREFIX_SHARE . '_before_text', get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_before_text', false ) ) ) . '</p>';
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_LINE', true ) ) {
			$button .= <<< EOM
			<a target="_blank" aria-label="line" rel="noopener noreferrer nofollow" data-tooltip="LINE で送る" class="line icon noscroll" href="http://line.me/R/msg/text/?{$page_title}%0D%0A{$link}"><i class="icomoon icon-line"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_Twitter', false ) ) {
			$button .= <<< EOM
			<a target="_blank" aria-label="twitter" rel="noopener noreferrer nofollow" data-tooltip="Twitter でツイートする" class="tw icon noscroll" href="#" onclick="window.open('{$tw_url}',null,'width=550px,height=420px');return false;"><i class="icomoon icon-twitter"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_X', true ) ) {
			$button .= <<< EOM
			<a target="_blank" aria-label="x" rel="noopener noreferrer nofollow" data-tooltip="X にポストする" class="x icon noscroll" href="#" onclick="window.open('{$tw_url}',null,'width=550px,height=420px');return false;"><i class="icomoon icon-x"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_Facebook', true ) ) {
			$button .= <<< EOM
			<a target="_blank" aria-label="facebook" rel="noopener noreferrer nofollow" data-tooltip="Facebook でシェアする" class="fb icon noscroll" href="#" onclick="window.open('{$fb_url}',null,'width=550px,height=420px');return false;"><i class="icomoon icon-facebook2"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_hatena', false ) ) {
			$button .= <<< EOM
			<a target="_blank" aria-label="hatena" rel="noopener noreferrer nofollow" data-tooltip="はてなブックマークで保存する" class="hb icon hatena-bookmark-button noscroll" href="http://b.hatena.ne.jp/entry/{$link}" title="はてなブックマークに追加"><i class="icomoon icon-hatena-bookmark"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_copy-url', true ) ) {
			$button .= <<< EOM
			<span id="copy-url" class="hb icon copy-url" data-copy-button data-tooltip="URL をコピーする" data-copied="コピーしました"><i class="icomoon icon-checkmark copied"></i><i class="icomoon icon-copy"></i></a>
EOM;
		}
		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_after_text', false ) ) {
			$after_text = '<p class="after-text">' . wp_kses_post( apply_filters( NISHIKI_PRO_PREFIX_SHARE . '_after_text', get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_after_text', false ) ) ) . '</p>';
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_css', true ) ) {
			$design_pattern = get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_design_pattern', '02' );
			$class          = ' nishiki-pro-share-button-style nishiki-pro-share-button-style-' . $design_pattern;
		}

		if ( $button ) {
			$output .= '<div class="nishiki-pro-share-button-wrapper center">';
			$output .= '<div class="nishiki-pro-share-button-inner">';
			$output .= $before_text . '<div class="nishiki-pro-share-buttons' . $class . '">' . $button . '</div>' . $after_text;
			$output .= '</div>';
			$output .= '</div>';
		}

		return $output;
	}
}

if ( ! function_exists( 'nishiki_pro_add_share_button_top' ) ) {
	add_action( 'nishiki_pro_before_singular_content', 'nishiki_pro_add_share_button_top' );

	/**
	 * シェアボタン本文の上
	 *
	 * @return void
	 */
	function nishiki_pro_add_share_button_top() {
		if ( get_post_meta( get_the_ID(), '_nishiki_pro_share_button_disable_' . get_post_type(), true ) ) {
			return;
		}

		$nishiki_pro_share_button_display_top = apply_filters(
			'nishiki_pro_share_button_display_top',
			true,
		);

		if( ! $nishiki_pro_share_button_display_top ){
			return;
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display', 'bottom' ) === 'top' || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display', 'bottom' ) === 'both' ) {
			nishiki_pro_sanitize_share_button( nishiki_pro_share_button() );
			// echo nishiki_pro_share_button();
		}
	}
}

if ( ! function_exists( 'nishiki_pro_add_share_button_bottom' ) ) {
	add_action( 'nishiki_pro_after_singular_content', 'nishiki_pro_add_share_button_bottom' );

	/**
	 * シェアボタン本文の下
	 *
	 * @return void
	 */
	function nishiki_pro_add_share_button_bottom() {
		if ( get_post_meta( get_the_ID(), '_nishiki_pro_share_button_disable_' . get_post_type(), true ) ) {
			return;
		}

		$nishiki_pro_share_button_display_bottom = apply_filters(
			'nishiki_pro_share_button_display_bottom',
			true,
		);

		if( ! $nishiki_pro_share_button_display_bottom ){
			return;
		}

		if ( get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display', 'bottom' ) === 'bottom' || get_theme_mod( 'setting_' . NISHIKI_PRO_PREFIX_SHARE . '_button_display', 'bottom' ) === 'both' ) {
			nishiki_pro_sanitize_share_button( nishiki_pro_share_button() );
			// echo nishiki_pro_share_button();
		}
	}
}

if ( ! function_exists( 'nishiki_pro_share_button_disable_add_meta_box' ) ) {
	add_action( 'add_meta_boxes', 'nishiki_pro_share_button_disable_add_meta_box' );

	/**
	 * Adds a box to the main column on the Post and Page edit screens.
	 *
	 * @return void
	 */
	function nishiki_pro_share_button_disable_add_meta_box() {

		$screens = nishiki_pro_get_all_post_types();
		foreach ( $screens as $screen ) {
			add_meta_box(
				'nishiki_pro_share_button_disable_' . $screen,
				__( 'シェアボタンを非表示にする', 'nishiki_pro' ),
				'nishiki_pro_share_button_meta_box_disable_callback',
				$screen,
				'side'
			);
		}
	}
}

if ( ! function_exists( 'nishiki_pro_share_button_meta_box_disable_callback' ) ) {
	/**
	 * Prints the box content.
	 *
	 * @param WP_Post $post The object for the current post/page.
	 */
	function nishiki_pro_share_button_meta_box_disable_callback( $post ) {

		// Add a nonce field so we can check for it later.
		wp_nonce_field( 'nishiki_pro_share_button_disable_save_meta_box_data', 'nishiki_pro_share_button_disable_meta_box_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(), '_nishiki_pro_share_button_disable_' . get_post_type(), true );

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

		echo '<label for="nishiki_pro_share_button"><input type="checkbox" id="nishiki_pro_share_button" name="nishiki_pro_share_button_disable_new_field" value="1" ' . esc_attr( $checked ) . ' /> 非表示</label>';
	}
}

if ( ! function_exists( 'nishiki_pro_share_button_disable_save_meta_box_data' ) ) {
	add_action( 'save_post', 'nishiki_pro_share_button_disable_save_meta_box_data' );

	/**
	 * When the post is saved, saves our custom data.
	 *
	 * @param int $post_id The ID of the post being saved.
	 */
	function nishiki_pro_share_button_disable_save_meta_box_data( $post_id ) {

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

		// Verify that the nonce is valid.
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nishiki_pro_share_button_disable_meta_box_nonce'] ) ), 'nishiki_pro_share_button_disable_save_meta_box_data' ) ) {
			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, '_nishiki_pro_share_button_disable_' . get_post_type(), true );

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

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

