<?php
/**
 * 
 *
 * @package qa_heatmap
 */

$qahm_admin_page_entire = new QAHM_Admin_Page_Entire();

class QAHM_Admin_Page_Entire extends QAHM_Admin_Page_Base {

	// スラッグ
	const SLUG = QAHM_NAME . '-entire';

	// nonce
	const NONCE_ACTION = self::SLUG . '-nonce-action';
	const NONCE_NAME   = self::SLUG . '-nonce-name';

	private static $error_msg = array();
	private $localize_ary;

	/**
	 * コンストラクタ
	 */
	public function __construct() {
		parent::__construct();

		 // コールバック
		add_action( 'init', array( $this, 'init_wp_filesystem' ) );
		add_action( 'load-qa-analytics_page_qahm-entire', array( $this, 'admin_init' ) );
		
		$this->regist_ajax_func( 'ajax_set_sitemanage_domainurl' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_memo' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_ignore_params' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_ignore_ips' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_url_case' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_base_html_p' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_search_params' );
		$this->regist_ajax_func( 'ajax_set_sitemanage_anontrack' );
		$this->regist_ajax_func( 'ajax_delete_sitemanages' );
	}
	
	// 管理画面の初期化
	public function admin_init(){
		if( defined('DOING_AJAX') && DOING_AJAX ){
			return;
		}

	}
	
	/**
	 * 初期化
	 */
	public function enqueue_scripts( $hook_suffix ) {
		if( $this->hook_suffix !== $hook_suffix ||
			! $this->is_enqueue_jquery()
		) {
			return;
		}

		global $qahm_time;
		$js_dir       = $this->get_js_dir_url();
		$data_dir     = $this->get_data_dir_url();
		$css_dir_url = $this->get_css_dir_url();


		// enqueue_style
		$this->common_enqueue_style();
		wp_enqueue_script( QAHM_NAME . '-admin-page-entire', $js_dir . 'admin-page-entire.js', array( QAHM_NAME . '-effect' ), QAHM_PLUGIN_VERSION ); //QA ZERO add
		wp_enqueue_style( QAHM_NAME . '-admin-page-entire-css', $css_dir_url . 'admin-page-entire.css', array( QAHM_NAME . '-reset' ), QAHM_PLUGIN_VERSION ); //QA ZERO add

		// enqueue script
		$this->common_enqueue_script();

		$scripts = $this->get_common_inline_script();
		wp_add_inline_script( QAHM_NAME . '-common', 'var ' . QAHM_NAME . ' = ' . QAHM_NAME . ' || {}; let ' . QAHM_NAME . 'Obj = ' . wp_json_encode( $scripts ) . '; ' . QAHM_NAME . ' = Object.assign( ' . QAHM_NAME . ', ' . QAHM_NAME . 'Obj );', 'before' );

		//QA ZERO start
		$localize['invalid_domainurl']         = esc_html( __( '有効なドメインURLでありません。', 'qa-zero' ) );
		$localize['registed_domainurl']         = esc_html( $this->japan( '既に登録済みのドメインURLです。', 'qa-zero' ) );
		$localize['invalid_ip_adress']         = esc_html( __( '有効なIPアドレスではありません。', 'qa-zero' ) );
		$localize['domainurl_add_failed']      = esc_html( __( 'ドメインURLの追加に失敗しました。', 'qa-zero' ) );
		$localize['invalid_urlparam']          = esc_html( __( 'URLパラメータが不正です。', 'qa-zero' ) );
		$localize['ignore_param_add_failed']   = esc_html( __( 'URLパラメータの追加に失敗しました。', 'qa-zero' ) );
		$localize['ignore_ip_add_failed']      = esc_html( __( 'IPアドレスの追加に失敗しました。', 'qa-zero' ) );
		$localize['sitemaneges_delete_failed'] = esc_html( __( 'ドメインURLの削除処理に失敗しました。', 'qa-zero' ) );
		$localize['memo_set_failed']           = esc_html( __( '編集したメモの保存処理に失敗しました。', 'qa-zero' ) );
		$localize['url_case_sensitivity_set_failed'] = esc_html( __( '大文字小文字を統一するかの設定処理に失敗しました。', 'qa-zero' ) );
		$localize['sitemap_add_failed']              = esc_html( __( 'サイトマップURLの追加に失敗しました。', 'qa-zero' ) );
		$localize['auto_upd_sitemap_use_set_failed'] = esc_html( __( 'sitemap.xmlで効率化の有効化に失敗しました。', 'qa-zero' ) );
		$localize['heatmap_auto_upd_set_failed']     = esc_html( __( 'ヒートマップ自動世代管理の有効化に失敗しました。', 'qa-zero' ) );
		$localize['base_html_p_set_failed']          = esc_html( __( 'HTML定期取得の設定に失敗しました。', 'qa-zero' ) );
		$localize['anontrack_set_failed']          = esc_html( __( 'Cookie拒否ユーザーの扱いの変更に失敗しました。', 'qa-zero' ) );
		$localize['searchparam_update_failed']          = esc_html( __( '検索パラメータの変更に失敗しました。', 'qa-zero' ) );
		//QA ZERO end
		wp_localize_script( QAHM_NAME . '-common', QAHM_NAME . 'l10n', $localize );

		$this->localize_ary = $localize;

	}

