<?php
/**
* Plugin Name: Corsair Login
* Plugin URI: https://corsairnow.com/
* Description: Shortcode based login form
* Version: 3.0
* Author: Corsair
* Author URI: https://corsairnow.com/
* Text Domain: corsair-login
* Domain Path: /languages
*/

/**
 * Definitions
 *
 *
 */
define( 'CLOG_VERSION', '3.0' );
define( 'CLOG_PLUGIN_DIR', WP_PLUGIN_DIR . '/' . dirname( plugin_basename( __FILE__ ) ) );
define( 'CLOG_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'CLOG_CUSTOM_EMAIL_ADDRESS', __("amplivouser@amplivo.com" , "corsair-login"));

$login_page_url=get_option('login_page_url');
if($login_page_url!=''){
	add_filter( 'login_url', 'my_login_page', 10, 3 );
}
function my_login_page( $login_url, $redirect, $force_reauth ) {
	return get_login_url();
}
/**
 * Function that initiates the plugin text domain
 *
 * @since v.1.1.1
 *
 * @return void
 */
function cors_load_plugin_textdomain(){
	load_plugin_textdomain( 'corsair-login', false, CLOG_PLUGIN_URL . '/languages/' );
}
add_action('init', 'cors_load_plugin_textdomain');

/**
 * Function that creates the "Basic Information" submenu page
 *
 * @since v.1.1.1
 *
 * @return void
 */
function cors_register_basic_info_submenu_page() {
	$menu_enqueue = add_submenu_page( 'users.php', __( 'Corsair Login', 'corsair-login' ), __( 'Corsair Login', 'corsair-login' ), 'manage_options', 'corsair-login', 'cors_basic_info_content' );
	add_action( 'admin_print_scripts-' . $menu_enqueue, 'corsair_login_admin_menuonly_js' );
	add_action( 'admin_print_styles-' . $menu_enqueue, 'corsair_login_admin_menuonly_style' );
}
add_action( 'admin_menu', 'cors_register_basic_info_submenu_page', 15 );
function corsair_login_admin_menuonly_js(){
	wp_enqueue_script('jquery', "//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", array(),'3.5.1', false);
	wp_enqueue_script('cors_bootstrap_js', "//cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js", array('jquery'),'3.4.1', false);
	wp_enqueue_script('select2-script', "//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js", array('jquery'),'4.1.0', false);
}
function corsair_login_admin_menuonly_style(){
	wp_enqueue_style('cors_admin_bootstrap_css', '//cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css', array(), false, 'all');
	wp_enqueue_style('select2-css', '//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');
}
function cors_custom_settings(){
	register_setting('dboption-settings-group', 'dboption');
}
add_action('admin_init', 'cors_custom_settings');


function cors_basic_info_content() {
	if(isset($_POST['submit'])){
		update_option('sider_recaptcha', isset($_POST['sider_recaptcha']) ? $_POST['sider_recaptcha'] : '');
		update_option('local_user', isset($_POST['local_user']) ? $_POST['local_user'] : '');
		update_option('custom_login_field_label_toggle', isset($_POST['custom_login_field_label_toggle']) ? $_POST['custom_login_field_label_toggle'] : 0);
		update_option('custom_login_field_label', isset($_POST['custom_login_field_label']) ? $_POST['custom_login_field_label'] : '');
		update_option('local_custom_user', isset($_POST['local_custom_user']) ? $_POST['local_custom_user'] : '');
		update_option('local_custom_user_table', $_POST['local_custom_user_table']);
		update_option('local_custom_user_field', $_POST['local_custom_user_field']);
		update_option('local_custom_email_id', $_POST['local_custom_email_id']);
		update_option('external_user', isset($_POST['external_user']) ? $_POST['external_user'] : '');
		update_option('corsair_apisource', $_POST['corsair_apisource']);
		update_option('default_email_id', $_POST['default_email_id']);
		update_option('login_page_url', $_POST['login_page_url']);


		update_option('logout_redirect', $_POST['logout_redirect']);
		update_option('login_error_redirect', $_POST['login_error_redirect']);
		update_option('login_request_redirect', $_POST['login_request_redirect']);

		update_option('corsair_white_list_toggle', isset($_POST['corsair_white_list_toggle']) ? $_POST['corsair_white_list_toggle'] : 0);
		update_option('corsair_whitelist_emails', isset($_POST['whitelist_emails']) ? $_POST['whitelist_emails'] : '');
		update_option('token_timeout_time', ( isset($_POST['token_timeout_time']) && $_POST['token_timeout_time'] > 0 ) ? $_POST['token_timeout_time'] : 10);

		update_option('corsair_emailtmpl_logo', isset($_POST['corsair_emailtmpl_logo']) ? $_POST['corsair_emailtmpl_logo'] : '');
		update_option('corsair_emailtmpl_basecolor', isset($_POST['corsair_emailtmpl_basecolor']) ? $_POST['corsair_emailtmpl_basecolor'] : '');
		update_option('corsair_emailtmpl_headercss', isset($_POST['corsair_emailtmpl_headercss']) ? $_POST['corsair_emailtmpl_headercss'] : '');
		update_option('corsair_2fa_otp', isset($_POST['corsair_2fa_otp']) ? $_POST['corsair_2fa_otp'] : '');
		update_option('corsair_2fa_ga', isset($_POST['corsair_2fa_ga']) ? $_POST['corsair_2fa_ga'] : '');
	}
	$all_pages=get_all_internal_pages();
	?>
	<style>.whitelist_emails_td .select2-container{ width:100% !important; } body { background: #f0f0f1; color: #3c434a; } li.nav-item { list-style: none; }</style>
	<style>@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap"); .cors_setting_section{ font-family: "Montserrat", Sans-serif !important; }</style>
	<div class="wrap wpa-wrap wpa-info-wrap cors_setting_section">
		<h1><?php printf( __( '<strong>Corsair Login</strong> <small>v.</small>%s', 'corsair-login' ), CLOG_VERSION ); ?></h1>
		<p class="wpa-info-text"><?php printf( __( 'A front-end login form without a password.', 'corsair-login' ) ); ?></p>
		<p><strong style="font-size: 30px; vertical-align: middle; color:#d54e21;"><?php echo get_option('total_logins', '0'); ?></strong> <?php _e('successful logins without passwords.', 'corsair-login'); ?></p>
		<hr />
		<!-- Database Options Code -->
		<h3 class="title"><?php  printf( __( 'Passwordless Login settings.', 'corsair-login' ));?></h3>
		<?php settings_fields('dboption-settings-group'); ?>
		<form method="post" id="passwordless_settings">

			<ul class="nav nav-tabs">
				<li class="nav-item"><a class="nav-link active" data-toggle="tab" href="#general"><?php _e('General','corsair-login'); ?></a></li>
				<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#api_options"><?php _e('API Options','corsair-login'); ?></a></li>
				<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#redirect_url"><?php _e('Redirect URL','corsair-login'); ?></a></li>
				<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#white_list"><?php _e('White list','corsair-login'); ?></a></li>
				<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#email_template"><?php _e('Email template','corsair-login'); ?></a></li>
				<li class="nav-item"><a class="nav-link" data-toggle="tab" href="#two_fa"><?php _e('2FA','corsair-login'); ?></a></li>
			</ul>
			<div class="tab-content">
				<div id="general" class="container tab-pane active">
					<!--h3>General</h3> <!-- tab -->
					<table class="form-table- option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="sider_recaptcha"><?php echo __("Enable Captcha" , "corsair-login"); ?></label></th>
								<td><div class="form-group"><div class="checkbox"><input type="checkbox" id="sider_recaptcha" name="sider_recaptcha" value="yes" <?php echo checked( 'yes', get_option( 'sider_recaptcha' ), true ); ?>></div></div></td>
							</tr>

							<tr class="form-field-">
								<th scope="row"><label for="custom_login_field_label_toggle"><?php echo __("Add custom login field label?" , "corsair-login"); ?></label></th>
								<td>
								<div class="form-group"><div class="checkbox"><input type="checkbox" id="custom_login_field_label_toggle" name="custom_login_field_label_toggle" value="1" <?php checked( 1, get_option( 'custom_login_field_label_toggle' ) ); ?>/></div></div></td>
							</tr>

							<tr class="form-field- row-table_customlogfield" style = "display: <?php echo $display = ( get_option('custom_login_field_label_toggle') == 1 ) ? 'default' : 'none';?>" >
								<th scope="row"></th>
								<td><div class="form-group"><label for="custom_login_field_label"><?php echo __("Custom label text" , "corsair-login"); ?></label><input type="text" id="custom_login_field_label" name="custom_login_field_label" value="<?php echo get_option( 'custom_login_field_label' ); ?>" class="form-control" pattern=".*\S+.*"/></div></td>
							</tr>

							<tr class="form-field-">
								<th scope="row"><label for="local_user"><?php echo __("Allow Local WordPress users" , "corsair-login"); ?></label></th>
								<td><div class="form-group"><div class="checkbox"><input type="checkbox" id="local_user" name="local_user" value="yes" <?php checked( 'yes', get_option( 'local_user' ) ); ?>/></div></td>
							</tr>

							<tr class="form-field-">
								<th scope="row"><label for="local_custom_user"><?php echo __("Allow Local Custom users" , "corsair-login"); ?></label></th>
								<td><div class="form-group"><div class="checkbox"><input type="checkbox" id="local_custom_user" name="local_custom_user" value="yes" <?php checked( 'yes', get_option( 'local_custom_user' ) ); ?>/></div></div></td>
							</tr>

							<tr class="form-field- row-table_source" style = "display: <?php echo check_login_source(get_option( 'local_custom_user' ));?>" >
								<th scope="row"></th>
								<td><div class="form-group"><label for="local_custom_user_table"><?php echo __("Custom User Table" , "corsair-login"); ?></label><input type="text" id="local_custom_user_table" name="local_custom_user_table" value="<?php echo get_option( 'local_custom_user_table' ); ?>" class="regular-text form-control" pattern=".*\S+.*"/>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Custom user table name. This table will be use to login if email is exist." , "corsair-login"); ?></span>
									</span>
									</div>
									</td>
							</tr>

							<tr class="form-field- row-table_source" style = "display: <?php echo check_login_source(get_option( 'local_custom_user' ));?>" >
								<th scope="row"></th>
								<td>
									<div class="form-group">
									<label for="local_custom_user_field"><?php echo __("Custom User Field in Table" , "corsair-login"); ?></label>
									<input type="text" id="local_custom_user_field" name="local_custom_user_field" value="<?php echo get_option( 'local_custom_user_field' ); ?>" class="regular-text form-control" pattern=".*\S+.*"/>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Field in custom user table, Login will be check based on this field." , "corsair-login"); ?></span>
									</span>
									</div>
								</td>
							</tr>

							<tr class="form-field- row-table_source" style = "display: <?php echo check_login_source(get_option( 'local_custom_user' ));?>">
								<th scope="row"></th>
								<td>
									<div class="form-group">
									<label for="default_email_id"><?php echo __("Local Custom Email Id" , "corsair-login"); ?></label>
									<select id="local_custom_email_id" name="local_custom_email_id" class="regular-text form-control">
										<?php echo get_wp_user_options(get_option('local_custom_email_id'));?>
									</select>

									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Used to login, when email will be found in custom user table." , "corsair-login"); ?></span>
									</span>
									</div>
								</td>
							</tr>

							<tr class="form-field-">
								<th scope="row"><label for="login_page_url"><?php echo __("Login Page" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group">
									<select name="login_page_url" class="login_page_url">
										<option value=""><?php echo __("Select Page" , "corsair-login"); ?></option>
										<?php
										if(!empty($all_pages)):
											foreach ($all_pages as $key_page => $value_page):?>
												<option value="<?php echo $value_page->ID;?>" <?php echo get_selected_page($value_page->ID,get_option( 'login_page_url'));?>><?php echo get_the_title($value_page->ID);?> (<?php echo $value_page->post_name;?>)</option>
											<?php endforeach;?>
										<?php endif;?>
									</select>

									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("This will be disabled default wp admin access" , "corsair-login"); ?></span>
									</span>
									</div>
								</td>
							</tr>

						</tbody>
					</table>
				</div>

				<div id="api_options" class="container tab-pane fade">
					<!--h3>API Options</h3> <!-- tab -->
					<table class="form-table option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="external_user"><?php echo __("Allow external User List" , "corsair-login"); ?></label></th>
								<td>
									<input type="checkbox" id="external_user" name="external_user" value="yes" <?php checked( 'yes', get_option( 'external_user' ) ); ?>/>
								</td>
							</tr>

							<tr class="form-field- row-api_source" style = "display: <?php echo check_login_source(get_option( 'external_user' ));?>">
								<th scope="row"></th>
								<td>
									<div class="form-group">
									<label for="api_source"><?php echo __("API Source" , "corsair-login"); ?></label>
									<input type="text" id="corsair_apisource" name="corsair_apisource"  value="<?php echo get_option( 'corsair_apisource' ); ?>" class="regular-text form-control" pattern=".*\S+.*"/>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("e.g. https://yourapisite.com/api/userstatus/get. Note : Api email parameter will be use as <strong>'email'</strong>" , "corsair-login"); ?>
									</span>
									</span>
									</div>
								</td>
							</tr>

							<tr class="form-field- row-api_source" style = "display: <?php echo check_login_source(get_option( 'external_user' ));?>">
								<th scope="row"></th>
								<td>
									<div class="form-group">
									<label for="default_email_id"><?php echo __("External Custom Email Id" , "corsair-login"); ?></label>
									<select id="default_email_id" name="default_email_id" class="regular-text form-control">
										<?php echo get_wp_user_options(get_option('default_email_id'));?>
									</select>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Used to login, when email will be found in API." , "corsair-login"); ?></span>
									</span>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<div id="redirect_url" class="container tab-pane fade">
					<!-- h3>Redirect URL</h3> <!-- tab -->
					<table class="form-table option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="login_error_redirect"><?php echo __("Login Error Url" , "corsair-login"); ?></label></th>
								<td>
									<select name="login_error_redirect" class="login_error_redirect">
										<option value=""><?php echo __("Select Page" , "corsair-login"); ?></option>
										<?php
										if(!empty($all_pages)):
											foreach ($all_pages as $key_page => $value_page):?>
												<option value="<?php echo $value_page->ID;?>" <?php echo get_selected_page($value_page->ID,get_option( 'login_error_redirect'));?>><?php echo get_the_title($value_page->ID);?> (<?php echo $value_page->post_name;?>)</option>
											<?php endforeach;?>
										<?php endif;?>
									</select>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Redirect after faileed. Default is home url." , "corsair-login"); ?></span>
									</span>
								</td>
							</tr>
							<tr class="form-field-">
								<th scope="row"><label for="logout_redirect"><?php echo __("Logout Url" , "corsair-login"); ?></label></th>
								<td>
									<select name="logout_redirect" class="logout_redirect">
										<option value=""><?php echo __("Select Page" , "corsair-login"); ?></option>
										<?php
										if(!empty($all_pages)):
											foreach ($all_pages as $key_page => $value_page):?>
												<option value="<?php echo $value_page->ID;?>" <?php echo get_selected_page($value_page->ID,get_option( 'logout_redirect'));?>><?php echo get_the_title($value_page->ID);?> (<?php echo $value_page->post_name;?>)</option>
											<?php endforeach;?>
										<?php endif;?>
									</select>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Redirect after logout. Default is home url." , "corsair-login"); ?></span>
									</span>
								</td>
							</tr>
							<tr class="form-field-">
								<th scope="row"><label for="login_request_redirect"><?php echo __("Login Request" , "corsair-login"); ?></label></th>
								<td>
									<select name="login_request_redirect" class="login_request_redirect">
										<option value=""><?php echo __("Select Page" , "corsair-login"); ?></option>
										<?php
										if(!empty($all_pages)):
											foreach ($all_pages as $key_page => $value_page):?>
												<option value="<?php echo $value_page->ID;?>" <?php echo get_selected_page($value_page->ID,get_option( 'login_request_redirect'));?>><?php echo get_the_title($value_page->ID);?> (<?php echo $value_page->post_name;?>)</option>
											<?php endforeach;?>
										<?php endif;?>
									</select>
									<span class="tooltip">
										<span class="tooltiptext"><?php echo __("Redirect after succesfull login request. Default is login page." , "corsair-login"); ?></span>
									</span>
								</td>
							</tr>

							<tr class="form-field-">
								<th scope="row"><label for="token_timeout_time"><?php echo __("Token timeout (in minutes)" , "corsair-login"); ?></label></th>
								<td>
									<input type="number" id="token_timeout_time" name="token_timeout_time" value="<?php echo get_option( 'token_timeout_time' ); ?>" class="regular-text"/>
								</td>
							</tr>
							<tr>
								<td colspan="2" class="redirection_message" style="display: none;">
									<span class="redirection_notice"></span>
								</td>
							</tr>
							<tr class="form-field-">
								<td colspan="2">
									<table class="redirect-table">
										<tr>
											<th><?php echo __("User Role" , "corsair-login"); ?></th>
											<th><?php echo __("URL Source" , "corsair-login"); ?></th>
											<th class="source-heading"><?php echo __("Redirection Link" , "corsair-login"); ?></th>
											<th></th>
										</tr>
										<tr class="role-section">
											<td class="input_section">
												<div class="loading-image" id="lodingimages">
													<img src="<?php echo CLOG_PLUGIN_URL;?>/image/loading.gif">
												</div>
												<select name="user_role" class="user_role">
													<option value=""><?php echo __("Select User Role" , "corsair-login"); ?></option>
													<?php echo get_user_roll_option();?>
												</select>
												<span class="user-roll-error"></span>
											</td>
											<td class="input_section">
												<select name="url_source" class="url_source">
													<option value="internal"><?php echo __("Internal" , "corsair-login"); ?></option>
													<option value="external"><?php echo __("External" , "corsair-login"); ?></option>
												</select>
												<span class="url-source-error"></span>
											</td>
											<td class="input_section source-content">
												<select name="redirection_link" class="redirection_link">
													<option value=""><?php echo __("Select Page" , "corsair-login"); ?></option>
													<?php
													if(!empty($all_pages)):
														foreach ($all_pages as $key_page => $value_page):?>
															<option value="<?php echo $value_page->ID;?>"><?php echo get_the_title($value_page->ID);?> (<?php echo $value_page->post_name;?>)</option>
														<?php endforeach;?>
													<?php endif;?>
												</select>
												<span class="redirection-link-error"></span>
											</td>
											<td class="btn_section">
												<button type="button" class="button-primary btn-redirection"><?php echo __("ADD" , "corsair-login"); ?></button>
												<span class="corsair-error"></span>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr class="form-field">
								<th scope="row"><label for="redirect_url"><?php echo __("Redirection Rules" , "corsair-login"); ?></label></th>
								<td></td>
							</tr>
							<tr class="form-field-">
								<td colspan="2">
									<table class="redirection-rule">
										<tr>
											<th><?php echo __("User Role" , "corsair-login"); ?></th>
											<th><?php echo __("URL Source" , "corsair-login"); ?></th>
											<th><?php echo __("Redirection Link" , "corsair-login"); ?></th>
											<th><?php echo __("Status " , "corsair-login"); ?>
												<span class="tooltip">
													<span class="tooltiptext"><?php echo __("Drag to change status, Redirection will not work utill it is inactive " , "corsair-login"); ?></span>
												</span>
											</th>
											<th><?php echo __("Status " , "corsair-login"); ?></th>
										</tr>
										<?php echo get_all_redirection_rules();?>
									</table>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<div id="white_list" class="container tab-pane fade">
					<!--h3>White list</h3> <!-- tab -->
					<table class="form-table option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_white_list_toggle"><?php echo __("Enable white list?" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group"><div class="checkbox">
									<input type="checkbox" id="corsair_white_list_toggle" name="corsair_white_list_toggle" value="1" <?php checked( 1, get_option( 'corsair_white_list_toggle' ) ); ?>/>
									</div></div>
								</td>
							</tr>

							<tr class="form-field- row-table_white_list_section" style = "display: <?php echo $display = ( get_option('corsair_white_list_toggle') == 1 ) ? 'default' : 'none';?>" >
								<th></th>
								<td class="whitelist_emails_td">
									<?php $whitelist_emails = (array)get_option( 'corsair_whitelist_emails' ); ?>
									<div class="form-group">
									<label for="whitelist_emails"><?php echo __("White list email" , "corsair-login"); ?></label>
									<select class="regular-text form-control" name="whitelist_emails[]" id="whitelist_emails" multiple="multiple">
									<?php
									echo '<pre>'; print_r( $whitelist_emails ); echo '</pre>';
									if( !empty( $whitelist_emails ) ){
										foreach( $whitelist_emails as $whitelist_email ){
											if( !empty( $whitelist_email ) ){
											?><option value="<?php echo $whitelist_email ?>" selected><?php echo $whitelist_email ?></option><?php
											}
										}
									}
									?>
									</select>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<div id="email_template" class="container tab-pane fade">
					<!--h3>Email template</h3> <!-- tab -->
					<table class="form-table option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_emailtmpl_logo"><?php echo __("Template logo" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group">
									<input type="text" id="corsair_emailtmpl_logo" name="corsair_emailtmpl_logo" value="<?php echo get_option( 'corsair_emailtmpl_logo' ); ?>" class="regular-text form-control"/>
									</div>
								</td>
							</tr>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_emailtmpl_basecolor"><?php echo __("Template color css style" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group">
									<input type="text" id="corsair_emailtmpl_basecolor" name="corsair_emailtmpl_basecolor" value="<?php echo get_option( 'corsair_emailtmpl_basecolor' ); ?>" class="regular-text form-control"/>
									</div>
								</td>
							</tr>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_emailtmpl_headercss"><?php echo __("Template Header color css style" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group">
									<input type="text" id="corsair_emailtmpl_headercss" name="corsair_emailtmpl_headercss" value="<?php echo get_option( 'corsair_emailtmpl_headercss' ); ?>" class="regular-text form-control"/>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<div id="two_fa" class="container tab-pane fade">
					<h4>2 Factor Authentication</h4> <!-- tab -->
					<table class="form-table option-field">
						<tbody>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_2fa_otp"><?php echo __("Login using OTP" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group"><div class="checkbox"><input type="checkbox" id="corsair_2fa_otp" name="corsair_2fa_otp" value="yes" <?php echo checked( 'yes', get_option( 'corsair_2fa_otp' ), true ); ?>></div></div>
								</td>
							</tr>
							<tr class="form-field-">
								<th scope="row"><label for="corsair_2fa_ga"><?php echo __("Login using Google Authenticator" , "corsair-login"); ?></label></th>
								<td>
									<div class="form-group"><div class="checkbox"><input type="checkbox" id="corsair_2fa_ga" name="corsair_2fa_ga" value="yes" <?php echo checked( 'yes', get_option( 'corsair_2fa_ga' ), true ); ?>></div></div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

			</div>

			<p><?php submit_button(); ?></p>
		</form>
			<hr />
			<h2 class="wpa-callout"><?php echo __( 'Passwordless login for WordPress', 'corsair-login' ); ?></h2>
			<div class="wpa-row wpa-2-col">
				<div>
					<h3><?php echo __( '[corsair-login] shortcode', 'corsair-login' ); ?></h3>
					<p><?php echo __( 'Just place <strong class="nowrap">[corsair-login]</strong> shortcode in a page and you\'re good to go.', 'corsair-login' ); ?></p>
				</div>
				<div>
					<h3><?php echo __( 'An alternative to passwords', 'corsair-login'  ); ?></h3>
					<p><?php echo __( 'Passwordless Authentication <strong>dose not</strong> replace the default login functionality in WordPress. Instead you can have the two work in parallel.', 'corsair-login' ); ?></p>
				</div>
			</div>
			<hr/>
		</div>
		<div class="modal-overlay"></div>
		<div class="model-box redirection-model">
			<span class="exit"><?php echo __("x " , "corsair-login"); ?></span>
			<div class="redirection-form"></div>
		</div>
		<?php
	}

/**
 * Add scripts and styles to the back-end
 *
 * @since v.1.1.1
 *
 * @return void
 */
function cors_print_script( $hook ){
	if ( ( $hook == 'users_page_corsair-login' ) ){
		wp_enqueue_style( 'back-end-style', CLOG_PLUGIN_URL . 'assets/style-back-end.css', false, CLOG_VERSION );
		wp_enqueue_script( 'back-end-script', CLOG_PLUGIN_URL . 'assets/back_end.js', false, CLOG_VERSION);
		wp_localize_script('back-end-script', 'object', array('admin_ajax_url' => admin_url('admin-ajax.php')));
	}

}
add_action( 'admin_enqueue_scripts', 'cors_print_script' );

/**
 * Add scripts and styles to the front-end
 *
 * @since 1.1.1
 *
 * @return void
 */
function cors_add_plugin_stylesheet() {
	if (  file_exists( CLOG_PLUGIN_DIR . '/assets/style-front-end.css' )  ){
		wp_register_style( 'stylesheet', CLOG_PLUGIN_URL . 'assets/style-front-end.css' );
		wp_enqueue_style( 'stylesheet' );
		wp_enqueue_script('jquery');
		wp_enqueue_script( 'front-end-script', CLOG_PLUGIN_URL . 'assets/front_end.js', false, CLOG_VERSION);

		if(check_recaptcha()==true){
			wp_register_style( 'sider_recaptcha', CLOG_PLUGIN_URL . 'assets/sider_recaptcha.css' );
			wp_enqueue_style( 'sider_recaptcha' );
			wp_enqueue_script( 'sider_recaptcha-script', CLOG_PLUGIN_URL . 'assets/sider_recaptcha.js', false, CLOG_VERSION);
		}

	}

	/**
	 * New login script
	 */
	wp_enqueue_script('sweetalert', "//cdn.jsdelivr.net/npm/sweetalert2@7.32.4/dist/sweetalert2.all.min.js", array('jquery'),'7.32.4', false);
	wp_enqueue_script( 'blockUI', '//cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js', array('jquery'),'2.70' , true );
	wp_enqueue_script(
		'corsairlogin',
		CLOG_PLUGIN_URL . '/assets/ajax-login.js',
		array('jquery'),
		time(),
		true
	 );
	$actionResetAuth = [ 'action' => 'cl_reset2faauth_act','_micro' => wp_create_nonce( '_XyReset2FaAuthyX_' ) ];
	$actionResetPwd = [ 'action' => 'cl_resetpwd_act','_micro' => wp_create_nonce( '_XyResetPWDLinkyX_' ) ];
	$actionToggleLogin = [ 'action' => 'cl_togglelogin_act','_micro' => wp_create_nonce( '_XyToggleLoginEnableX_' ) ];
	$actionToggleWithdrawal = [ 'action' => 'cl_togglewithdrawal_act','_micro' => wp_create_nonce( '_XyToggleWithdrawalSuspendX_' ) ];

	$logout_time_config = get_option('logout_time_config');
	$sasm_logout_time_config = get_option('sasm_logout_time_config');

	if( current_user_can('administrator') || current_user_can('supportmanager') || current_user_can('supportagent') || current_user_can('member_assistant') ){
		$logout_time = ( !empty( $sasm_logout_time_config ) && $sasm_logout_time_config > 0 ) ? 60000 * $sasm_logout_time_config : 60000 * 120;
	}else{
		$logout_time = ( !empty( $logout_time_config ) && $logout_time_config > 0 ) ? 60000 * $logout_time_config : 60000 * 20;
	}

	$is_user_logged_in = ( is_user_logged_in() ) ? 1 : 0;
	$is_admin_login = ( current_user_can('administrator') || current_user_can('supportmanager') || current_user_can('supportagent')  ) ? 1 : 0;

	wp_localize_script(
		'corsairlogin',
		'corsairloginData',
		array(
		   'ajaxUrl' => admin_url('admin-ajax.php'),
		   'loginUrl' => get_login_url(),
		   'resetRequestUrl' => home_url('request-reset-link'),
		   'homeUrl' => home_url(),
		   'profileUrl' => get_the_permalink( get_page_by_path('content/operations/member/my-profile') ),
		   'actionResetAuth' => $actionResetAuth,
		   'actionResetPwd' => $actionResetPwd,
		   'actionToggleLogin' => $actionToggleLogin,
		   'actionToggleWithdrawal' => $actionToggleWithdrawal,
		   'idleLogoutTime' => $logout_time,
		   'isLoggedInUser' => $is_user_logged_in,
		   'isAdminLoggedIn' => $is_admin_login,
		)
	);

	wp_enqueue_script( 'bs-popper', '//cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js', array( 'jquery' ), '1.16.0', true );
	wp_enqueue_script( 'bs-js', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array( 'jquery' ), '4.3.1', true );
	wp_register_script( 'bs-table', plugin_dir_url( __FILE__ ). 'assets/bootstrap-table.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_script( 'bs-table-filter-control', plugin_dir_url( __FILE__ ).'assets/bootstrap-table-filter-control.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_script( 'bs-sticky-header', plugin_dir_url( __FILE__ ).'assets/bootstrap-table-sticky-header.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_style( 'bs-table', plugin_dir_url( __FILE__ ).'assets/bootstrap-table.min.css', array(), '1.18.3', 'all' );
	wp_register_style( 'bs-sticky-header', '//unpkg.com/bootstrap-table@1.18.3/dist/extensions/sticky-header/bootstrap-table-sticky-header.css', array(), '1.18.3', 'all' );
	wp_enqueue_style( 'bs-css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', array(), '4.3.1', 'all' );

}
add_action( 'wp_print_styles', 'cors_add_plugin_stylesheet' );

function cors_front_end_sider_script() {
	if(check_recaptcha()==true){
		?>
		<script>
			var captcha = sliderCaptcha({
				id: "captcha",
				repeatIcon: "fa fa-redo",
				onSuccess: function () {
					console.log("all good");
					var handler = setTimeout(function () {
						window.clearTimeout(handler);
						captcha.reset();
					}, 500);
				},
			});
		</script>
		<?php
	}
}
add_action('wp_footer', 'cors_front_end_sider_script');


/**
 * Shortcode for the corsair login form
 *
 * @since 1.1.1
 *
 * @return html
 */
function cors_output_buffer() {
	ob_start();
}
add_action('init', 'cors_output_buffer');

function cors_front_end_login(){
	ob_start();
	$account = ( isset( $_POST['user_email']) ) ? $account = sanitize_text_field( $_POST['user_email'] ) : false;
	$nonce = ( isset( $_POST['nonce']) ) ? $nonce = sanitize_key( $_POST['nonce'] ) : false;
	$error_token = ( isset( $_GET['error_token']) ) ? $error_token = sanitize_key( $_GET['error_token'] ) : false;
	$adminapp_error = ( isset( $_GET['adminapp_error']) ) ? sanitize_key( $_GET['adminapp_error'] ) : false;
	$get_login_error_url= get_login_error_url();
	$white_list_toggle = ( get_option( 'corsair_white_list_toggle' ) ) ? get_option( 'corsair_white_list_toggle' ) : 0;
	if( $account && $white_list_toggle ){
		$whitelist_emails = (array)get_option( 'corsair_whitelist_emails' );
		if( !in_array( $account, $whitelist_emails) ){
			wp_redirect($get_login_error_url);
			exit;
		}
	}

	/* $sent_link = cors_send_link($account, $nonce);
	$login_request_url= get_login_request_url();
	if( $account && !is_wp_error($sent_link) ){
		if($login_request_url!=''){
			wp_redirect($login_request_url);
			exit();
		}
		else{
			echo '<p class="wpa-box wpa-success">'. apply_filters('success_link_msg', __('Please check your email. You will soon receive an email with a login link.', 'corsair-login') ) .'</p>';
		}
	} else */
	if ( is_user_logged_in() ) {
	    ?>
		<style>
		.Login-guest-section{display:none !important;}
		.Product-step-0{display:block;}
		</style>
	    <?php
		$current_user = wp_get_current_user();
		echo '<p class="wpa-box wpa-alert">'.apply_filters('success_login_msg', sprintf(__( 'You are currently logged in as %1$s. %2$s', 'corsair-login' ), '<a href="'.$authorPostsUrl = get_author_posts_url( $current_user->ID ).'" title="'.$current_user->display_name.'">'.$current_user->display_name.'</a>', '<a href="'.wp_logout_url( $redirectTo = cors_curpageurl() ).'" title="'.__( 'Log out of this account', 'corsair-login' ).'">'. __( 'Log out', 'corsair-login').' &raquo;</a>' ) ) . '</p><!-- .alert-->';
	} else {

		/* if ( is_wp_error($sent_link) ){
			echo '<p class="wpa-box wpa-error">' . apply_filters( 'error', $sent_link->get_error_message() ) . '</p>';
		}

		if( $error_token ) {
			echo '<p class="wpa-box wpa-error">' . apply_filters( 'invalid_token_error', __('Your token has probably expired. Please try again.', 'corsair-login') ) . '</p>';
		}

        if( $adminapp_error ) {//admin approval compatibility
        	echo '<p class="wpa-box wpa-error">' . apply_filters( 'admin_approval_error', __('Your account needs to be approved by an admin before you can log-in.', 'corsair-login') ) . '</p>';
        } */

        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );

        $custom_label = get_option( 'custom_login_field_label' );
        $custom_label_toggle = get_option( 'custom_login_field_label_toggle' );
        $label = __('Email Address', 'corsair-login');
        if( !empty( $custom_label ) && $custom_label_toggle == 1 ){
        	$label = $custom_label;
        }
		$passwordLabel = __('Password', 'corsair-login');
        ?>
        <!-- shoud not show this untill check box checked -->
        <?php if(check_recaptcha()==true):?>
        	<div class="slidercaptcha card">
        		<div class="card-body">
        			<div id="captcha"></div>
        		</div>
        	</div>
        <?php endif;?>
        <!-- endof slider captcha-->
        <div id="corsair-login" style="display: <?php echo check_recaptcha_style();?>;">
        	<form name="wpaloginform" id="wpaloginform" action="" method="post">

				<section class="login_section">
				<div class="email_section">
					<label for="user_email"><?php echo( apply_filters('change_form_label', $label)) ; ?></label>
					<input type="email" name="user_email" id="user_email" class="input" value="<?php echo esc_attr( $account ); ?>" size="25" required />
				</div>

				<div class="password_section" style="display: none;">

					<div class="form-group">
						<label for="user_password"><?php echo( apply_filters('change_form_password_label', $passwordLabel)) ; ?></label>
						<div class="input-group-append align-items-center toggle_password">
						<input type="password" name="user_password" id="user_password" class="input" size="25" autocomplete="off" disabled />
							<div class="input-group-addon pl-1 pr-1"><a href="javascript:void(0);" tabindex="-1"><i class="fa fa-eye-slash" aria-hidden="true"></i></a></div>
						</div>
					</div>

				</div>

				<div class="password_section" style="display: none;">
				<label class="remember-checklist" for="remember">
					<input type="checkbox" name="remember" id="remember" value="1" class="input"><?php _e('Remember me', 'corsair-login'); ?>
				</label>
				</div>

				<input type="submit" name="wpa-submit" id="wpa-submit" class="button-primary" value="<?php esc_attr_e('Log In', 'corsair-login'); ?>" />
				</section>

				<section class="otp_section"></section>

        		<?php do_action('login_form'); ?>
        		<?php wp_nonce_field( 'corsair_login_request', 'micro_nonce', false ) ?>
				<input type="hidden" name="action" value="corsair_user_login" />
			</form>
			<!--div class="password_section" style="display: none;">
				<p class="signup_user_link"><?php //_e('Don\'t have a password?','corsair-login'); ?> <a href="<?php //echo home_url( 'request-reset-link' ); ?>"> <?php //_e('Reset password','corsair-login'); ?> </a></p>
			</div-->
			<div class="password_section" style="display: none;">
				<p class="signup_user_link"><?php _e('Forgot password,','corsair-login'); ?> <a href="<?php echo home_url( 'request-reset-link' ); ?>"> <?php _e('click here to reset','corsair-login'); ?> </a></p>
			</div>

			<div class="email_not_recognized_section">
				<p><?php _e('Email address not recognized?','corsair-login'); ?> </p><p><?php _e('Click','corsair-login'); ?> <strong><a href="<?php echo get_the_permalink( 2537 ); ?>"><?php _e('here','corsair-login'); ?></a></strong></p>
			</div>

        </div>
        <?php
    }

    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
add_shortcode( 'corsair-login', 'cors_front_end_login' );
/**
 * New login script
 */
add_shortcode( 'corsair-request-reset-password', 'cors_front_end_request_reset_password' );
function cors_front_end_request_reset_password(){
	ob_start();
	$attributes['errors'] = array();
	if ( isset( $_REQUEST['error'] ) ) {
		$error_codes = explode( ',', $_REQUEST['error'] );
		foreach ( $error_codes as $error_code ) {
			$attributes['errors'] []= get_error_message( $error_code );
		}
	}
	if ( count( $attributes['errors'] ) > 0 ) : ?>
    <?php foreach ( $attributes['errors'] as $error ) : ?>
        <p class="wpa-box wpa-error"><?php echo $error; ?></p>
    <?php endforeach; ?>
	<?php endif; ?>

	<?php
	if ( is_user_logged_in() ) {
		$current_user = wp_get_current_user();
		echo '<p class="wpa-box wpa-alert">'.apply_filters('success_login_msg', sprintf(__( 'You are currently logged in as %1$s. %2$s', 'corsair-login' ), '<a href="'.$authorPostsUrl = get_author_posts_url( $current_user->ID ).'" title="'.$current_user->display_name.'">'.$current_user->display_name.'</a>', '<a href="'.wp_logout_url( $redirectTo = cors_curpageurl() ).'" title="'.__( 'Log out of this account', 'corsair-login' ).'">'. __( 'Log out', 'corsair-login').' &raquo;</a>' ) ) . '</p><!-- .alert-->';
	}else { ?>
		<!-- shoud not show this untill check box checked -->
		<?php if(check_recaptcha()==true):?>
			<div class="slidercaptcha card">
				<div class="card-body">
					<div id="captcha"></div>
				</div>
			</div>
		<?php endif;?>
		<!-- endof slider captcha-->
		<div id="corsair-login" style="display: <?php echo check_recaptcha_style();?>;">
			<form name="wparesetpwdform" id="wparesetpwdform" autocomplete='off'>

				<label for="user_email"><?php _e('Email address *', 'corsair-login'); ?></label>
				<input type="email" name="user_email" id="user_email" class="input" autocomplete='off' required />
				<input type="submit" name="wpa-submit" id="wpa-submit" class="button-primary" value="<?php esc_attr_e('Send password reset link', 'corsair-login'); ?>" />

				<div class="fog-pwd">
					<a href="<?php echo get_login_url(); ?>"><?php _e('Back to login', 'corsair-login'); ?></a></br>
				</div>
				<?php do_action('register_form'); ?>
				<?php wp_nonce_field( 'corsair_reset_password_request', 'micro_nonce', false ) ?>
				<input type="hidden" name="action" value="corsair_user_reset_password" />
			</form>
		</div>
	<?php }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
add_shortcode( 'corsair-reset-password', 'cors_front_end_reset_password' );
function cors_front_end_reset_password(){
	ob_start();
	if ( is_user_logged_in() ) {
		$current_user = wp_get_current_user();
		echo '<p class="wpa-box wpa-alert">'.apply_filters('success_login_msg', sprintf(__( 'You are currently logged in as %1$s. %2$s', 'corsair-login' ), '<a href="'.$authorPostsUrl = get_author_posts_url( $current_user->ID ).'" title="'.$current_user->display_name.'">'.$current_user->display_name.'</a>', '<a href="'.wp_logout_url( $redirectTo = cors_curpageurl() ).'" title="'.__( 'Log out of this account', 'corsair-login' ).'">'. __( 'Log out', 'corsair-login').' &raquo;</a>' ) ) . '</p><!-- .alert-->';
	} else {

        list( $rp_path ) = explode( '?', wp_unslash( $_SERVER['REQUEST_URI'] ) );
		$rp_cookie       = 'wp-resetpass-' . COOKIEHASH;

		if ( isset( $_GET['key'] ) && isset( $_GET['login'] ) ) {
			$value = sprintf( '%s:%s', wp_unslash( $_GET['login'] ), wp_unslash( $_GET['key'] ) );
			setcookie( $rp_cookie, $value, 0, '/', COOKIE_DOMAIN, is_ssl(), true );

			wp_safe_redirect( remove_query_arg( array( 'key', 'login' ) ) );
			exit;
		}

		if ( isset( $_COOKIE[ $rp_cookie ] ) && 0 < strpos( $_COOKIE[ $rp_cookie ], ':' ) ) {
			list( $rp_login, $rp_key ) = explode( ':', wp_unslash( $_COOKIE[ $rp_cookie ] ), 2 );

			$user = check_password_reset_key( $rp_key, $rp_login );

			if ( isset( $_POST['pass1'] ) && ! hash_equals( $rp_key, $_POST['rp_key'] ) ) {
				$user = false;
			}
		} else {
			$user = false;
		}

		if ( ! $user || is_wp_error( $user ) ) {
			setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true );

			if ( $user && $user->get_error_code() === 'expired_key' ) {
				wp_redirect( site_url( 'request-reset-link?error=expiredkey' ) );
			} else {
				wp_redirect( site_url( 'request-reset-link?error=invalidkey' ) );
			}
			exit;
		}
		$rp_loginEncrypt = base64_encode( urlencode( $rp_login ) . md5('CLRPLOGIN'));
		?>
		<div id="corsair-login">
			<form name="wparesetpassform" id="wparesetpassform" autocomplete="off">
				<input type="hidden" name="user_login" id="user_login" value="<?php echo esc_attr( $rp_loginEncrypt ); ?>" autocomplete="off" />
				<div class="form-group user-pass1-wrap">
					<p class="mb-0"><label for="pass1"><?php _e( 'New password', 'corsair-login' ); ?></label></p>
					<div class="input-group-append align-items-center wp-pwd toggle_password">
						<input type="password" name="pass1" id="pass1" class="input password-input" value="" autocomplete="new-password" />
						<div class="input-group-addon pl-1 pr-1"><a href="javascript:void(0);" tabindex="-1"><i class="fa fa-eye-slash" aria-hidden="true"></i></a></div>
					</div>

					<!--div class="form-group">
						<label for="backupkey"><?php //_e('Enter Backup Key', 'corsair-login'); ?></label>
						<div class="input-group-append align-items-center" id="show_hide_password">
							<input class="form-control" type="password" name="key" id="backupkey" />
							<div class="input-group-addon pl-1 pr-1"><a href="javascript:void(0);"><i class="fa fa-eye-slash" aria-hidden="true"></i></a></div>
						</div>
					</div-->

				</div>

				<div class="form-group user-pass2-wrap">
					<p class="mb-0"><label for="pass2"><?php _e( 'Confirm new password', 'corsair-login' ); ?></label></p>
					<div class="input-group-append align-items-center wp-pwd toggle_password">
						<input type="password" name="pass2" id="pass2" class="input" value="" autocomplete="new-password" />
						<div class="input-group-addon pl-1 pr-1"><a href="javascript:void(0);" tabindex="-1"><i class="fa fa-eye-slash" aria-hidden="true"></i></a></div>
					</div>
				</div>
				<em><p><?php _e('Note: Password must be at least 8 characters and contain at least one number.', 'corsair-login'); ?></p></em>

				<input type="hidden" name="rp_key" value="<?php echo esc_attr( $rp_key ); ?>" />
				<p class="submit reset-pass-submit">
					<input type="submit" name="wp-submit" id="wpa-submit" class="button-primary" value="<?php esc_attr_e( 'Save Password', 'corsair-login' ); ?>" />
				</p>
				<?php wp_nonce_field( 'corsair_reseting_password', 'micro_nonce', false ) ?>
				<input type="hidden" name="action" value="corsair_user_reseting_password" />
			</form>
		</div>
		<?php
    }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

function corsair_refAccount_shortcode(){
	$refAccount='';
	if(isset($_SESSION['refAccount']) && $_SESSION['refAccount']!=''){

		$refAccount=$_SESSION['refAccount'];
	}
	return $refAccount;

}

add_shortcode( 'corsair-refAccount', 'corsair_refAccount_shortcode' );

/**
 * Checks to see if an account is valid.
 *
 * @since v.1.1.1
 *
 * @return bool / WP_Error
 */
function cors_valid_account( $account ){
	$login_error_url= get_login_error_url();
	$return_account = new WP_Error( 'invalid_account', __( 'The email you provided do not exist. Please try again.', 'corsair-login' ) );
	if(check_local_user()==false && check_local_custom_user()==false && check_external_user()==false){
		wp_redirect($login_error_url);
		exit();
// 		return new WP_Error( 'invalid_account', __( 'The email you provided do not exist. Please try again.', 'corsair-login' ) );
	}
	if( is_email( $account )) {
		$account = sanitize_email( $account );
	} else {
		wp_redirect($login_error_url);
		exit();
//		return new WP_Error( 'invalid_account', __( 'The email you provided do not exist. Please try again.', 'corsair-login' ) );
	}


	if(check_local_user()==true){
		if( email_exists( $account )) {
			$wpUser = get_user_by( 'email', $account );
			$cip_user_status = get_user_meta( $wpUser->ID, 'cip_user_status', true );
			if( $cip_user_status === 'deactive' ){
				/*wp_redirect($login_error_url);
				exit();*/
				return new WP_Error( 'account_deactive', __( 'Your account is deactive.', 'corsair-login' ) );
			}else{
				return $account;
			}
		}
	}
	if(check_local_custom_user()==true){
		$validEmail = false;
		global $wpdb;
		$tableNameArr = explode( ',', get_option( 'local_custom_user_table') );
		$fieldNameArr = explode( ',', get_option( 'local_custom_user_field') );
		if( $tableNameArr ){
			foreach( $tableNameArr as $key => $tableNameLoop ){
				if( !$validEmail ){
					$table_name = $wpdb->prefix . $tableNameLoop;
					$field_name=get_option( 'local_custom_user_field');
					$validEmail = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE ".$fieldNameArr[$key]." = '" . $account . "'") > 0 ? true : false;
				}
			}
		}

		if($validEmail == true){
			return get_option( 'local_custom_email_id');
		}
		/* else {
			wp_redirect($login_error_url);
			exit();

//			return new WP_Error( 'invalid_account', __( 'The email you provided do not exist. Please try again.', 'corsair-login' ) );
		} */
	}
	// shoud not check this unless check box checked
	if(check_external_user()==true){
		$check_email_in_api=corsair_get_users_from_sourceapi($account);
		if($check_email_in_api==true){
			return get_login_email_address();
		}
		/* else {
			wp_redirect($login_error_url);
			exit();

		//	return new WP_Error( 'invalid_account', __( 'The email you provided do not exist. Please try again.', 'corsair-login' ) );
		} */
	}
	// shoud not check this unless check box checked
	return $return_account;
}

/**
 * Sends an email with the unique login link.
 *
 * @since v.1.1.1
 *
 * @return bool / WP_Error
 */
function cors_send_link( $email_account = false, $nonce = false ){
	if ( $email_account  == false ){
		return false;
	}
	$valid_email = cors_valid_account( $email_account  );
	$errors = new WP_Error;
	if (is_wp_error($valid_email)){
		$errors->add('invalid_account', $valid_email->get_error_message());
	} else{
		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
		add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
		add_filter( 'wp_mail_from_name', function(){ return sprintf( __( 'Login Request %s','corsair-login'), get_option('blogname') ); } );

		//Filters to change the content type of the email
		add_filter('wp_mail_content_type', function(){ return "text/html"; } );

		$encryptedRefEmail = encrypt($email_account, $nonce . "Corssair2021");

		$unique_url = cors_generate_url( $valid_email , $nonce, rawurlencode($encryptedRefEmail) );
		$subject = apply_filters('email_subject', sprintf(__("Your login link for %s", 'corsair-login'), $blogname));

		$htmlurl = plugin_dir_url(__FILE__).'mail_template.html';
		$htmlContent = file_get_contents($htmlurl);

		$token_timeout = get_token_timeout_time();
		$minute_text = sprintf( _n( '%s minute', '%s minutes', $token_timeout, 'corsair-login' ), $token_timeout );

		$message = apply_filters('email_message', sprintf(__('%s <br><br> This is an e-mail from %s. <br> Click the button below to sign in to your account. <br> <p><a href="%s" target="_blank" REPLACE_STYLE>Please click here for login</a></p> <br> This link will expire in %s. <br> If the button above does not work, paste this link into your web browser: <br><br> %s <br><br> If you did not make this request, you can safely ignore this e-mail.', 'corsair-login'), $blogname, $blogname, esc_url($unique_url), $minute_text, esc_url($unique_url) ) );

		$corsair_emailtmpl_logo = ( get_option( 'corsair_emailtmpl_logo' ) ) ? get_option( 'corsair_emailtmpl_logo') : '';
		$corsair_emailtmpl_basecolor = ( get_option( 'corsair_emailtmpl_basecolor' ) ) ? get_option( 'corsair_emailtmpl_basecolor') : '';
		$corsair_emailtmpl_headercss = ( get_option( 'corsair_emailtmpl_headercss' ) ) ? get_option( 'corsair_emailtmpl_headercss') : '';


		$htmlContent = str_replace('REPLACE_MESSAGE', $message, $htmlContent);
		$htmlContent = str_replace('REPLACE_SITEURL', site_url(), $htmlContent);
		$htmlContent = str_replace('REPLACE_COPYRIGHT', 'Copyright © Amplivo.com '.date('Y').'. All rights reserved.', $htmlContent);
		$htmlContent = str_replace('REPLACE_HEADER_LOGO', $corsair_emailtmpl_logo, $htmlContent);
		$htmlContent = str_replace('REPLACE_STYLE', 'style="font-size: 18px; font-family: Arial, Helvetica, sans-serif; color: #ffffff; text-decoration: none; padding: 6px 24px; display: inline-block;'.$corsair_emailtmpl_basecolor.'"', $htmlContent);
		$htmlContent = str_replace('REPLACE_FOOTER_STYLE', $corsair_emailtmpl_basecolor, $htmlContent);
		$htmlContent = str_replace('REPLACE_HEADER_STYLE', $corsair_emailtmpl_headercss, $htmlContent);

		$sent_mail = wp_mail( $email_account, $subject, $htmlContent );

		if ( !$sent_mail ){
			$errors->add('email_not_sent', __('There was a problem sending your email. Please try again or contact an admin.', 'corsair-login'));
		}
		if( $sent_mail && is_page( 4258 ) ){
			$_SESSION['buypageid'] = $buyid;
		}
	}
	$error_codes = $errors->get_error_codes();

	if (empty( $error_codes  )){
		return false;
	}else{
		return $errors;
	}
}

/**
 * Generates unique URL based on UID and nonce
 *
 * @since v.1.1.1
 *
 * @return string
 */
function cors_generate_url( $email = false, $nonce = false ,$ref=false){
	if ( $email  == false ){
		return false;
	}
	/* get user id */
	$user = get_user_by( 'email', $email );
	$token = cors_create_onetime_token( $user->ID, $user->ID  );

	$arr_params = array( 'error_token', 'uid', 'token', 'nonce','ref' );
	$url = remove_query_arg( $arr_params, cors_curpageurl() );

	if( is_page( 4258 ) ){
		$url_params = array('uid' => $user->ID, 'token' => $token, 'nonce' => $nonce,'ref'=>$ref,'buypage'=>1);
	}else{
		$url_params = array('uid' => $user->ID, 'token' => $token, 'nonce' => $nonce,'ref'=>$ref);
	}
	$url = add_query_arg($url_params, $url);

	return $url;
}

/**
 * Automatically logs in a user with the correct nonce
 *
 * @since v.1.1.1
 *
 * @return string
 */
add_action( 'init', 'cors_autologin_via_url' );
function cors_autologin_via_url(){
	if( isset( $_GET['token'] ) && isset( $_GET['uid'] ) && isset( $_GET['nonce'] ) ){
		session_start();
		$ref = ( $_GET['ref'] );
		$uid = sanitize_key( $_GET['uid'] );
		$token  =  sanitize_key( $_REQUEST['token'] );
		$nonce  = sanitize_key( $_REQUEST['nonce'] );
		$buypage = ( isset( $_GET['buypage'] ) && $_GET['buypage'] == 1 ) ? 1 : 0 ;
		if( $buypage ){
			$redirect_url= get_permalink( 4258 );
		}else{
			$redirect_url=get_redirect_url($uid);
		}
		// $hash_meta = get_user_meta( $uid, $uid, true);
		// $hash_meta_expiration = get_user_meta( $uid, $uid . '_expiration', true);
		$arr_params = array( 'uid', 'token', 'nonce', 'ref' );
		$current_page_url = remove_query_arg( $arr_params, cors_curpageurl() );

		require_once( ABSPATH . 'wp-includes/class-phpass.php');
		$wp_hasher = new PasswordHash(8, TRUE);
		$time = time();

		$hash_meta = ( isset( $_SESSION['corsairTknHash'] ) && !empty( $_SESSION['corsairTknHash'] ) ) ? $_SESSION['corsairTknHash'] : 0;
		$hash_meta_expiration = ( isset( $_SESSION['corsairTknExpiration'] ) && !empty( $_SESSION['corsairTknExpiration'] ) ) ? $_SESSION['corsairTknExpiration'] : 0;

		if ( ! $wp_hasher->CheckPassword($token . $hash_meta_expiration, $hash_meta) || ! wp_verify_nonce( $nonce, 'corsair_login_request' ) ){
			wp_redirect( $current_page_url . '?error_token=true' );
			exit;
		}else {
			wp_set_auth_cookie( $uid );
			// delete_user_meta($uid, $uid );
			// delete_user_meta($uid, $uid . '_expiration');

			$_SESSION["corsairTknHash"] = 0;
			$_SESSION["corsairTknExpiration"] = 0;
			unset($_SESSION["corsairTknHash"]);
			unset($_SESSION["corsairTknExpiration"]);

			$total_logins = get_option( 'total_logins', 0);
			update_option( 'total_logins', $total_logins + 1);

			$refEmail = rawurldecode($ref);
			$email = decrypt($refEmail,$nonce . "Corssair2021");

			$_SESSION['refAccount']=$email;
			wp_redirect( apply_filters('after_login_redirect', $redirect_url) );

			exit;
		}
	}
}

/**
 * Create a nonce like token that you only use once based on transients
 *
 *
 * @since v.1.1.1
 *
 * @return string
 */
function cors_create_onetime_token( $action = -1, $user_id = 0 ) {
	$time = time();

	// random salt
	$key = wp_generate_password( 20, false );

	require_once( ABSPATH . 'wp-includes/class-phpass.php');
	$wp_hasher = new PasswordHash(8, TRUE);
	$string = $key . $action . $time;

	// we're sending this to the user
	$token  = wp_hash( $string );
	$token_timeout = get_token_timeout_time();
	$expiration = apply_filters('change_link_expiration', $time + 60 * $token_timeout);
	$expiration_action = $action . '_expiration';

	// we're storing a combination of token and expiration
	$stored_hash = $wp_hasher->HashPassword( $token . $expiration );

	// update_user_meta( $user_id, $action , $stored_hash ); // adjust the lifetime of the token. Currently 10 min.
	// update_user_meta( $user_id, $expiration_action , $expiration );

	$_SESSION['corsairTknHash'] = $stored_hash;
	$_SESSION['corsairTknExpiration'] = $expiration;

	return $token;
}
//add_action('wp_footer','testtesttest');
function testtesttest(){
	$maxlifetime = ini_get("session.gc_maxlifetime");
	// echo '<br/>'.$maxlifetime;
}
function get_token_timeout_time(){
	$token_timeout_time = get_option( 'token_timeout_time' );
	$token_timeout = ( !empty( $token_timeout_time ) && $token_timeout_time > 0 ) ? $token_timeout_time : 10;
	return $token_timeout;
}

/**
 * Returns the current page URL
 *
 * @since v.1.1.1
 *
 * @return string
 */
function cors_curpageurl() {
	$req_uri = $_SERVER['REQUEST_URI'];

	$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
	$home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );

    // Trim path info from the end and the leading home path from the front.
	$req_uri = ltrim($req_uri, '/');
	$req_uri = preg_replace( $home_path_regex, '', $req_uri );
	$req_uri = trim(home_url(), '/') . '/' . ltrim( $req_uri, '/' );

	return $req_uri;
}

add_filter( 'logout_redirect','corsair_redirect_after_logout' );
function corsair_redirect_after_logout() {
	return get_logout_redirect_url();

}

function corsair_my_session(){
	if( !session_id() ){
		session_start();
	}
}

add_action('init', 'corsair_my_session');

add_action( 'wp_logout', 'corsair_unset_refAccount' );
function corsair_unset_refAccount() {
	$_SESSION['refAccount'] = "";
	unset( $_SESSION['refAccount'] );
	$_SESSION = array();
	session_unset();
	session_destroy();
}
add_action( 'clear_auth_cookie', 'corsair_clear_auth_cookie_refAccount' );
function corsair_clear_auth_cookie_refAccount() {
	$_SESSION['refAccount'] = "";
	unset( $_SESSION['refAccount'] );
	$_SESSION = array();
	session_unset();
	session_destroy();
}
add_action( 'login_form', 'corsair_login_form_refAccount_clear' );
function corsair_login_form_refAccount_clear() {
	$_SESSION['refAccount'] = "";
	unset( $_SESSION['refAccount'] );
}
/**
 * Add notices on plugin activation.
 *
 * @since v.1.1.1
 *
 * @return string
 */

include_once("inc/wpa.class.notices.php");
$learn_more_notice = new WPA_Add_Notices(
	'learn_more',
	sprintf( __( '<p>Use [corsair-login] shortcode in your pages or widgets. %1$sLearn more.%2$s  %3$sDismiss%4$s</p>', 'corsair-login'), "<a href='users.php?page=corsair-login&learn_more_dismiss_notification=0'>", "</a>", "<a href='". add_query_arg( 'learn_more_dismiss_notification', '0' ) ."' class='wpa-dismiss-notification' style='float:right;margin-left:20px;'> ", "</a>" ),
	'updated',	'',	''
);
/**
 * Function that adds user role redirection table and custom user table
 *
 * @since v.1.1.1
 */

// create custom redirection table

function corsair_create_redirection_table()
{
	global $wpdb;
	$table_name = $wpdb->prefix .'corsair_redirection';

    #Check to see if the table exists already, if not, then create it

	if($wpdb->get_var( "show tables like '$table_name'" ) != $table_name)
	{

		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		$sql = "CREATE TABLE $table_name (
		id int NOT NULL AUTO_INCREMENT,
		redirection_url varchar(255) DEFAULT '' NOT NULL,
		url_source varchar(155) DEFAULT '' NOT NULL,
		user_role varchar(155) DEFAULT '' NOT NULL,
		status  ENUM('1','2') NOT NULL,
		PRIMARY KEY  (id)
	) $charset_collate;";

	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
}
}
register_activation_hook( __FILE__, 'corsair_create_redirection_table' );

// Deleting the table while plugin activation

function delete_corsair_redirection_table() {
	global $wpdb;
	$table_name = $wpdb->prefix.'corsair_redirection';
	$sql = "DROP TABLE IF EXISTS $table_name";
	$wpdb->query($sql);
}
register_deactivation_hook( __FILE__, 'delete_corsair_redirection_table' );
/**
* Shortcode for the corsair member view login form
*
* @since 1.1.1
*
* @return html
*/
// 236 switch user
add_shortcode('CORSAIR-TEMP-MEMBER-LOGIN-FORM','corsair_temp_member_login_form_cb');
function corsair_temp_member_login_form_cb(){
    // $before_switch_user = wp_get_current_user();
	// $before_switch_email = $before_switch_user->user_email;
	$html = "";
	ob_start();
	if( current_user_can( 'administrator' ) || current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
	?>
	<div id="corsair-login">
    	<form name="wpaloginform_switch" id="wpaloginform_switch" action="" method="post">
    		<label for="user_email"><?php echo( apply_filters('change_form_label', $label)) ; ?></label>
    		<input type="email" name="user_email" id="user_email" class="input" value="" size="25" />
    		<label class="corsair-validation-error"></label>
    		<input type="submit" name="wpa-submit" id="wpa-submit" class="button-primary" value="<?php esc_attr_e('Log In', 'corsair-login'); ?>" />
    		<?php wp_nonce_field( 'corsair_login_request_switch_temp', 'nonce', false ) ?>
    	</form>
    </div>
	<?php
	}
	$html .= ob_get_clean();
	return $html;
}
//csr holder / member wp user set login expiry time to 30min.
// add_filter( 'auth_cookie_expiration','csrholder_30min_change_cookie_logout', 10, 3 );
function csrholder_30min_change_cookie_logout( $expiration, $user_id, $remember ){
	if( user_can( $user_id, 'member' ) && ( !user_can( $user_id, 'supportmanager' ) || !user_can( $user_id, 'supportagent' ) || !user_can( $user_id, 'administrator' ) ) ){
		$expiration = 60 * 240;
	}
	return $expiration;
}
add_action('wp_ajax_idle_inactivity_logout_act', 'corsair_login_idle_inactivity_logout_act');
function corsair_login_idle_inactivity_logout_act(){
	$user = wp_get_current_user();
	$logs = sprintf( __('%s auto logged-out due to idle inactive at %s', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
	create_corsairlogin_logs_entry( $user->ID, 'auto-logout', '','member', $logs, true  );
	wp_logout();
	$out = array( 'error' => 0, 'msg' => 'success' );
	echo wp_json_encode( $out );
	exit;
}
add_shortcode('Buy-Page-ID','corsair_buypage');
function corsair_buypage(){
	$buyid = get_the_ID();
	$_SESSION['buypageid'] = $buyid;
}
include_once("inc/api_functions.php");
include_once("inc/ajax_functions.php");
require_once 'google2fa/vendor/autoload.php';
/* require_once 'simple-qrcode/vendor/autoload.php';
use SimpleSoftwareIO\QrCode\Facades\QrCode; */
/**
 * Shortcode for enable disable login authentication options
 */
add_shortcode('CORSAIR-MEMBER-LOGIN-AUTH-TYPE','corsair_member_login_auth_type_cb');
function corsair_member_login_auth_type_cb(){


	$html = "";
	$current_user = wp_get_current_user();
	$user_id = $current_user->ID;
	ob_start();
	if( is_user_logged_in() ){
		$current_user = wp_get_current_user();
		$corsair_2fa_otp = get_option( 'corsair_2fa_otp' );
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$login_auth_type = get_user_meta( $user_id, 'login_auth_type', true );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_login = get_user_meta( $user_id, 'google_auth_key_login', true );
		$google_auth_key_withdrawal = get_user_meta( $user_id, 'google_auth_key_withdrawal', true );
		$otp_auth_key = get_user_meta( $user_id, 'otp_auth_key', true );
		$total_step = 4;

		$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_login == 1 ) ? 1 : 0;
		$ga2fa_withdrawal_enabled = ( !empty( $google_auth_key ) && $google_auth_key_withdrawal == 1 ) ? 1 : 0;

	?>
	<div class="row">
		<div class="col-md-12 shadow p-3 bg-white rounded">
		<form id="users_login_authentication_option" name="users_login_authentication_option">
			<h5><?php _e('Improve your account security by enabling additional security measures.', 'corsair-login'); ?></h5><br/>
			<?php if( $corsair_2fa_otp == 'yes' ){ $gaToggle = ( !empty( $otp_auth_key ) ) ? __('Enabled', 'corsair-login') : __('Disabled', 'corsair-login'); ?>
			<div class="2fa_otp_section">
			<h5><strong><?php _e('OTP (One-Time-Passcode)', 'corsair-login'); ?></strong></h5>
			<div class="m-10">
				<div class="card-">
					<?php /*<div class="card-header d-flex justify-content-between"><div><?php _e('OTP Email Authentication', 'corsair-login'); ?></div> <div><b><?php echo $gaToggle; ?></b></div> </div>*/ ?>
					<div class="" style="padding-top: 0 !important;">
						<p class="card-text"><?php _e('One-Time-Passcode will be sent to your registered email address.') ?></p>

						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="opt_email_login" name="opt_email_login" <?php checked( 1, $otp_auth_key, true ); ?> />
							<label class="custom-control-label pt-1" for="opt_email_login"><?php _e('Login', 'corsair-login'); ?></label>
						</div>

						<div class="custom-control custom-checkbox mb-3" style="pointer-events: none;">
							<input type="checkbox" class="custom-control-input" id="opt_email_withdrawal" name="opt_email_withdrawal" checked />
							<label class="custom-control-label pt-1" for="opt_email_withdrawal"><?php _e('Withdrawal (Required)', 'corsair-login'); ?></label>
						</div>

						<?php /*if( !empty( $otp_auth_key ) ){ ?>
							<button type="button" class="btn btn-primary" id="disable_otp2fa_modal"><?php _e('Disable', 'corsair-login'); ?></button>
						<?php }else{ ?>
							<button type="button" class="btn btn-primary" id="enable_otp2fa_modal"><?php _e('Enable', 'corsair-login'); ?></button>
						<?php }*/ ?>
					</div>
				</div>
			</div>
			</div>
			<?php } ?>

			<?php if( $corsair_2fa_otp == 'yes' && $corsair_2fa_ga == 'yes' ){ ?> <br/> <?php } ?>

			<?php if( $corsair_2fa_ga == 'yes' ){ $gaToggle = ( !empty( $google_auth_key ) ) ? __('Enabled', 'corsair-login') : __('Disabled', 'corsair-login'); ?>
			<div class="2fa_ga_section">
			<h5><strong><?php _e('Google Authenticator 2FA', 'corsair-login'); ?></strong></h5>
			<div class="m-10">
				<div class="card-">

					<?php if( empty( $google_auth_key ) ){ ?>
						<p class="card-text"><?php _e('Google authenticator app is required and available for download in the next step.') ?></p>
					<?php } ?>

					<div class="" style="padding-top: 0 !important;">

						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="ga2fa_login" name="ga2fa_login" <?php checked( 1, $ga2fa_login_enabled, true ); ?> />
							<label class="custom-control-label pt-1" for="ga2fa_login"><?php _e('Login', 'corsair-login'); ?></label>
						</div>

						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="ga2fa_withdrawal" name="ga2fa_withdrawal" <?php checked( 1, $ga2fa_withdrawal_enabled, true ); ?> />
							<label class="custom-control-label pt-1" for="ga2fa_withdrawal"><?php _e('Withdrawal', 'corsair-login'); ?></label>
						</div>

						<input type="hidden" name="_micro" id="toggle2famicro" value="<?php echo wp_create_nonce('_CL_Toogle2FAMicro_LC_'); ?>" />


						<?php if( !empty( $google_auth_key ) ){ ?>
							<button type="button" class="btn btn-primary" id="disable_ga2fa_modal" data-toggle="modal" data-target="#disableGa2faModal"><?php _e('Disable', 'corsair-login'); ?></button>
							<?php /*<p class="card-text"><?php _e('Google 2FA (Withdrawals and some other secure activities are disabled for 1 working day after Google 2FA is disabled)') ?></p>*/ ?>
						<?php } ?>

						<?php /*if( !empty( $google_auth_key ) ){ ?>
							<p class="card-text"><?php _e('If you have lost access to the device used for enabling 2FA authenctication, please contact support.', 'corsair-login'); ?></p>
							<button type="button" class="btn btn-primary" id="disable_ga2fa_modal" data-toggle="modal" data-target="#disableGa2faModal"><?php _e('Disable', 'corsair-login'); ?></button>
							<?php }else{ ?>
							<p class="card-text"><?php _e('Google authenticator app is required and available for download in the next step.', 'corsair-login'); ?></p>
							<button type="button" class="btn btn-primary" id="enable_ga2fa_modal" data-toggle="modal" data-target="#enableGa2faModal"><?php _e('Enable', 'corsair-login'); ?></button>
						<?php }*/ ?>
					</div>
				</div>
			</div>
			</div>
			<?php } ?>
			<input type="hidden" name="action" value="user_login_auth_option_act" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce( '_USERS_LogiN_AuthenticatioN_OPTION_' ); ?>" />
		</form>
		</div>
	</div>

	<?php if( $corsair_2fa_otp == 'yes' && empty( $otp_auth_key ) ){ ?>
		<div class="modal fade" id="enableOTP2faModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content">
				<div class="modal-body">
				</div>
			</div>
		</div>
	</div>
	<?php } ?>
	<?php if( $corsair_2fa_otp == 'yes' && !empty( $otp_auth_key ) ){ ?>
		<div class="modal fade" id="disableOTP2faModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content">
				<div class="modal-body">
				</div>
			</div>
		</div>
	</div>
	<?php } ?>

	<?php if( $corsair_2fa_ga == 'yes' && empty( $google_auth_key ) ){ ?>
	<div class="modal fade" id="enableGa2faModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
			<div class="modal-content">
				<div class="modal-body">
				<div class="container-fluid">
					<div class="row justify-content-center">
						<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mt-0 mb-2">
							<div class="card-">
								<form name="ga2faEnableFrm" class="ga2faEnableFrm" id="msform">
								<!-- progressbar -->
									<ul id="progressbar" class="mb-3">
										<li class="active" id="fieldmapping"><strong><?php _e('Download App','corsair-login') ?></strong></li>
										<li id="fieldmapping"><strong><?php _e('Scan QR Code','corsair-login') ?></strong></li>
										<!--li id="fieldmapping"><strong><?php //_e('Backup Key','corsair-login') ?></strong></li-->
										<li id="fieldmapping"><strong><?php _e('Enable Google Authenticator','corsair-login') ?></strong></li>
										<li id="fieldmapping"><strong><?php _e('Complete','corsair-login') ?></strong></li>
									</ul>
									<div class="progress">
										<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
									</div>
									<br> <!-- fieldsets -->
									<fieldset class="step_0">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></p>
												</div>
											</div>

											<div class="row text-center justify-content-center">
												<div class="col-lg-8 col-10 pt-24">
													<h3 class="text-center">Download and install the Authenticator app</h3>
													<br>
													<div class=" row">
														<div class="col-sm-6 text-center">
															<img src="<?php echo CLOG_PLUGIN_URL;?>/assets/app-store-ga-qr-code.png">
															<p class="main_heading text-center">App Store</p>
														</div>
														<div class="col-sm-6 text-center">
															<img src="<?php echo CLOG_PLUGIN_URL;?>/assets/google-play-store-ga-qr.png">
															<p class="main_heading text-center">Android APK</p>
														</div>
													</div>
													<div class="row">
														<div class="col-sm-12">
															<p class="text-center mt-3"><b>Scan to Download</b> iOS and Android</p>
														</div>
													</div>
													<br>
												</div>
                                    		</div>

										</div>
										<input type="button" name="next" class="next_ga action-button" value="Next" />
									</fieldset>

									<fieldset class="step_1">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps mb-0"><?php echo sprintf('Step %s - %s', 2, $total_step); ?></p>
												</div>
											</div>
											<div class="row text-center justify-content-center">
											<?php
												$siteUrl = get_bloginfo('url');
												$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

												$google2fa = new \PragmaRX\Google2FA\Google2FA();
												$secret_key = $google2fa->generateSecretKey();
												$qr = $google2fa->getQRCodeUrl( $siteUrlName, $current_user->user_email, $secret_key );
												// $image_url = 'https://chart.googleapis.com/chart?cht=qr&chs=250x250&chl='.$qr;
												$_SESSION['google_auth_key'] = $secret_key;

												$image_url = add_query_arg( array(
													'qr'	=>	$qr,
													'action' => 'google2fa_qrcode',
												), admin_url('admin-ajax.php') );
											?>
											<input type="hidden" name="google_auth_key" id="google_auth_key" value="<?php echo $secret_key; ?>" />
											<div class="col-12">
												<h3 class="fs-title text-center main_heading mb-0"><?php _e('Scan this QR Code in the Authenticator app', 'corsair-login'); ?></h3>
												<img style="padding: 30px;" src="<?php echo $image_url; ?>" />
											</div>
											</div>
											<div class="row text-center justify-content-center">
												<div class="col-sm-8 pt-24">
													<h3 class="fs-title text-center main_heading"><?php _e('Save this Backup Key in secure location', 'corsair-login'); ?></h3>
												<p class="csr_color text-center"> <strong><?php echo $secret_key; ?></strong></p>
												<p class="text-center"><?php _e('If you are unable to scan the Qr Code, Please enter this code manually into the app', 'corsair-login'); ?></p>
												<div class="text-center">
													<p class="text-center mb-0"><?php _e('This key will allow you to recover your Authenticator, if you lose your phone. Otherwise, resetting Google Authenticator will take at least 7 days.', 'corsair-login'); ?></p>
												</div>
											</div>
											</div>

										</div>
										<input type="button" name="next" class="next_ga action-button" value="Next" /> <input type="button" name="previous" class="previous_ga action-button-previous" value="Previous" />
									</fieldset>

									<fieldset class="step_2">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps"><?php echo sprintf('Step %s - %s', 3, $total_step); ?></p>
												</div>
											</div>

											<div class="row justify-content-center">
											<div class="col-12">
												<h3 class="fs-title text-center main_heading"><?php _e('Enable Authenticator by verifying your account', 'corsair-login'); ?></h3>

												<div class="form-group">
													<label for="backupkey"><?php _e('Enter Backup Key', 'corsair-login'); ?></label>
													<div class="input-group-append align-items-center" id="show_hide_password">
														<input class="form-control" type="password" name="key" id="backupkey" />
														<div class="input-group-addon pl-1 pr-1"><a href="javascript:void(0);" tabindex="-1"><i class="fa fa-eye-slash" aria-hidden="true"></i></a></div>
													</div>
												</div>

												<div class="form-group">
													<label for="backupkey"><?php _e('Enter the 6-digit code generated by the Authenticator App.', 'corsair-login'); ?></label>
													<input type="number" class="form-control" name="code" placeholder="" id="init-code" maxlength="6">

												</div>

											</div>
											</div>


										</div>
										<input type="button" name="next" class="next_ga action-button" value="Next" /> <input type="button" name="previous" class="previous_ga action-button-previous" value="Previous" />
									</fieldset>

									<fieldset class="step_3">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps"><?php echo sprintf('Step %s - %s', 4, $total_step); ?></p>
												</div>
											</div>
										</div>
										<input type="button" name="next" class="next_ga action-button" value="Submit" /> <input type="button" name="previous" class="previous_ga action-button-previous" value="Previous" />
									</fieldset>
									<input type="hidden" name="action" value="googleAuth2FAactivationAct" />
									<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPGoogleAuthenticatorEnablingCIP_'); ?>" />
								</form>
							</div>
						</div>
					</div>
				</div>
				</div>
			</div>
		</div>
	</div>
	<?php }else if( $corsair_2fa_ga == 'yes' && !empty( $google_auth_key ) ){ ?>
	<div class="modal fade" id="disableGa2faModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content">
				<div class="modal-body">
				<div class="container-fluid">
					<div class="row">
						<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 p-0 mt-2 mb-2">
							<div class="card-">
								<form name="ga2faDisableFrm" class="ga2faDisableFrm">
									<div class="row">
										<div class="col-12">
											<p class="text-center main_heading"><b><?php _e('Disable Google 2FA', 'corsair-login'); ?></b></p>
											<div class="form-group">
												<label for="verify-code"><?php _e('Enter the 6-digit code generated by the Authenticator App.', 'corsair-login'); ?></label>
												<input type="number" class="form-control" name="code" placeholder="" id="verify-code" maxlength="6">

											</div>
											<input type="submit" name="submit" class="action-button" value="<?php _e('Confirm', 'corsair-login'); ?>" />
											<input type="button" name="cancel" class="action-button" data-dismiss="modal" value="<?php _e('Cancel', 'corsair-login'); ?>" />
										</div>
									</div>
									<input type="hidden" name="action" value="googleAuth2FADeactivateAct" />
									<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPGoogleAuthenticatorDisablingCIP_'); ?>" />
								</form>
							</div>
						</div>
					</div>
				</div>
				</div>
			</div>
		</div>
	</div>
	<div class="modal fade" id="disableToggleGa2faModal" tabindex="-1" role="dialog">
		<div class="modal-dialog modal-dialog-centered" role="document">
			<div class="modal-content">
				<div class="modal-body">
				<div class="container-fluid">
					<div class="row">
						<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 p-0 mt-2 mb-2">
							<div class="card-">
								<form name="ga2faDisableToggleFrm" class="ga2faDisableToggleFrm">
									<div class="row">
										<div class="col-12">
											<p class="text-center main_heading"><b><?php _e('Disable Google 2FA', 'corsair-login'); ?></b></p>
											<div class="form-group">
												<label for="verify-code"><?php _e('Enter the 6-digit code generated by the Authenticator App.', 'corsair-login'); ?></label>
												<input type="number" class="form-control" name="code" placeholder="" id="verify-code" maxlength="6">

											</div>
											<input type="submit" name="submit" class="action-button" value="<?php _e('Confirm', 'corsair-login'); ?>" />
											<input type="button" name="cancel" class="action-button" data-dismiss="modal" value="<?php _e('Cancel', 'corsair-login'); ?>" />
										</div>
									</div>
									<input type="hidden" name="action" value="disable_for_user_ga_twofa" />
									<input type="hidden" name="_micro" id="toggle2famicro" value="<?php echo wp_create_nonce('_CL_Toogle2FAMicro_LC_'); ?>" />
								</form>
							</div>
						</div>
					</div>
				</div>
				</div>
			</div>
		</div>
	</div>
	<?php } ?>
	<?php
	}
	$html .= ob_get_clean();
	return $html;
}
add_shortcode('MEMBER-LISTING-AUTHENTICATION-MANAGE', 'corsair_login_member_listing_authentication_manage_callback');
function corsair_login_member_listing_authentication_manage_callback(){
	$html = "";

		wp_enqueue_style( 'cip-css' );
		wp_enqueue_style( 'bs-table' );
		wp_enqueue_style( 'bs-sticky-header' );
		wp_enqueue_script('bs-table');
		wp_enqueue_script('bs-sticky-header');
		wp_enqueue_script('bs-table-filter-control');
		ob_start();
		?>
		<table id="cl_member_users_list" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
		<thead>
			<tr>
				<th data-field="id" class="id" data-switchable="false"><?php _e('Id','corsair-login'); ?></th>
				<th data-field="email" data-sortable="true" data-filter-control="input" class="email" data-switchable="false"><?php _e('Email','corsair-login'); ?></th>
				<th data-field="action_otp" class="action_otp"><?php _e('Email OTP','corsair-login'); ?></th>
				<th data-field="action_g2fa" class="action_g2fa"><?php _e('Google 2FA','corsair-login'); ?></th>
				<th data-field="action_reset_pw" class="action_reset_pw"><?php _e('Password','corsair-login'); ?></th>
				<th data-field="toggle_login" class="toggle_login"><?php _e('Login','corsair-login'); ?></th>
				<th data-field="toggle_withdrawal" class="toggle_withdrawal"><?php _e('Withdrawal','corsair-login'); ?></th>
				<th data-field="switch_user" class="switch_user"><?php _e('Switch User','corsair-login'); ?></th>
			</tr>
		</thead>
		<tbody>
		</tbody>
		</table>
		<?php
		$html .= ob_get_clean();

	return $html;
}
add_action('wp_footer', 'corsair_login_bsdatatable_script');
function corsair_login_bsdatatable_script(){
	$cl_member_users_list_url = add_query_arg( [
		'action'	=>	'cl_member_users_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

	$walletapiLogsUrl = add_query_arg( [
		'action'	=>	'wallet_api_logs_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	?>
	<script>
	jQuery(document).ready(function($){
		if( $('#cl_member_users_list').length > 0 ){
			var cl_member_users_list_url = "<?php echo $cl_member_users_list_url ?>";
			var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
			stickyHeaderOffset = wpadminbar;
			var $tablePendinReview = $('#cl_member_users_list');
			$tablePendinReview.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: cl_member_users_list_url,
				queryParams: function (p) {
					return {
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order,
					};
				},
				stickyHeader: false,
				stickyHeaderOffsetY: stickyHeaderOffset,
				onPostBody: function (){
					if( $('[data-toggle-tt="tooltip"]').length > 0 ){
						$('[data-toggle-tt="tooltip"]').tooltip();
					}
					$('.filter-control input.search-input').prop('readonly',false);
				},
				onSearch: function( search ){
					$('.filter-control input.search-input').prop('readonly',true);
				}
			});
		}
		if( $('#cip_logs_table').length > 0 ){
			var cip_logs_table = $('#cip_logs_table');
			var walletapiLogsUrl = "<?php echo $walletapiLogsUrl; ?>";
			cip_logs_table.bootstrapTable({
				method: 'post',
				contentType: 'application/x-www-form-urlencoded',
				url: walletapiLogsUrl,
				queryParams: function (p) {
					return {
						columnfilter: p.filter,
						limit: p.limit,
						offset: p.offset,
						sort: p.sort,
						order: p.order,
					};
				},
				stickyHeader: true,
				onPostBody: function (){

				}
			});
		}
	});
  	</script>
  <?php
}
add_action('wp_ajax_cl_member_users_list_loader','cl_member_users_list_loader_cb');
function cl_member_users_list_loader_cb(){
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'login';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';

	$args = array(
		'role__in' => array('member', 'supportagent'),
		'fields' 	=> 'ID',
		'number' 	=> $limit,
		'offset' 	=> $offset,
		'orderby'	=> $orderby,
		'order'		=> $order,
	);

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'email' ){
				$args = wp_parse_args( ['search' => "*{$filterData}*", 'search_columns' => ['user_login', 'user_email'] ], $args );
			}
		}
	}


	$memberQuery = new WP_User_Query( $args );
	$memberData = $memberQuery->get_results();
	$total_items = $memberQuery->get_total();
	$rows = array();
	if( !empty( $memberData ) ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $memberData as $user_id ){
			$memberInfo = get_userdata($user_id);
			if( $memberInfo ){

				$login_auth_type = get_user_meta( $user_id, 'login_auth_type', true );
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$otp_auth_key = get_user_meta( $user_id, 'otp_auth_key', true );

				$isLoginEnable = get_user_meta( $user_id, 'csrnow_login_enable', true );

				$currentStatus = __('Suspended', 'corsair-login');
				if( $isLoginEnable == 1 ){
					$currentStatus = __('Enabled', 'corsair-login');
				}

				$isWithdrawalSuspend = get_user_meta( $user_id, 'csrnow_withdrawal_suspend', true );

				if( $isWithdrawalSuspend != 1 ){
					$isWithdrawalSuspend = 0;
				}

				$withdrawalStatus = __('Enabled', 'corsair-login');
				if( $isWithdrawalSuspend == 1 ){
					$withdrawalStatus = __('Suspended', 'corsair-login');
				}

				//236 switch user - get current user role
				$current_user = wp_get_current_user();
				if (!empty($current_user->roles)) {
					$role = $current_user->roles;
					$currentUserSwitchable = false;

					if (in_array('switchable', $current_user->roles)) {
						$currentUserSwitchable = true;
					}
				}

				$row = array();
				$row['id'] = $sno;

				$row['email'] = $memberInfo->user_email;
				$encryptId = base64_encode( $user_id . md5('324CL_MembeR_CL324'));

				if( !empty( $otp_auth_key ) ){
					$row['action_otp'] = '<a href="javascript:void(0);" class="disable2faauth" data-toggle-tt="tooltip" data-placement="top" data-pop-title="disable email OTP" title="'.__('Disable', 'corsair-login').'" data-id="'.$encryptId.'" data-type="'.base64_encode( md5('EmailOtpReset') ).'"><i class="fas fa-undo"></i></a></a>';
				}else{
					$row['action_otp'] = '-';
				}

				if( !empty( $google_auth_key ) ){
					$row['action_g2fa'] = '<a href="javascript:void(0);" class="disable2faauth" data-toggle-tt="tooltip" data-placement="top" data-pop-title="disable google 2FA" title="'.__('Disable', 'corsair-login').'" data-id="'.$encryptId.'" data-type="'.base64_encode( md5('Google2FAReset') ).'"><i class="fas fa-undo"></i></a></a>';
				}else{
					$row['action_g2fa'] = '-';
				}

				$row['action_reset_pw'] = '<a href="javascript:void(0);" class="pwdreset" data-toggle-tt="tooltip" data-placement="top" data-pop-title="Send reset password link" title="'.__('Reset', 'corsair-login').'" data-id="'.$encryptId.'" data-type="'.base64_encode( md5('CL_SMpwdrestSM_CL') ).'"><i class="fas fa-undo"></i></a></a>';

				$row['toggle_login'] = '<div class="custom-control custom-switch toggleloginsection"><input type="checkbox" class="custom-control-input" id="toggle_'.$sno.'" name="toggle_'.$sno.'" value="'.$encryptId.'" '.checked( '1', $isLoginEnable, false ).' ><label class="custom-control-label" for="toggle_'.$sno.'">'. $currentStatus .'</label></div>';

				$row['toggle_withdrawal'] = '<div class="custom-control custom-switch togglewithdrawalsection"><input type="checkbox" class="custom-control-input" id="toggle_withdrawal_'.$sno.'" name="toggle_withdrawal_'.$sno.'" value="'.$encryptId.'" '.checked( '0', $isWithdrawalSuspend, false ).' ><label class="custom-control-label" for="toggle_withdrawal_'.$sno.'">'. $withdrawalStatus .'</label></div>';

				$nonce = wp_create_nonce('corsair_login_request_switch_temp');
				$tooltipMessage = $currentUserSwitchable ? __('Switch User', 'corsair-login') : __('You are not authorized to switch user', 'corsair-login');
				$iconClass = $currentUserSwitchable ? 'switchUser' : 'disabled';

				$row['switch_user'] = '<i class="fas fa-random ' . $iconClass . '" aria-hidden="true" data-toggle-tt="tooltip" data-placement="top" title="' . $tooltipMessage . '" data-email="' . $memberInfo->user_email . '" data-nonce="' . $nonce . '"></i>';

				$rows[] = $row;
				$sno=$sno+1;
			}
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'args'			=>	$args,
	);
	echo wp_json_encode( $out );
	exit;
}
add_shortcode( 'USER-LOGIN-INFO', 'corsair_user_login_info' );
function corsair_user_login_info( $attr ){
	$args = shortcode_atts( array(
		'type' => 'link'
	), $attr );
	$type = $args['type'];
	$html = "";
	ob_start();
	if( $type == 'info' ){
		if( is_user_logged_in() ){
			global $current_user;
			$user_name = $current_user->user_login ;
			$user_email = $current_user->user_email ;
			$user_roles = $current_user->roles;
			$user_role = array_shift($user_roles);
			$UserData = get_user_by( 'id', get_current_user_id() );
			?>
			<p class='ciphelper_user_info'><?php echo sprintf( __('Welcome, %s (%s)', 'corsair-login'), $user_email, $user_role ); ?></p><?php
		}
	}
	$html .= ob_get_clean();
	return $html;
}
add_action( 'wp_login', 'cip_clear_geolocation_session_after_login', 15, 2 );
function cip_clear_geolocation_session_after_login( $user_login, WP_User $user ){
	$_SESSION["vpnapi_geolocation"] = 0;
	unset($_SESSION["vpnapi_geolocation"]);
}
/* add_action( 'wp_login', 'cip_user_loggin_logs_cb', 10, 2 );
function cip_user_loggin_logs_cb( $user_login, WP_User $user ){
	$log_type = 'loggedin';
	create_corsairlogin_logs_entry( $user->ID, $log_type );
}
add_action( 'clear_auth_cookie', 'cip_user_loggout_logs_cb', 10 );
function cip_user_loggout_logs_cb(){
	$log_type = 'loggedout';
	$user = wp_get_current_user();
	create_corsairlogin_logs_entry( $user->ID, $log_type );
} */
function create_corsairlogin_logs_entry( $user_id = 0, $log_type = '', $extra_val = '', $user_type = '', $logs = '' , $islog = true ){ //4966
	global $wpdb;
	$logsTable = $wpdb->prefix . 'cip_logs';
	$userData = get_user_by( 'id', $user_id );

	if( in_array( "administrator", $userData->roles ) ){
		$user_type = 'sm';
		$islog = true;
	}
	if( $islog ){

		$user_roles = $userData->roles;
		$user_role = array_shift($user_roles);

		switch ($log_type) {
			case 'loggedin':
				$logs = sprintf( __('%s (%s) logged in at %s','corsair-login'),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;

			case 'loggedout':
				$logs = sprintf( __('%s (%s) logged out at %s','corsair-login'),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
		}
		$data = [
			'user_id'	=>	$user_id,
			'user_type'	=>	$user_type,
			'log_type'	=>	$log_type,
			'logs'		=>	$logs,
			'_date'		=>	date_i18n('Y-m-d H:i:s'),
		];
		$wpdb->insert(  $logsTable, $data );
	}
}
add_shortcode('ADD-LOGOUT-TIMEOUT','add_logout_timeout_cb');
function add_logout_timeout_cb()
{

	$html = "";
	$optionValue = get_option('logout_time_config');

	$sasm_logout_time_config = ( !empty( get_option('sasm_logout_time_config') ) ) ? get_option('sasm_logout_time_config') : 120;
	ob_start();
	if( is_user_logged_in() ){
	?>
	<div class="row">
		<div class="col-md-6">
			<div class="shadow m-t-3 p-3 bg-white rounded h-100">
				<form id="logout_time_config_form" name="logout_time_config_form">

					<h6>Automatic logout after period of inactivity (minutes):</h6>
					<input type="input" name="logout_time" id="logout_time_config" value="<?=$optionValue?>" class="form-control"><br />
					<button type="button" class="form-control submit_logout_time btn btn-primary">Submit</button>

					<input type="hidden" name="action" value="logout_time_config_act" />
					<input type="hidden" name="_micro" id="_micro" value="<?php echo wp_create_nonce( 'logout_time_CONFIGURATION' ); ?>" />
					<p><span class="form_response"></span></p>
				</form>
			</div>
		</div>
		<div class="col-md-6">
			<div class="shadow m-t-3 p-3 bg-white rounded h-100">
				<form id="sasm_logout_time_config_form" name="sasm_logout_time_config_form">
					<h6>SA/SM Automatic logout after period of inactivity (minutes):</h6>
					<input type="input" name="sasm_logout_time_config" id="sasm_logout_time_config" value="<?=$sasm_logout_time_config?>" class="form-control"><br />
					<button type="button" class="form-control submit_sasm_logout_time btn btn-primary">Submit</button>

					<input type="hidden" name="action" value="sasm_logout_time_config_act" />
					<input type="hidden" name="_micro" id="_micro" value="<?php echo wp_create_nonce( 'sasm_logout_time_CONFIGURATION' ); ?>" />
				</form>
			</div>
		</div>


	</div>

	<script type="text/javascript">

		const swalToast1 = Swal.mixin({
		    toast: true,
		    animation: true,
		    position: 'bottom',
		    showConfirmButton: false,
		    timer: 4000,
		});
		//for input type number remove '-'
		jQuery(document).ready(function($) {
			$("#withdrawal_suspension_minutes").on("keydown", function (e) {
				if (e.key === '-') {
					e.preventDefault();
				}
			});
			$("#withdrawal_suspension_minutes").on("input", function () {
				var v = $(this).val();
				if (v.includes('-')) {
					$(this).val(v.replace(/-/g, ""));
				}
			});
		});
		// Remove - from input
		jQuery("#logout_time_config, #sasm_logout_time_config").on("input", function () {
			var c = this.selectionStart,
				r = /-/g,
				v = $(this).val();
			if (r.test(v)) {
				$(this).val(v.replace(r, ""));
				c--;
			}
			this.setSelectionRange(c, c);
		})
		jQuery(document).on('click','.submit_logout_time',function(){
			var form = jQuery('#logout_time_config_form');

			var data = {
					action:"logout_time_config_act",
					value: form.find('#logout_time_config').val(),
					_micro: jQuery('#logout_time_config_form #_micro').val()
				};

			jQuery.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				swalToast1({ type: 'success', title: obj.message });
			});
			return false;

		});

		jQuery('body').on('click','.submit_sasm_logout_time',function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var form = jQuery('#sasm_logout_time_config_form');
			var data = jQuery(form).serialize();
			$form.block( block_config );
			jQuery.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				swalToast1({ type: 'success', title: obj.message });
				$form.unblock();
			});
			return false;
		});

	</script>

	<?php
	}
	$html .= ob_get_clean();
	return $html;
}

add_action( 'wp_ajax_logout_time_config_act', 'logout_time_config_act' );
function logout_time_config_act(){

	if(wp_verify_nonce( $_POST['_micro'],'logout_time_CONFIGURATION'))
	{
		$logout_time_config = get_option('logout_time_config');
		if(get_option('logout_time_config'))
		{
			update_option('logout_time_config', $_POST['value']);
		}
		else{
			add_option('logout_time_config', $_POST['value']);
		}
	}

	$current_user = wp_get_current_user();
	$user_id = $current_user->ID;
	$user_roles = $current_user->roles;
	$user_role = array_shift($user_roles);
	$logs = sprintf( __('%s (%s) has changed login time to %s previous value %s at %s','corsair-login'),$current_user->user_email,$user_role, $_POST['value'], $logout_time_config, date_i18n('d/m/Y H:i A') );
	create_corsairlogin_logs_entry( $user_id, 'update', '',$user_role, $logs, true  );

	$data = [
		"message"=>"Automatic logout after period of inactivity ".$_POST['value']." minutes",
		"status"=> true
	];

	echo wp_json_encode($data);
	exit;
}
add_action( 'wp_ajax_sasm_logout_time_config_act', 'sasm_logout_time_config_act' );
function sasm_logout_time_config_act(){

	if(wp_verify_nonce( $_POST['_micro'],'sasm_logout_time_CONFIGURATION')){
		$sasm_logout_time_config = get_option('sasm_logout_time_config');
		update_option('sasm_logout_time_config', $_POST['sasm_logout_time_config']);

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$user_roles = $current_user->roles;
		$user_role = array_shift($user_roles);
		$logs = sprintf( __('%s (%s) has changed SA/SM login time to %s previous value %s at %s','corsair-login'),$current_user->user_email,$user_role, $_POST['sasm_logout_time_config'], $sasm_logout_time_config, date_i18n('d/m/Y H:i A') );
		create_corsairlogin_logs_entry( $user_id, 'update', '',$user_role, $logs, true  );

		$data = [
			"message"=>"SA/SM Automatic logout after period of inactivity ".$_POST['sasm_logout_time_config']." minutes",
			"status"=> true
		];
	}


	echo wp_json_encode($data);
	exit;
}
//236 switch user Added modal to footer
add_action( 'wp_footer', 'add_popup_to_footer' );
function add_popup_to_footer() {
	?>
	<div id="user_switch_2fa" class="modal fade" role="dialog">
			<div class="modal-dialog modal-dialog-centered modal-lg">
				<!-- Modal content-->
				<div class="modal-content">
					<div class="modal-body switch_user_2fa_loader">
						<span class="modalpopup_close_btn close" data-dismiss="modal">×</span>
						<form class="user_switch_2fa_form" id="user_switch_2fa_form" name="user_switch_2fa_form">
							<div class="otp_section pb-3">
								<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
								<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
								<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
							</div>
							<button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
							<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
							<input type="hidden" name="user_to_switch" id="user_to_switch" value />
							<input type="hidden" name="user_to_switch_nonce" id="user_to_switch_nonce" value />
							<input type="hidden" name="action" value="cip_user_switch_2fa" />
							<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YCIPuser_switch_2faCIPY_'); ?>" />
						</form>
					</div>
				</div>
			</div>
		</div>
	<?php
}
//236 switch user
add_action( 'wp_ajax_cip_user_switch_2fa', 'cip_user_switch_2fa' );
function cip_user_switch_2fa(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPuser_switch_2faCIPY_' ) && $_POST['email'] !="" && $_POST['authCode'] !="" ){
		//print_r($_POST);
		$gaOTPValid = false;
		$user_id = get_current_user_id();
		$before_switch_user = wp_get_current_user();
		$before_switch_email = $before_switch_user->user_email;

		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		if( empty( $google_auth_key ) ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( !empty( $_POST['authCode'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['authCode'], 0) ){
				$gaOTPValid = true;
			}
		}
		if( $gaOTPValid === false ){
			$out = array( "error" => 1, 'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		//if 2FA is true
		if($gaOTPValid = true){

			$html = "";
			ob_start();
			global $wpdb;
			$account = ( isset( $_POST['email']) ) ? $account = sanitize_text_field( $_POST['email'] ) : false;

			$nonce = ( isset( $_POST['nonce']) ) ? $nonce = sanitize_key( $_POST['nonce'] ) : false;
			$table_name = $wpdb->prefix . get_option( 'local_custom_user_table');;
			$field_name=get_option( 'local_custom_user_field');

			if( current_user_can( 'switchable' ) && wp_verify_nonce( $nonce, 'corsair_login_request_switch_temp' ) ){
				if( $account ){
					$check_email_in_api=corsair_get_users_from_sourceapi($account);
					if( $check_email_in_api==true ){
						$validEmail = true;
					}else{
						$validEmail = false;
						$tableNameArr = explode( ',', get_option( 'local_custom_user_table') );
						$fieldNameArr = explode( ',', get_option( 'local_custom_user_field') );
						if( $tableNameArr ){
							foreach( $tableNameArr as $key => $tableNameLoop ){
								if( !$validEmail ){
									$table_name = $wpdb->prefix . $tableNameLoop;
									$field_name=get_option( 'local_custom_user_field');
									$validEmail = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE ".$fieldNameArr[$key]." = '" . $account . "'") > 0 ? true : false;
								}
							}
						}

						//$validEmail = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE ".$field_name." = '" . $account . "'") > 0 ? true : false;
					}

					if( $validEmail != true && check_local_user()==true){
						if( email_exists( $account )) {
							$wpUser = get_user_by( 'email', $account );
							if( $wpUser instanceof WP_User ) {
								$validEmail = true;
							}
						}
					}
					//email is not in db
					if( $validEmail != true){
						//echo '<p class="wpa-box wpa-error">Invalid email</p>';
							$out = array( "error" => 1,'msg' => __('Invalid email',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
					}else{
						$_SESSION['refAccount'] = $account;
						$_SESSION['isSwitch'] = 'Yes';
						$_SESSION['beforeSwitchEmail'] = $before_switch_email;
						$current_user = wp_get_current_user();
						$user_id = $current_user->ID;
						$logs = sprintf( __('%s switched login to %s at %s', 'corsair-login'), $current_user->user_email, $account, date_i18n('d/m/Y H:i A') );
						create_corsairlogin_logs_entry( $user_id, 'switch', '','member', $logs, true  );
					}
				}
			}
		}


		$out = array( "error" => 0,'auth_verified' => $gaOTPValid, "msg" => 'success');
	}
	echo wp_json_encode( $out );
	exit;
}
add_filter( 'send_email_change_email', '__return_false' );

add_filter('wp_nav_menu_items', 'do_shortcode'); //enable shortcode working in menu
add_shortcode('CORSAIR-SWITCH-BACK-FROM-TEMP-MEMBER-LOGIN', 'corsair_switch_back_from_temp_member_login_cb');
function corsair_switch_back_from_temp_member_login_cb() {

    //member email - Admin switch from admin -> member
    $switchedUserEmail = isset($_SESSION['refAccount']) ? $_SESSION['refAccount'] : '';
	//admin email - Admin switch back from member -> admin
    $switchBackUserEmail = isset($_SESSION['beforeSwitchEmail']) ? $_SESSION['beforeSwitchEmail'] : '';
    $nonce = isset($_POST['nonce']) ? $_POST['nonce'] : '';

    if (current_user_can('switchable') && wp_verify_nonce($nonce, 'corsair_switch_back_from_temp_member') && $switchBackUserEmail != '') {
        $_SESSION['refAccount'] = $switchBackUserEmail;
		unset($_SESSION['beforeSwitchEmail']);
		unset($_SESSION['isSwitch']); //unset because it was set "yes" when switch
        $current_user = wp_get_current_user();
        $user_id = $current_user->ID;
        $logs = sprintf(__('User %s switched back to %s at %s', 'corsair-login'), $switchedUserEmail, $switchBackUserEmail, date_i18n('d/m/Y H:i A'));
        create_corsairlogin_logs_entry($user_id, 'switch back', '', 'member', $logs, true);
        wp_redirect('/content/testing/switch/');
        exit;
    }

    // Show the form if the session variable exists
    if (isset($_SESSION['beforeSwitchEmail']) && $_SESSION['beforeSwitchEmail'] != '') {
		ob_start();
        ?>
        <div id="corsair-switch-back-from-temp-user">
            <form name="wpaTemp_user_switch_back" id="wpaTemp_user_switch_back" action="" method="post">
                <input type="submit" name="wpa-submit" id="wpa-submit" class="button-primary switch_back_member" value="<?php esc_attr_e('Switch Back', 'corsair-login'); ?>" />
                <?php wp_nonce_field('corsair_switch_back_from_temp_member', 'nonce', false); ?>
            </form>
        </div>
        <?php
		return ob_get_clean();
    }
	return '';
}


add_action('template_redirect', function() {
    // Check if the current request is for wp-admin or wp-login.php
    if (is_admin() && !is_user_logged_in()) {
        wp_redirect(home_url('/content/main/lobby/'));
        exit;
    }
});

add_action('login_init', function() {
    // Redirect from wp-login.php if the user is not logged in
    if (!is_user_logged_in()) {
		if( !isset( $_GET['action'] ) && $_GET['action'] != 'rp' ){
			wp_redirect(home_url('/content/main/lobby/'));
			exit;
		}
    }
});