<?php 
if ( ! defined( 'ABSPATH' ) ) exit;
function emailotpauthn_reset_v634_settings(){
	
	emailotpauthn_turn_version_settings('enterprisedemo',false,0);
	emailotpauthn_turn_version_settings('isdemofilplcd',false,"");
	emailotpauthn_turn_version_settings('useupgrdfiture',false,0);
	emailotpauthn_turn_version_settings('settingsdetls',false,"");

	$emptysetting = "not_initiated";
	$savednoticentxts = get_option('emailotpauthn_formnoticentxt',$emptysetting);
	$savednoticentxts = isset($savednoticentxts) ? (empty(trim($savednoticentxts)) ? $emptysetting : $savednoticentxts) : $emptysetting;
	if(strcasecmp($savednoticentxts,$emptysetting)!=0){
		$formnoticentxt = "#-ntbreak-#" . hex2bin($savednoticentxts);
		$savednoticentxts = explode("#-ntbreak-#",$formnoticentxt);
		// The if section below is developed specially to convert this array from version 6.3.5 to version 6.3.4 only.
		if(count($savednoticentxts) > 66){
			$savednoticentxts[] = "Error: Invalid username, email address or incorrect password.";
			unset($savednoticentxts[64]);
			unset($savednoticentxts[65]);
		}
		$formnoticentxt = trim(implode("#-ntbreak-#",$savednoticentxts),"#-ntbreak-#");
		update_option("emailotpauthn_formnoticentxt", bin2hex($formnoticentxt));
	}

	emailotpauthn_recall_settings();

}

function emailotpauthn_reset_v635_settings(){
	
	emailotpauthn_turn_version_settings('enterprisedemo',true,0);
	emailotpauthn_turn_version_settings('isdemofilplcd',true,"");
	emailotpauthn_turn_version_settings('useupgrdfiture',true,0);
	emailotpauthn_turn_version_settings('settingsdetls',true,"");
	
	emailotpauthn_recall_settings();

}

function emailotpauthn_turn_version_settings($settingName,$isTurnToNew,$setigType){
	$preverval = "634";
	$postverval = "635";
	if($isTurnToNew){
		$preverval = "635";
		$postverval = "634";
	}
	$current_seting = get_option( 'emailotpauthn_'.$settingName );
	$preseting_vals = get_option( 'emailotpauthn_'.$preverval.$settingName );
	if ( $current_seting === false ) $current_seting = $setigType;
	if ( $preseting_vals === false ) $preseting_vals = $setigType;
	if(strcasecmp($settingName,"settingsdetls")==0){
		$emptysetting = "not_initiated";
		$defaultNewSettings = array(
			"swichtolgoutbtn"=>0,
			"emailotpauthn_enbladvncadmin"=>0,
			"emailotpauthn_2fa_time_out"=>0,
			"emailotpauthn_2fa_on_login"=>0,
			"emailotpauthn_2fa_on_regtr"=>0,
			"emailotpauthn_2fa_sessions"=>0,
			"emailotpauthn_2fa_on_oldsn"=>0,
			"emailotpauthn_2fa_on_newsn"=>0,
			"emailotpauthn_rdrct2faurlout"=>"",
		);
		$settingsdetls = isset($current_seting) ? (empty(trim($current_seting)) ? $emptysetting : $current_seting) : $emptysetting;
		if(strcasecmp($settingsdetls,$emptysetting)!=0){
			$savedsettings = json_decode($settingsdetls,true);
			if(empty($preseting_vals)){
				if($isTurnToNew){
					$defaultsettings = array_merge($defaultNewSettings, $savedsettings);
				} else {
					$defaultsettings = array_diff_key($savedsettings, $defaultNewSettings);
				}
			} else {
				if($isTurnToNew){
					$preseting_vals = json_decode($preseting_vals,true);
					$defaultsettings = array_merge($preseting_vals, $savedsettings);
				} else {
					$defaultsettings = array_diff_key($savedsettings, $defaultNewSettings);
				}
			}
			$newsettingsvals = json_encode($defaultsettings);
			if(empty($newsettingsvals)) {
				$preseting_vals = $setigType;
			} else {
				$preseting_vals = $newsettingsvals;
			}
		}
	}
	update_option( 'emailotpauthn_'.$postverval.$settingName, $current_seting );
	update_option( 'emailotpauthn_'.$settingName, $preseting_vals );
}

function emailotpauthn_recall_settings(){

	global $extrnlcvrbl, $eotpasettings, $inline_used, $extrnlvrbl, $formtexts;
	$extrnlcvrbl = null;
	$eotpasettings = null;
	$inline_used = null;
	$extrnlvrbl = null;
	$formtexts = null;

}

function emailotpauthn_filedir_validation($old_file,$new_file,$avl_file){
	$respns = false;
	if(is_writable(dirname($old_file)) && file_exists($old_file) && is_writable($old_file) && file_exists($avl_file) && is_writable($avl_file) && (!file_exists($new_file))) $respns = true;
	return $respns;
}