	/**
	 * ページの表示
	 */
	public function create_html() {

		global $qahm_data_api;

		$sitemanage_datas = $qahm_data_api->get_sitemanage(); //QA ZERO add

		$lang_ja['target_user_question'] =  esc_html__( 'Which type of users do you want meet the goal?', 'qa-zero' );
		$lang_ja['target_individual'] =  esc_html__( 'Personal', 'qa-zero' );
		$lang_ja['target_corporation'] =  esc_html__( 'Corporations/Organizations', 'qa-zero' );


		$lang_ja['select_sitetype_question'] =  esc_html__( 'Choose a category that describes your site best.', 'qa-zero' );
		$lang_ja['general'] =  esc_html__( 'General', 'qa-zero' );
		$lang_ja['media'] =  esc_html__( 'Media', 'qa-zero' );
		$lang_ja['service'] =  esc_html__( 'Providing services', 'qa-zero' );
		$lang_ja['ec_mall'] =  esc_html__( 'EC/Mall', 'qa-zero' );

		$lang_ja['general_company'] = esc_html__( 'About a company/services', 'qa-zero' );
		$lang_ja['media_affiliate'] = esc_html__( 'Affiliate blogs/Media', 'qa-zero' );
		$lang_ja['service_matching'] = esc_html__( 'Matching', 'qa-zero' );
		$lang_ja['ec_ec'] = esc_html__( 'Product sales', 'qa-zero' );
		$lang_ja['general_shop'] = esc_html__( 'About stores/facilities', 'qa-zero' );
		$lang_ja['media_owned'] = esc_html__( 'Owned media', 'qa-zero' );
		$lang_ja['service_ugc'] = esc_html__( 'Posting', 'qa-zero' );
		$lang_ja['ec_contents'] = esc_html__( 'Online content sales', 'qa-zero' );
		$lang_ja['general_ir'] = esc_html__( 'IR', 'qa-zero' );
		$lang_ja['media_other'] = esc_html__( 'Other information dissemination', 'qa-zero' );
		$lang_ja['service_membershi'] = esc_html__( 'SNS/Member services', 'qa-zero' );
		$lang_ja['ec_license'] = esc_html__( 'License sales', 'qa-zero' );
		$lang_ja['general_recruit'] = esc_html__( 'Recruitment', 'qa-zero' );
		$lang_ja['service_other'] = esc_html__( 'Other services', 'qa-zero' );
		$lang_ja['ec_other'] = esc_html__( 'Other sales', 'qa-zero' );

		$lang_ja['membership_question'] = esc_html__( 'Does the site have "member registration"?', 'qa-zero' );
		$lang_ja['payment_question'] = esc_html__( 'Does the site have "payment function"?', 'qa-zero' );
		$lang_ja['goal_monthly_access_question'] = esc_html__( 'Enter the target number for monthly sessions.', 'qa-zero' );

		$lang_ja['membership_yes'] = esc_html__( 'Yes.', 'qa-zero' );
		$lang_ja['membership_no'] = esc_html__( 'No.', 'qa-zero' );
		$lang_ja['next'] = esc_html__( 'Next', 'qa-zero' );

		$lang_ja['payment_no'] = esc_html__( 'No.', 'qa-zero' );
		$lang_ja['payment_yes'] = esc_html__( 'Yes, using original system.', 'qa-zero' );
		$lang_ja['payment_cart'] = esc_html__( 'Using external cart system.', 'qa-zero' );


		$lang_ja['month_later'] = esc_html__( 'month(s) later, reaching', 'qa-zero' );
		$lang_ja['session_goal'] = esc_html__( 'sessions/month is the goal.', 'qa-zero' );

		$goal        = esc_html__( 'Goal', 'qa-zero' );
		$goal_title  = esc_html__( 'Goal Name', 'qa-zero' );
		$required    = esc_html_x( '*', 'A mark that indicates it is required item.', 'qa-zero' );
		$goal_number = esc_html__( 'Completions Target in a Month', 'qa-zero' );
		$num_scale   = esc_html__( 'completion(s)', 'qa-zero' );
		$goal_value  = esc_html__( 'Goal Value (ave. monetary amount per goal)', 'qa-zero' );
		$val_scale   = esc_html_x( 'dollar(s)', 'Please put your currency. (This is only for a goal criterion.)', 'qa-zero' );
		$goal_sales  = esc_html__( 'Estimated Total Goal Value', 'qa-zero' );
		$goal_type   = esc_html__( 'Goal Type', 'qa-zero' );
		$goal_type_page  = esc_html__( 'Destination', 'qa-zero' );
		$goal_type_click = esc_html__( 'Click', 'qa-zero' );
		$goal_type_event = esc_html__( 'Event (Advanced)', 'qa-zero' );
		$goal_page   = esc_html__( 'Web page URL', 'qa-zero' );
		$click_page  = esc_html__( 'On which page?', 'qa-zero' );
		$eventtype   = esc_html__( 'Event Type', 'qa-zero' );
		$savechanges = esc_attr__( 'Save Changes', 'qa-zero' );
		$savesetting = esc_attr__( 'Settings saved.', 'qa-zero' );
		$clickselector = esc_html__( 'Click the object. (auto-fill)', 'qa-zero' );
		$eventselector = esc_html__( 'HTML tag (in RegEx)', 'qa-zero' );
		$pagematch_complete = esc_html__( 'Equals to', 'qa-zero' );
		$pagematch_prefix   = esc_html__( 'Begins with', 'qa-zero' );
		$click_sel_load = esc_html__( 'Load the Page', 'qa-zero' );
		$click_sel_set  = esc_html__( 'The goal has been set.', 'qa-zero' );
		$unset_goal = esc_html_x( 'Unset', 'unset a goal', 'qa-zero' );


		//each event
		$event_click   = esc_html__( 'on click', 'qa-zero' );

		// iframe
		$click_iframe_url = esc_url( get_home_url() );
	
		//$acount_ary  = $qahm_google_api->get_gabackup_acount( 'gabackup_acount' ); del for develop problem

?>

	<div id="<?php echo esc_attr( basename( __FILE__, '.php' ) ); ?>" class="qahm-admin-page">
		<div class="wrap">
			<h1>QA <?php esc_html_e( 'サイト全体', 'qa-zero' ); ?></h1>
				<div class="tabs">
					<input id="tab_sitemanage" type="radio" name="tab_item" value="sitemanage" checked>
					<label class="tab_item" for="tab_sitemanage"><span class="qahm_margin-right4" style="pointer-events: none;"><i class="fa fa-list"></i> </span><?php esc_html_e( '各サイト管理', 'qa-zero' ); ?></label>
					<div class="tab_content" id="tab_sitemanage_content">

						<h2><?php esc_html_e( '管理サイト追加', 'qa-zero' ); ?></h2>

						<form id="domainurl_submit_form" class="domainurl-form" onsubmit="SaveSitemanage(this);return false">
							<label for="domainurl-input"><?php esc_html_e( 'ドメインURL', 'qa-zero' ); ?></label>
							<input type="url" name="domain_url" id="domainurl-input">
							<button type="submit" class="button" id="domain_url_add_btn" ><?php esc_html_e( '追加', 'qa-zero' ); ?></button>
						</form>

						<h2><?php esc_html_e( '管理サイト一覧', 'qa-zero' ); ?></h2>
						
						<div class="sm_tablenav">
							<select name="action" id="sm-bulk-act-selector">
								<option value="-1"><?php esc_html_e( '一括操作', 'qa-zero' );?></option>
								<option value="delete"><?php esc_html_e( '削除', 'qa-zero' );?></option>
							</select>
							<button onclick="ClickSmbulkAction();" class="button"><?php esc_html_e( '適用', 'qa-zero' ); ?></button>
						</div>

						<table class="wp-like-table">
							<thead>
								<tr>
									<th class="text-center">
										<input type="checkbox" id="sm_table_all_cbx">
									</th>
									<th><?php esc_html_e( 'ドメインURL', 'qa-zero' );?></th>
									<th><?php esc_html_e( '自由メモ', 'qa-zero' );?></th>
									<th><?php esc_html_e( 'トラッキングタグ', 'qa-zero' );?></th>
									<th><?php esc_html_e( '除外URLパラメーター', 'qa-zero' );?></th>
									<th><?php esc_html_e( '検索パラメーター', 'qa-zero' );?></th>
									<th><?php esc_html_e( '計測しないIP', 'qa-zero' );?></th>
									<th><?php esc_html_e( 'URLを小文字に統一', 'qa-zero' );?></th>
									<th><?php esc_html_e( 'HTML定期取得', 'qa-zero' );?></th>
								</tr>
							</thead>
							<tbody>
								<?php if ( $sitemanage_datas ) {
									foreach ($sitemanage_datas as $sitemanage_data) { ?>
									<tr data-sid="<?php echo $sitemanage_data['site_id'];?>">
										<td class="text-center">
											<input type="checkbox" class="sm_table_cbx" data-sid="<?php echo $sitemanage_data['site_id'];?>">
										</td>
										<td><?php 
												$signal_color = "blue";
												switch ($sitemanage_data['status']) {
													case 0:
														$signal_color = "green";
														break;
													case 1:
														$signal_color = "yellow";
														break;
													case 2:
														$signal_color = "red";
														break;
												}
												echo "<span class='".$signal_color."-signal'>".$sitemanage_data['url']."</span>";
											?></td>
										<td>
											<form class="flex-form edit_memo" onsubmit="SetSmMemo(this);return false">
												<textarea name="sm_memo"><?php echo $sitemanage_data['memo'];?></textarea>
												<input type="text" name="sid" value="<?php echo $sitemanage_data['site_id'] ?>" hidden>
												<button type="submit" class="button"><?php esc_html_e( '保存', 'qa-zero' ); ?></button>
											</form>
										</td>
										<td>
											<div>
												<a href="<?php echo plugin_dir_url( __FILE__ )."tracking_tag.php?tracking_id=".$sitemanage_data['tracking_id']."&c_mode=false";?>" download="<?php echo "qtag_". $sitemanage_data['domain'].".txt"; ?>" id="t_tag_<?php echo $sitemanage_data['site_id'];?>"><?php esc_html_e( 'トラッキングタグ', 'qa-zero' ); ?></a>
												<a href="<?php echo plugin_dir_url( __FILE__ )."tracking_tag.php?tracking_id=".$sitemanage_data['tracking_id']."&host=".$sitemanage_data['domain']."&c_mode=false"; ?>" download="<?php echo "qtag_". $sitemanage_data['domain']."_crossdomain.txt"; ?>" id="t_tagc_<?php echo $sitemanage_data['site_id'];?>" hidden><?php esc_html_e( 'トラッキングタグ', 'qa-zero' ); ?></a>
											</div>
											<div>
												<span><?php echo $sitemanage_data['tracking_id']; ?></span>
											</div>
											<div>
												<div>
													<input type="checkbox" id="xdm_tag_<?php echo $sitemanage_data['site_id'] ?>" onchange="ChangeXdmcheck(arguments[0]);" name="xdm_tag_<?php echo $sitemanage_data['site_id'] ?>" data-sid="<?php echo $sitemanage_data['site_id'];?>">
													<label for="xdm_tag_<?php echo $sitemanage_data['site_id'] ?>"><?php esc_html_e( 'ｻﾌﾞﾄﾞﾒｲﾝとﾕｰｻﾞｰ共有', 'qa-zero' ); ?></label>
												</div>
												<div>
													<input type="checkbox" id="cookiem_tag_<?php echo $sitemanage_data['site_id'] ?>" onchange="ChangeCookieMcheck(arguments[0]);" name="cookiem_<?php echo $sitemanage_data['site_id'] ?>" data-sid="<?php echo $sitemanage_data['site_id'];?>">
													<label for="cookiem_tag_<?php echo $sitemanage_data['site_id'] ?>"><?php esc_html_e( 'Cookie同意モード', 'qa-zero' ); ?></label>
													<div id="anontrack_radio_box_<?php echo $sitemanage_data['site_id'] ?>" hidden>
														<div><?php esc_html_e( 'Cookie拒否ﾕｰｻﾞｰの扱い', 'qa-zero' ); ?></div>
														<div>
															<input type="radio" name="anontrack_<?php echo $sitemanage_data['site_id']; ?>" value="0" data-sid="<?php echo $sitemanage_data['site_id'];?>" onchange="AnontrackChange(arguments[0])" <?php if( $sitemanage_data['anontrack'] == 0 ) echo "checked"; ?>><?php esc_html_e( 'なるべく長く匿名ｾｯｼｮﾝ追跡(ｻﾌﾞﾄﾞﾒｲﾝも共通ID)', 'qa-zero' ); ?>
														</div>
														<div>
															<input type="radio" name="anontrack_<?php echo $sitemanage_data['site_id']; ?>" value="1" data-sid="<?php echo $sitemanage_data['site_id'];?>" onchange="AnontrackChange(arguments[0])" <?php if( $sitemanage_data['anontrack'] == 1 ) echo "checked"; ?>><?php esc_html_e( '一日限定の匿名ｾｯｼｮﾝ追跡', 'qa-zero' ); ?>
														</div>
													</div>
												</div>
											</div>
										</td>
										<td>
											<div>
												<form class="flex-form edit_ignoreparam" onsubmit="SetSmIgnoreParams(this);return false">
													<input type="text" name="ignore_params" class="sminfo-input" value='<?php echo $sitemanage_data['ignore_params'];?>'>
													<input type="text" name="sid" value="<?php echo $sitemanage_data['site_id'] ?>" hidden>
													<button type="submit" class="button"><?php esc_html_e( '更新', 'qa-zero' ); ?></button>
												</form>

											</div>
										</td>
										<td>
											<div>
												<form class="flex-form update_searchparam" onsubmit="SetSmSearchParams(this);return false">
													<input type="text" name="searchparam" class="sminfo-input" value="<?php echo $sitemanage_data['search_params']; ?>">
													<input type="text" name="sid" value="<?php echo $sitemanage_data['site_id']; ?>" hidden>
													<button type="submit" class="button"><?php esc_html_e( '更新', 'qa-zero' ); ?></button>
												</form>
											</div>
										</td>
										<td>
											<div>
												<?php echo $sitemanage_data['ignore_ips'];?>

												<form class="flex-form edit_ignore_ip" onsubmit="SetSmIgnoreIps(this);return false">
													<input type="text" name="ignore_ip" class="sminfo-input">
													<input type="text" name="sid" value="<?php echo $sitemanage_data['site_id'] ?>" hidden>
													<button type="submit" class="button"><?php esc_html_e( '追加', 'qa-zero' ); ?></button>
												</form>
											</div>    
										</td>
										<td>
											<input type="radio" name="url_case_<?php echo $sitemanage_data['site_id']; ?>" value="0" data-sid="<?php echo $sitemanage_data['site_id'];?>" onclick="UrlCaseRadioChange(arguments[0])" <?php if( $sitemanage_data['url_case_sensitivity'] == 0 ) echo "checked"; ?>><?php esc_html_e( 'する', 'qa-zero' ); ?>
											<input type="radio" name="url_case_<?php echo $sitemanage_data['site_id']; ?>" value="1" data-sid="<?php echo $sitemanage_data['site_id'];?>" onclick="UrlCaseRadioChange(arguments[0])" <?php if( $sitemanage_data['url_case_sensitivity'] == 1 ) echo "checked"; ?>><?php esc_html_e( 'しない', 'qa-zero' ); ?>
										</td>
										<td>
											<input type="radio" name="get_base_html_p_<?php echo $sitemanage_data['site_id']; ?>" value="1" data-sid="<?php echo $sitemanage_data['site_id'];?>" onclick="GetBasehtmlPChange(arguments[0])" <?php if( $sitemanage_data['get_base_html_periodic'] == 1 ) echo "checked"; ?>><?php esc_html_e( 'する', 'qa-zero'); ?>
											<input type="radio" name="get_base_html_p_<?php echo $sitemanage_data['site_id']; ?>" value="0" data-sid="<?php echo $sitemanage_data['site_id'];?>" onclick="GetBasehtmlPChange(arguments[0])" <?php if( $sitemanage_data['get_base_html_periodic'] == 0 ) echo "checked"; ?>><?php esc_html_e( 'しない', 'qa-zero'); ?>
										</td>

									</tr>
								<?php }
								} ?>
							</tbody>

						</table>

					</div>
<!-- QA ZERO end -->

			</div>
		</div>
	</div>


<?php
	}

