<?php
/**
 * 管理画面のページを表示するクラスの基本クラス
 *
 * @package qa_heatmap
 */

class QAHM_Admin_Page_Base extends QAHM_File_Data {
	public $hook_suffix;

	function __construct() {
	}
	
	/**
	 * 共通部分のスタイル
	 */
	protected function common_enqueue_style() {
		$css_dir_url = $this->get_css_dir_url();
		wp_enqueue_style( QAHM_NAME . '-sweet-alert-2', $css_dir_url . '/lib/sweet-alert-2/sweetalert2.min.css', null, QAHM_PLUGIN_VERSION );
		wp_enqueue_style( QAHM_NAME . '-reset', $css_dir_url . 'reset.css', array( QAHM_NAME . '-sweet-alert-2' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_style( QAHM_NAME . '-qa-table', $css_dir_url . '/lib/qa-table/qa-table.css', array( QAHM_NAME . '-reset' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_style( QAHM_NAME . '-common', $css_dir_url . 'common.css', array( QAHM_NAME . '-reset' ), QAHM_PLUGIN_VERSION );
		// Differs between ZERO and QA - Start ----------
		// 環境によるCSSの読み込み
		if ( QAHM_TYPE === QAHM_TYPE_ZERO ) {
			wp_enqueue_style( QAHM_NAME . '-qa-table-custom', $css_dir_url . 'qa-table-custom-zero.css', array( QAHM_NAME . '-qa-table' ), QAHM_PLUGIN_VERSION );
			wp_enqueue_style( QAHM_NAME . '-admin-page-common', $css_dir_url . 'admin-page-common-zero.css', array( QAHM_NAME . '-reset' ), QAHM_PLUGIN_VERSION );
		} elseif ( QAHM_TYPE === QAHM_TYPE_WP ) {
			wp_enqueue_style( QAHM_NAME . '-qa-table-custom', $css_dir_url . 'qa-table-custom-wp.css', array( QAHM_NAME . '-qa-table' ), QAHM_PLUGIN_VERSION );
			wp_enqueue_style( QAHM_NAME . '-admin-page-common', $css_dir_url . 'admin-page-common-wp.css', array( QAHM_NAME . '-reset' ), QAHM_PLUGIN_VERSION );
		}
		// Differs between ZERO and QA - End ----------
	}
	
	/**
	 * 共通部分のスクリプト
	 */
	protected function common_enqueue_script() {
		$js_dir_url = $this->get_js_dir_url();
		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( QAHM_NAME . '-qa-table',  $js_dir_url . 'lib/qa-table/qa-table.js', null, QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-font-awesome',  $js_dir_url . 'lib/font-awesome/all.min.js', null, QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-sweet-alert-2',  $js_dir_url . 'lib/sweet-alert-2/sweetalert2.min.js', array( 'jquery' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-alert-message',  $js_dir_url . 'alert-message.js', array( QAHM_NAME . '-sweet-alert-2' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-common',  $js_dir_url . 'common.js', array( 'jquery', QAHM_NAME . '-qa-table' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-load-screen',  $js_dir_url . 'load-screen.js', array( QAHM_NAME . '-common' ), QAHM_PLUGIN_VERSION );
		wp_enqueue_script( QAHM_NAME . '-effect',  $js_dir_url . 'effect.js', array( QAHM_NAME . '-load-screen' ), QAHM_PLUGIN_VERSION );
	}

	/**
	 * 共通部分のインラインスクリプト
	 */
	protected function get_common_inline_script() {
		$dev001 = defined( 'QAZR_DEV001' ) ? true : false;
		$dev002 = defined( 'QAZR_DEV002' ) ? true : false;
		$dev003 = defined( 'QAZR_DEV003' ) ? true : false;
		global $qahm_time;
		$timezone = $qahm_time->timezone_obj->getName();

		$scripts = array(
			'nonce_api'            => wp_create_nonce( QAHM_Data_Api::NONCE_API ),
			'ajax_url'             => admin_url( 'admin-ajax.php' ),
			'const_debug_level'    => QAHM_DEBUG_LEVEL,
			'const_debug'          => QAHM_DEBUG,
			//'license_plan'         => $this->wrap_get_option( 'license_plan' ),
			//'license_plans'        => $this->get_plan(),
			'site_url'             => get_site_url(),
			'plugin_dir_url'       => plugin_dir_url( __FILE__ ),
			'plugin_version'       => QAHM_PLUGIN_VERSION,
			'data_dir_url'         => $this->get_data_dir_url(),
			'devices'              => QAHM_DEVICES,
			'dev001'               => $dev001,
			'dev002'               => $dev002,
			'dev003'               => $dev003,
			// common variables
			'wp_gmt_offset' 	  	=> get_option( 'gmt_offset' ),
			'wp_timezone'	  		=> $timezone,
			'wp_lang'		  		=> get_option( 'WPLANG' ),
			'wp_user_locale'	  	=> get_user_locale(),
		);

		return $scripts;
	}

	/**
	 * JS用 localization(l10n) テキスト（admin-page共通）
	 */
	protected function get_common_localize_script() {
		$localize = array(
		//	'test' => esc_html__( 'ここに共通ローカライズ単語を書いていく。このメッセージは翻訳不要', 'qa-heatmap-analytics' ),
		);

		return $localize;
	}

	/**
	 * 簡略な言語コード（例: ja, en）を完全なロケール（例: ja_JP, en_US）に変換する
	 *
	 * @param string $locale get_locale() や determine_locale() の返り値
	 * @return string 完全ロケール（未定義ならそのまま返す）
	 */
	protected function normalize_locale( $locale ) {
		$locale_map = array(
			// 日本語
			'ja' => 'ja_JP',

			// 英語（アメリカ）
			'en' => 'en_US',

			// 英語（イギリス）など追加も可能
			'en_GB' => 'en_GB',

			// 中国語
			'zh' => 'zh_CN',
			'zh-hans' => 'zh_CN', // 簡体字
			'zh-hant' => 'zh_TW', // 繁体字

			// フランス語
			'fr' => 'fr_FR',

			// ドイツ語
			'de' => 'de_DE',

			// スペイン語
			'es' => 'es_ES',

			// 韓国語
			'ko' => 'ko_KR',

			// イタリア語
			'it' => 'it_IT',

			// ロシア語
			'ru' => 'ru_RU',

			// ポルトガル語
			'pt' => 'pt_PT',
			'pt-br' => 'pt_BR',

			// その他必要に応じて追加
		);

		return $locale_map[ strtolower( $locale ) ] ?? $locale;
	}

	/**
	 * jQueryのキューイングチェック
	 */
	protected function is_enqueue_jquery() {
		if ( wp_script_is( 'jquery' ) ) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * jQueryが存在しない時のメッセージを表示
	 */
	protected function view_not_enqueue_jquery_html() {
		$msg = '<div id="qahm-error" class="error notice is-dismissible"><p>';
		/* translators: %s is the plugin name */
		$msg .= sprintf(
			esc_html__( 'jQuery is not loaded, so %s cannot function properly.', 'qa-heatmap-analytics' ),
			QAHM_PLUGIN_NAME
		);
		$msg .= '<br>';
		$msg .= esc_html__( 'Please use "wp_enqueue_script" to load jQuery.', 'qa-heatmap-analytics' );
		$msg .= '</p></div>';
		echo wp_kses_post( $msg );
	}

	/**
	 * メンテナンス表示
	 */
	protected function view_maintenance_html() {
		$style = <<<EOD
		<style>
		.mainteqa {
			width: 800px;
			background-color: #fcfcfc;
			padding: 24px;
		}
		.mainteqa h1 {
			border-bottom: solid 2px #f9cdc5;
			margin-bottom: 32px;
			font-size: 1.2rem;
			line-height: 2;
		}
		.mainteqa p {
			line-height: 1.8;
			margin-bottom: 1em;
		}
		</style>
EOD;

		$mes  = '<div class="mainteqa">';
		$mes .= '<h1>' . esc_html__( 'Maintenance Notice', 'qa-heatmap-analytics' ) . '</h1>';
		$mes .= '<p>' . esc_html__( 'Your data is currently undergoing maintenance. This process may take a few minutes to complete.', 'qa-heatmap-analytics' ) . '</p>';
		$mes .= '<p>' . esc_html__( 'After updating the plugin, changes may take a few minutes to apply. Reloading the page afterward is recommended.', 'qa-heatmap-analytics' ) . '</p>';
		$mes .= '<p>' . sprintf(
			/* translators: %1$s and %2$s are anchor tags for the troubleshooting page */
			esc_html__( 'If this notice continues to appear for an extended period, please refer to our %1$sTroubleshooting page%2$s.', 'qa-heatmap-analytics' ),
			'<a href="https://mem.quarka.org/en/manual/keep-getting-data-is-under-maintenance/" target="_blank" rel="noopener">',
			'</a>'
		) . '</p>';
		$mes .= '</div>';

		echo wp_kses( $style, array( 'style' => array() ) );
		echo wp_kses_post( $mes );
	}


	/**
	 * RSSを表示
	 */
	protected function view_rss_feed() {
		$wp_lang_set = get_bloginfo( 'language' );

		// 日本語環境以外では表示しない
		if ( strpos( $wp_lang_set, 'ja' ) !== 0 ) {
			return;
		}

		include_once ABSPATH . WPINC . '/feed.php';

		// プラグイン種別に応じてRSS情報を設定
		if ( QAHM_TYPE === QAHM_TYPE_ZERO ) {
			$rss_url      = 'https://qazero.com/blog/feed/';
			$heading_text = __( 'QA ZERO ブログ', 'qa-heatmap-analytics' );
			$show_version = false;
		} elseif ( QAHM_TYPE === QAHM_TYPE_WP ) {
			$rss_url      = 'https://mem.quarka.org/category/wpuserinfo/feed/';
			$heading_text = __( "What's New", 'qa-heatmap-analytics' );
			$show_version = true;
		} else {
			return;
		}

		$rss = fetch_feed( $rss_url );
		if ( is_wp_error( $rss ) ) {
			return;
		}

		$maxitems = $rss->get_item_quantity( 5 );
		if ( empty( $maxitems ) || $maxitems <= 0 ) {
			return;
		}

		$rss_items   = $rss->get_items( 0, $maxitems );
		$date_format = 'Y年n月j日'; // 日本語前提で固定
		?>

		<div id="qa-zero-rss" class="qa-zero-data-container">
			<div class="qa-zero-data">
				<div class="qa-zero-data__title">
					<svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 25 24" fill="none">
						<mask id="mask0_rss" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="3" y="3" width="19" height="18">
							<path fill-rule="evenodd" clip-rule="evenodd" d="M18.1589 3C17.9101 3 17.6514 3.1 17.4623 3.29L15.6413 5.12L19.3729 8.87L21.1939 7.04C21.582 6.65 21.582 6.02 21.1939 5.63L18.8654 3.29C18.6664 3.09 18.4176 3 18.1589 3ZM14.5766 9.02L15.492 9.94L6.47648 19H5.56099V18.08L14.5766 9.02ZM3.5708 17.25L14.5766 6.19L18.3082 9.94L7.30241 21H3.5708V17.25Z" fill="white"/>
						</mask>
						<g mask="url(#mask0_rss)">
							<rect x="0.586914" width="23.8823" height="24"/>
						</g>
					</svg>
					<?php echo esc_html( $heading_text ); ?>
				</div>

				<div class="rss-widget">
					<?php if ( $show_version ) : ?>
						<style>
							.rss-note {
								color: #666;
								font-size: 0.9em;
								margin-bottom: 0.5em;
							}
						</style>
						<p class="rss-note">
							<?php echo esc_html__( 'Current plugin version:', 'qa-heatmap-analytics' ) . ' ' . esc_html( QAHM_PLUGIN_VERSION ); ?>
						</p>
					<?php endif; ?>

					<ul>
						<?php foreach ( $rss_items as $item ) : ?>
							<li>
								<span class="qa-zero-data__rss-date">
									<?php echo esc_html( $item->get_date( $date_format ) ); ?>
								</span>
								<a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank" class="rsswidget" rel="noopener">
									<?php echo esc_html( $item->get_title() ); ?>
								</a>
							</li>
						<?php endforeach; ?>
					</ul>
				</div>
			</div>
		</div>

		<?php
	}

} // end of class