function emailotpauthn_get_version($pluginfile){
    if(!file_exists($pluginfile)) return '';
    $pluginheaders=array('Version'=>'Version');
    $plugindata=get_file_data($pluginfile,$pluginheaders);
    return $plugindata['Version'];
}
?>
<style>
.notice{
 display:none;
}
</style>
<div class="wrap" style="text-align:center;">
	<br/><br/>
    <h2 style="color:#990000;">Switch The Version of <?php echo esc_html( EMAILOTPAUTHN_PLUGIN_NAME ); ?></h2><br/><br/>
	<?php
		$logged_in_email = '';
		if (current_user_can('manage_options')) {
			$logged_in_user = wp_get_current_user();
			$logged_in_email = $logged_in_user->user_email;
		} else {
			wp_die('You are not authorized to proceed.');
		}
		$dir_file = dirname(__FILE__);
		if ($_SERVER["REQUEST_METHOD"] == "POST"){
			if ( !(isset( $_POST['eotpa_switching_plugin_version'] ) && wp_verify_nonce( $_POST['eotpa_switching_plugin_version'], 'eotpa_switch_the_version' )) ) {
				wp_die( 'Security check failed! Invalid token.' );
			}
			if(isset($_POST['cmdswitch']) && !empty(trim($_POST['cmdswitch']))) {
				$nextplugin = strtolower(trim($_POST['cmdswitch']));
				if($nextplugin == 'new' || $nextplugin == 'old'){
					$msgtoswitch = '';
					if(isset($_POST['msgswitch']) && !empty(trim($_POST['msgswitch']))) {
						$msgtoswitch = trim($_POST['msgswitch']);
						$msgtoswitch = preg_replace('/[^a-zA-Z0-9_ \-\/,.;:?()]/s',' ',$msgtoswitch);
					}
					
					if (file_exists(sprintf("%s/lib/", $dir_file))) {
						if($nextplugin == 'old'){
							$currentplugin = 'new';
						} elseif($nextplugin == 'new'){
							$currentplugin = 'old';
						}
						
						$respns = false;
						$respstr = '';
						// Check lib directories
						$respns = emailotpauthn_filedir_validation(sprintf("%s/lib/", $dir_file),sprintf("%s/lib_" . $currentplugin . "/", $dir_file),sprintf("%s/lib_" . $nextplugin . "/", $dir_file));
						// Check email-otp-authenticator.pot files
						if($respns) $respns = emailotpauthn_filedir_validation(sprintf("%s/languages/email-otp-authenticator.pot", $dir_file),sprintf("%s/languages/email-otp-authenticator.pot_" . $currentplugin . "", $dir_file),sprintf("%s/languages/email-otp-authenticator.pot_" . $nextplugin . "", $dir_file));
						// check readme.txt files
						if($respns) $respns = emailotpauthn_filedir_validation(sprintf("%s/readme.txt", $dir_file),sprintf("%s/readme.txt_" . $currentplugin . "", $dir_file),sprintf("%s/readme.txt_" . $nextplugin . "", $dir_file));
						// Check email-otp-authenticator.php files
						if($respns) $respns = emailotpauthn_filedir_validation(sprintf("%s/email-otp-authenticator.php", $dir_file),sprintf("%s/email-otp-authenticator.php_" . $currentplugin . "", $dir_file),sprintf("%s/email-otp-authenticator.php_" . $nextplugin . "", $dir_file));

						if($respns){
							// Exchange lib directory
							$respns = rename(sprintf("%s/lib/", $dir_file),sprintf("%s/lib_" . $currentplugin . "/", $dir_file));
							if($respns) { $respstr .= 'A'; $respns = false; }
							$respns = rename(sprintf("%s/lib_" . $nextplugin . "/", $dir_file),sprintf("%s/lib/", $dir_file));
							if($respns) { $respstr .= 'B'; $respns = false; }
						
							// Exchange email-otp-authenticator.pot file
							$respns = rename(sprintf("%s/languages/email-otp-authenticator.pot", $dir_file),sprintf("%s/languages/email-otp-authenticator.pot_" . $currentplugin . "", $dir_file));
							if($respns) { $respstr .= 'C'; $respns = false; }
							$respns = rename(sprintf("%s/languages/email-otp-authenticator.pot_" . $nextplugin . "", $dir_file),sprintf("%s/languages/email-otp-authenticator.pot", $dir_file));
							if($respns) { $respstr .= 'D'; $respns = false; }
						
							// Exchange readme.txt file
							$respns = rename(sprintf("%s/readme.txt", $dir_file),sprintf("%s/readme.txt_" . $currentplugin . "", $dir_file));
							if($respns) { $respstr .= 'E'; $respns = false; }
							$respns = rename(sprintf("%s/readme.txt_" . $nextplugin . "", $dir_file),sprintf("%s/readme.txt", $dir_file));
							if($respns) { $respstr .= 'F'; $respns = false; }
						
							// Exchange email-otp-authenticator.php file
							$respns = rename(sprintf("%s/email-otp-authenticator.php", $dir_file),sprintf("%s/email-otp-authenticator.php_" . $currentplugin . "", $dir_file));
							if($respns) { $respstr .= 'G'; $respns = false; }
							$respns = rename(sprintf("%s/email-otp-authenticator.php_" . $nextplugin . "", $dir_file),sprintf("%s/email-otp-authenticator.php", $dir_file));
							if($respns) { $respstr .= 'H'; $respns = false; }
							
							if($nextplugin == 'old') emailotpauthn_reset_v634_settings(); else emailotpauthn_reset_v635_settings();
							
							$url = 'https://eotpa.cs7.in/switchrecords/index.php';
							$data = ['plugin' => EMAILOTPAUTHN_PLUGIN_NAME, 'version' => EMAILOTPAUTHN_PLUGIN_VERSION, 'adminemail' => $logged_in_email, 'activated' => $nextplugin, 'progress' => $respstr, 'message' => $msgtoswitch];

							$options = [
								'http' => [
									'header' => "Content-type: application/x-www-form-urlencoded\r\n",
									'method' => 'POST',
									'content' => http_build_query($data),
								],
							];

							$context = stream_context_create($options);
							$result = file_get_contents($url, false, $context);
							if(empty($msgtoswitch)){
								?> <h2><?php printf( esc_html__("%1\$s Version Activated.","email-otp-authenticator"),'<big style="text-transform: uppercase;">' . esc_html( $nextplugin ) . '</big>'); ?></h2><?php
							} else {
								if ($result) {
									?> <h2><?php printf( esc_html__("%1\$s Version Activated.","email-otp-authenticator"),'<big style="text-transform: uppercase;">' . esc_html( $nextplugin ) . '</big>'); ?></h2><span style="color:green;"><?php esc_html_e("Your important feedback has been sent.","email-otp-authenticator"); ?></span><?php
								} else {
									?> <h2><?php printf( esc_html__("%1\$s Version Activated.","email-otp-authenticator"),'<big style="text-transform: uppercase;">' . esc_html( $nextplugin ) . '</big>'); ?></h2><span style="color:green;"><?php esc_html_e("Your important feedback could not be sent.","email-otp-authenticator"); ?></span><?php
								}
							}
						} else {
							?><h2><?php esc_html_e("Version switch failed","email-otp-authenticator"); ?></h2><b><?php esc_html_e("Required file or directory permissions are not available, or the file is missing.","email-otp-authenticator"); ?></b><?php
						}
					}
				}
			}
		} else {
			$activate = '';
			$activated = '';
			if (file_exists(sprintf("%s/lib_new/", $dir_file))) {
				$activate = 'NEW';
				$activated = 'OLD';
			} elseif (file_exists(sprintf("%s/lib_old/", $dir_file))) {
				$activate = 'OLD';
				$activated = 'NEW';
			} else {
				?> <h2><?php esc_html_e("No alternative version available.","email-otp-authenticator"); ?></h2> <?php
			}
			if(!empty(trim($activate))){
				$nxtpfile = sprintf("%s/email-otp-authenticator.php_" . strtolower($activate) . "", $dir_file);
				$nxtpver = emailotpauthn_get_version($nxtpfile);
		?>
				<h2 style="color:#006600;">The <big style="text-transform: uppercase;"><?php echo esc_html( $activated ); ?></big> Version: <?php echo esc_html( EMAILOTPAUTHN_PLUGIN_VERSION ); ?> is Active.</h2>
				<form action="<?php the_permalink(); ?>" method="post">
					<input type="hidden" name="cmdswitch" value="<?php echo esc_html( $activate ); ?>">
					<?php wp_nonce_field( 'eotpa_switch_the_version', 'eotpa_switching_plugin_version' ); ?>
					<label for="msgswitch"><?php esc_html_e("Why do you want to switch ?","email-otp-authenticator"); ?> <small>( <?php esc_html_e("Please help me to improve.","email-otp-authenticator"); ?> )</small></label><br><textarea rows="6" cols="70" name="msgswitch" id="msgswitch" wrap="off" style="vertical-align:top;overflow-x: scroll; overflow-y: scroll;"  onkeyup="this.value = this.value.replace(/[^a-zA-Z0-9_ \-\/,.;:?()\n\r]/s, '')"/></textarea><br><br>
					<input type="submit" name="submit" value="Activate <?php echo esc_html( $activate . ' Version ' . $nxtpver ); ?>">
				</form>
		<?php }
		} ?>
	<br/>
	<h3><a href="admin.php?page=email-otp-authenticator" style="text-decoration:none;color:#000066;"><?php esc_html_e("Return to Settings","email-otp-authenticator"); ?></a></h3>
	
</div>