	/**
	 * ドメインURLを追加するためのAJAXハンドラー
	 */
	public function ajax_set_sitemanage_domainurl() {
		$this->nonce_check();
		
		$url = $this->wrap_filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL);
		
		if (!$url) {
			$this->response_array_to_json(array("result" => "url_invalid_error"));
			return;
		}
		
		$result = $this->set_sitemanage_domainurl($url);
		$this->response_array_to_json($result);
		return;
	}

	/**
	 * ドメインURLをサイト管理に追加するコア機能
	 * 
	 * @param string $url サイト管理に追加するURL
	 * @return array 結果ステータスの配列
	 */
	public function set_sitemanage_domainurl($url) {
		global $qahm_time;
		global $qahm_log;
		$result_array = array("result" => "success");
		
		$parse_url = parse_url($url);
		
		if (!$parse_url) {
			return array("result" => "url_invalid_error");
		}
		
		$domain_url = $this->to_domain_url($parse_url);
		$tracking_id = $this->get_tracking_id($domain_url);
		
		$sitemanage = $this->wrap_get_option('sitemanage');
		if ($sitemanage) {
			foreach ($sitemanage as $site) {
				if ($site['tracking_id'] == $tracking_id && $site['status'] != 255) {
					return array("result" => "registed_domainurl");
				}
			}
		} else {
			$sitemanage = array();
		}
		
		$sitemanage[] = array(
			"site_id" => count($sitemanage),
			"url" => $domain_url,
			"domain" => $parse_url["host"],
			"tracking_id" => $tracking_id,
			"memo" => "",
			"status" => 0,
			"ignore_params" => "",
			"search_params" => "",
			"ignore_ips" => "",
			"url_case_sensitivity" => 0,
			"get_base_html_periodic" => 0,
			"anontrack" => 0,
			"insert_datetime" => $qahm_time->now_str(),
		);
		
		$res = $this->wrap_update_option('sitemanage', $sitemanage);
		
		if (!$res) {
			return array("result" => "db_insert_error");
		}
		
		$cq_res = $this->create_qtag($tracking_id);
		
		// 指定tracking_idのgscテーブル作成
		$qahm_database_manager = new QAHM_Database_Creator();
		$gsc_table_created = $qahm_database_manager->create_gsc_query_log_table($tracking_id);
		
		if (!$gsc_table_created) {
			// GSCテーブル作成に失敗した場合
			$qahm_log->error("QAHM: Failed to create GSC query log table for tracking_id: {$tracking_id}");
			
			// サイト管理情報は既に保存されているので、警告レベルのエラーとして返す
			return array(
				"result" => "gsc_table_creation_error",
				"message" => "Site registration completed, but GSC table creation failed",
				"tracking_id" => $tracking_id
			);
		}
		
		// 全て成功した場合
		$result_array["tracking_id"] = $tracking_id;
		return $result_array;
	}

	
	public function ajax_set_sitemanage_memo(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();

		$site_id = $this->wrap_filter_input( INPUT_POST, 'sid');
		$sm_memo = $this->wrap_filter_input( INPUT_POST, 'sm_memo');

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['memo'] = $sm_memo;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);
		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;
		
	}

	// 除外パラメータ
	public function ajax_set_sitemanage_ignore_params(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();

		$site_id       = (int) $this->wrap_filter_input( INPUT_POST, 'sid');
		$ignore_params = $this->wrap_filter_input( INPUT_POST, 'ignore_params');

		$is_invalid = false;

		// URLパラメータをカンマ区切りで分割し、各パラメータの形式を検証
		$params = explode(',', $ignore_params);
		foreach ($params as $param) {
			if (preg_match("/^[a-zA-Z0-9\-\_]+$/", $param) !== 1) {
				$is_invalid = true;
			}
		}
	
		// $sidが整数でない、または$urlparamが空の場合はエラー
		if (!is_int($site_id) || empty($ignore_params)) {
			$is_invalid = true;
		}

		if ( $is_invalid ) {
			$result_array["result"] = "invalid_urlparam";
			$this->response_array_to_json($result_array);
			return;
		}

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['ignore_params'] = $ignore_params;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);
		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;
		
	}

	// 除外IP
	public function ajax_set_sitemanage_ignore_ips(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();

		$site_id   = $this->wrap_filter_input( INPUT_POST, 'sid');
		$ignore_ip = $this->wrap_filter_input( INPUT_POST, 'ignore_ip');

		if (filter_var($ignore_ip, FILTER_VALIDATE_IP)) {
			$sitemanage = $this->wrap_get_option('sitemanage');
			foreach ($sitemanage as &$site) {
				if ($site['site_id'] == $site_id) {

					$ignore_ip_ary = array_filter(explode(",", $site['ignore_ips'])); // 現在のリストを配列化し空要素を削除
					if (!in_array($ignore_ip, $ignore_ip_ary)) { // 重複をチェック
						$ignore_ip_ary[] = $ignore_ip; // 新しいIPを追加
					}
					$ignore_ips_str = implode(",", $ignore_ip_ary); // 再び文字列化

					$site['ignore_ips'] = $ignore_ips_str;
					break;
				}
			}
			unset($site);
			$res = $this->wrap_update_option('sitemanage', $sitemanage);
		}else{
			$res = false;
		}

		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;
		
	}
	
	// 検索パラメーター
	public function ajax_set_sitemanage_search_params() {

		$result_array = array( "result" => "success" );

		$this->nonce_check();		
	
		$site_id       = (int) $this->wrap_filter_input(INPUT_POST, 'sid');
		$search_params = $this->wrap_filter_input(INPUT_POST, 'search_params');

		$is_invalid = false;

		// URLパラメータをカンマ区切りで分割し、各パラメータの形式を検証
		$params = explode(',', $search_params);
		foreach ($params as $param) {
			if (preg_match("/^[a-zA-Z0-9\-\_]+$/", $param) !== 1) {
				$is_invalid = true;
			}
		}
	
		// $sidが整数でない、または$urlparamが空の場合はエラー
		if (!is_int($site_id) || empty($search_params)) {
			$is_invalid = true;
		}

		if ( $is_invalid ) {
			$result_array["result"] = "invalid_urlparam";
			$this->response_array_to_json($result_array);
			return;
		}

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['search_params'] = $search_params;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);
		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;
	}

	// URLを小文字に統一
	public function ajax_set_sitemanage_url_case(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();

		$site_id  = (int) $this->wrap_filter_input( INPUT_POST, 'sid');
		$value    = (int) $this->wrap_filter_input( INPUT_POST, 'value');

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['url_case_sensitivity'] = $value;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);

		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;

	}

	// HTML定期取得
	public function ajax_set_sitemanage_base_html_p(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();		

		$site_id  = (int) $this->wrap_filter_input( INPUT_POST, 'sid');
		$value    = (int) $this->wrap_filter_input( INPUT_POST, 'value');

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['get_base_html_periodic'] = $value;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);

		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;
	}

	// Cookie拒否ユーザーの扱い
	public function ajax_set_sitemanage_anontrack(){

		$result_array = array( "result" => "success" );

		$this->nonce_check();

		$site_id  = (int) $this->wrap_filter_input( INPUT_POST, 'sid');
		$value    = (int) $this->wrap_filter_input( INPUT_POST, 'value');

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if ($site['site_id'] == $site_id) {
				$site['anontrack'] = $value;
				break;
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);

		if(!$res){
			$result_array["result"] = "error";
		}

		$this->response_array_to_json($result_array);
		return;

	}

	public function ajax_delete_sitemanages(){

		$result_array = array( "result" => "success" );
		$this->nonce_check();

		$sids_json_str      = $this->wrap_filter_input( INPUT_POST, 'sids_json');
		$sids = json_decode($sids_json_str);

		$is_invalid = false;

		if( !is_array( $sids ) ){
			$is_invalid = true;
		}

		$sids_count = count( $sids );
		if( $sids_count == 0 ){
			$is_invalid = true;
		}

		if( $is_invalid ){
			$result_array = array( "result" => "error" );
			$this->response_array_to_json($result_array);
			return;
		}

		$sitemanage = $this->wrap_get_option('sitemanage');
		foreach ($sitemanage as &$site) {
			if (in_array($site['site_id'], $sids)) {
				$site['status'] = 255; // site_id が一致した場合、status を 255 に設定
		
				//qtag.jsの削除
				$this->delete_qtag( $site['tracking_id'] );
			}
		}
		unset($site);
		$res = $this->wrap_update_option('sitemanage', $sitemanage);

		if(!$res){
			$result_array = array( "result" => "error" );
		}

		$this->response_array_to_json($result_array);
		
		return;

	}

	private function nonce_check(){

		$nonce = $this->wrap_filter_input( INPUT_POST, 'nonce' );
		if ( ! wp_verify_nonce( $nonce, QAHM_Data_Api::NONCE_API) || $this->is_maintenance() ) {
			http_response_code( 400 );
			die( 'nonce error' );
		}

	}
	

	private function response_array_to_json($array){
		header("Content-type: application/json; charset=UTF-8");
		echo wp_json_encode( $array );
		die();
	}
} // end of class

?>
