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

class QAHM_Update extends QAHM_File_Data {

	public function __construct() {
	}

	public function check_version() {
		global $qahm_license;
		global $qahm_db;
		global $qahm_data_api;
		global $qahm_log;
		global $wpdb;

		$ver = $this->wrap_get_option( 'plugin_version' );
		if ( $ver === QAHM_PLUGIN_VERSION ) {
			$this->delete_maintenance_file();
			return;
		}

		// Differs between ZERO and QA - Start ----------
		// プラグインタイプによってアップデート処理を分ける
		if ( QAHM_TYPE === QAHM_TYPE_ZERO ) {
			if( version_compare( '1.1.0.0', $ver, '>' ) ) {
				//qa_readersにis_rejectカラム追加
				$alt_query ='ALTER TABLE '.$wpdb->prefix.'qa_readers ADD COLUMN is_reject TINYINT(1) AFTER language';
				$qahm_db->query($alt_query);

				$alt_query ='ALTER TABLE '.$wpdb->prefix.'qa_sitemanage ADD COLUMN anontrack TINYINT(1) AFTER get_base_html_periodic';
				$qahm_db->query($alt_query);

				$this->wrap_update_option( 'plugin_version', '1.1.0.0' );
			}

			if( version_compare( '2.2.0.0', $ver, '>' ) ) {
				// テーブルの型変更
				$queries = [
					"ALTER TABLE {$wpdb->prefix}qa_utm_content MODIFY COLUMN content_id INT",
					"ALTER TABLE {$wpdb->prefix}qa_utm_media MODIFY COLUMN medium_id INT",
					"ALTER TABLE {$wpdb->prefix}qa_pv_log MODIFY COLUMN access_time DATETIME DEFAULT CURRENT_TIMESTAMP",
					"ALTER TABLE {$wpdb->prefix}qa_pv_log MODIFY COLUMN medium_id INT",
					"ALTER TABLE {$wpdb->prefix}qa_pv_log MODIFY COLUMN campaign_id INT",
					"ALTER TABLE {$wpdb->prefix}qa_pv_log MODIFY COLUMN content_id INT"
				];

				// クエリの実行とエラーハンドリング
				foreach ($queries as $query) {
					$result = $wpdb->query($query);
					if ($result === false) {
						$qahm_log->info("SQL Error: {$wpdb->last_error} in query: {$wpdb->last_query}");
					} else {
						$qahm_log->info("Query executed successfully: {$query}");
					}
				}

				$this->wrap_update_option( 'plugin_version', '2.2.0.0' );
			}

			if( version_compare( '2.2.4.0', $ver, '>' ) ) {
				$search_params = $this->wrap_get_option('search_params');
				if ( $search_params ) {
					$search_params = json_decode($search_params, true);
				}

				$table_name = $wpdb->prefix . 'qa_sitemanage';
				$sitemanage = $wpdb->get_results("SELECT * FROM $table_name", ARRAY_A);

				$data = null;
				if ( $sitemanage ) {
					$data = array();
					foreach ($sitemanage as $site) {
						$params = isset($search_params[$site['tracking_id']]) ? $search_params[$site['tracking_id']] : null;
						$data[] = [
							'site_id'               => (int) $site['sid'],
							'url'                   => $site['url'],
							'domain'                => $site['domain'],
							'memo'                  => $site['memo'],
							'tracking_id'           => $site['tracking_id'],
							'ignore_params'         => $site['ignore_params'],
							'ignore_ips'            => $site['ignore_ips'],
							'search_params'         => $params,
							'status'                => (int) $site['status'],
							'url_case_sensitivity'  => (int) $site['url_case_sensitivity'],
							'insert_datetime'       => $site['insert_datetime'],
							'get_base_html_periodic'=> (int) $site['get_base_html_periodic'],
							'anontrack'             => isset($site['anontrack']) ? (int) $site['anontrack'] : null,
						];
					}
				}
				$this->wrap_update_option( 'sitemanage', $data );

				$this->wrap_update_option( 'plugin_version', '2.2.4.0' );
			}

			if( version_compare( '2.3.0.0', $ver, '>' ) ) {			
				// 全角・半角の区別をするため、該当テーブルのカラムをutf8mb4_binに変更
				// qa_gsc_query_logテーブルのkeyword
				$siteary = $qahm_data_api->get_sitemanage();
				foreach ( $siteary as $site ) {
					$tracking_id = $site['tracking_id'];
					$query_log_table = $qahm_db->prefix . 'qa_gsc_'.$tracking_id.'_query_log';
					// 存在チェック
					$table_exists = $qahm_db->get_var("SHOW TABLES LIKE '{$query_log_table}'");
					if ( !$table_exists ) {
						continue;
					}
					$alter_query = "ALTER TABLE `$query_log_table` MODIFY `keyword` VARCHAR(190) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;";
					$result = $wpdb->query($alter_query);
					if ($result === false) {
						$qahm_log->info("(During plugin update) SQL Error: {$wpdb->last_error} in query: {$wpdb->last_query}");
					}
				}

				// qa_utm_campaignsテーブルの utm_campaign
				$table_exists = $qahm_db->get_var("SHOW TABLES LIKE '{$qahm_db->prefix}qa_utm_campaigns'");
				if ( $table_exists ) {
					$alter_query = "ALTER TABLE `{$qahm_db->prefix}qa_utm_campaigns` MODIFY `utm_campaign` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL;";
					$result = $wpdb->query($alter_query);
					if ($result === false) {
						$qahm_log->info("(During plugin update) SQL Error: {$wpdb->last_error} in query: {$wpdb->last_query}");
					}
				}

				// qa_utm_contentテーブルの utm_content
				$table_exists = $qahm_db->get_var("SHOW TABLES LIKE '{$qahm_db->prefix}qa_utm_content'");
				if ( $table_exists ) {
					$alter_query = "ALTER TABLE `{$qahm_db->prefix}qa_utm_content` MODIFY `utm_content` VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL;";
					$result = $wpdb->query($alter_query);
					if ($result === false) {
						$qahm_log->info("(During plugin update) SQL Error: {$wpdb->last_error} in query: {$wpdb->last_query}");
					}
				}

				$this->wrap_update_option( 'plugin_version', '2.3.0.0' );
			}
		} elseif ( QAHM_TYPE === QAHM_TYPE_WP ) {
			// QA WPのバージョンを取得
			if( version_compare( '4.8.0.0', $ver, '>' ) ) {
				$this->wrap_update_option( 'data_retention_days', 30 );
				$this->wrap_update_option( 'cb_sup_mode', 'yes' );
				$this->wrap_update_option( 'send_email_address', get_option( 'admin_email' ) );
				$this->wrap_update_option( 'pv_limit_rate', 0 );
				$this->wrap_update_option( 'pv_warning_mail_month', null );
				$this->wrap_update_option( 'pv_over_mail_month', null );
				$this->wrap_update_option( 'advanced_mode', false );
			}
		}
		// Differs between ZERO and QA - End ----------

		// 最終的にプラグインバージョンを現行のものに変更
		$this->wrap_update_option( 'plugin_version', QAHM_PLUGIN_VERSION );

		// プラグインバージョンに合わせてBrainsファイル更新のため、ライセンス認証
		$lic_authoirzed = $this->lic_authorized();
		if ( $lic_authoirzed ) {
			$key = $this->wrap_get_option( 'license_key' );
			$id  = $this->wrap_get_option( 'license_id' );
			$qahm_license->activate( $key, $id );
		}

		// メンテナンスファイルを削除
		$this->delete_maintenance_file();

		$qahm_log->info( 'Update process has completed.' );
	}

	
	/**
	 * メンテナンスファイルの削除
	 */
	private function delete_maintenance_file() {
		global $wp_filesystem;
		$maintenance_path = $this->get_temp_dir_path() . 'maintenance.php';
		if ( $wp_filesystem->exists( $maintenance_path ) ) {
			$wp_filesystem->delete( $maintenance_path );
		}
	}

}
